
local timeInit = 0
local initTimer = math.random()	-- only used when object is placed down.
								-- this will prevent a dozen objects being placed down at the same time from starting to calculate
								-- the TimeWarp all at the same moment, give your potato a break and spread the cpu load a bit :)
local Now = 0
local StartingMinute = 0
local EndingMinute = 0

local myMapSize = "UNKNOWN"
local mySlowTime = "UNKNOWN"

local myTimeWarpFactor = 0
local timeWarpFound = false

local timeTot = 0

local Get = Object.GetProperty
local Set = Object.SetProperty
local Find = Object.GetNearbyObjects

local presents = {"Bed","BunkBed","SuperiorBed","Toilet","Table","Chair","Bench","JailDoor","JailDoorLarge","Door","StaffDoor","SolitaryDoor","RemoteDoor","Window","WindowLarge","Tree","Cooker","Fridge","Bin","Sink","ServingTable","ShowerHead","Bookshelf","OfficeDesk","SchoolDesk","FilingCabinet","MedicalBed","MorgueSlab","PowerStation","Capacitor","PowerSwitch","WaterPumpStation","WaterBoiler","PipeValve","Sprinkler","Drain","MetalDetector","WeightsBench","PhoneBooth","Tv","LargeTv","PoolTable","Cctv","CctvMonitor","DoorControlSystem","PhoneMonitor","Servo","DoorTimer","LogicCircuit","LogicBridge","PressurePad","StatusLight","LaundryMachine","WorkshopSaw","WorkshopPress","CarpenterTable","IroningBoard","LaundryBasket","VisitorTable","VisitorTableSecure","DogCrate","GuardLocker","WeaponRack","SofaChairSingle","SofaChairDouble","DrinkMachine","ArcadeCabinet","Radio","Altar","Pews","PrayerMat","SortingTable","ShopFront","GuardTower","Radiator","InvisibleLightSpawner","DefaultLightSpawner","TLLightSpawner","LightBulbSpawner","OutdoorLightSpawner","GardenLightSpawner","ServerSpawner","ServerParts","ServerPartsRack","ClassroomPCSpawner","FreeTimeEcoComputerSpawner","FreeTimeComputerStandardSpawner","FreeTimeThinClientSpawner","FreeTimeLaptopStandardSpawner","FreeTimeComputerDeluxeSpawner","FreeTimeLearningComputerSpawner","PrinterTonerSmall","PrinterTonerLarge","PrinterDrumkitSmall","PrinterDrumkitLarge","PrinterPaperSmall","PrinterPaperLarge","BoringFilingCabinet","WorkThinClientSpawner","NetworkPrinterTinySpawner","NetworkPrinterSmallSpawner","NetworkPrinterLargeSpawner","AdminDeskSpawner","OfficeChair","HQFilingCabinet","MaterialDuper","ElectricRadiator","SmallBench","MiniBench","SmallTable","WoodenWindow","WoodenWindowLarge","GlassWindow","SuperiorTable","SuperiorBench","SmallWoodenSink","SmallSink","IroningBoard","SmallIroningBoard","YogaMat","GraveStoneSpawner","CoffinTable","SmallTableMorgue","SmallTableFP","ParlourChair","ParlourAltar","Crematorium","Candelabra","ChurchStatue","ChurchWindow","OakDesk","OakBookShelf","BookShelfLarge","HiddenDoor","LeatherChair","CigaretteMachine","UrinalPreview","NiceToiletAPreview","NiceToiletBPreview","TurkishDrainPreview","ToiletDry","Urinal","NiceToilet","NiceToilet2","TurkishDrain","WallSinkPreview","WallSink","MedicalBedLarge","MedicineCabinet","FirstAidBox","Eeg","IntravenousPole","FireExtinguisher","WaterTank","FiremanLocker","FiremanShowerHead","CashBack","StaffDoorWood","StaffDoorMin","StaffDoorMed","StaffDoorMax","StaffDoorProt","ToughStaffDoor","StaffDoorDeathRow","StaffDoorShared","JailDoorXL","BlastDoor","ModernDoor","HeavyDoor","HeavyDoorLarge","SolitaryDoorMin","SolitaryDoorMed","SolitaryDoorMax","SolitaryDoorProt","SolitaryDoorSuper","SolitaryDoorDeathRow","SolitaryDoorShared","RoadFenceWhite","RoadFenceGreen","RoadFenceBlue","RoadFenceOrange","RoadFenceRed","RoadFenceYellow","StaffFenceWhite","StaffFenceGreen","StaffFenceBlue","StaffFenceOrange","StaffFenceRed","StaffFenceYellow","WaterFountain","WaterCooler","StorageRack","CoffeeVendingMachine","FruitVendingMachine","SandwichVendingMachine","SnackVendingMachine","WaterVendingMachine","JuiceTable","OrangeJuicer","CoolingUnit","ForestryTreeSapling","WoodSaw","MetalStorageRack","LogStorageRack","WoodStorageRack","BarberChair","BarberChairScripted","BarberMirror","BlondBarberPress","BrownBarberPress","RedBarberPress","CircuitIsolator","BasketballBench","BasketballBasket","BasketballLocker","BoxingRing","SpeedBag","ControlBooth","ControlBoothMedium","ControlBoothLarge","SmartPhoneDetector","RiggedPhoneSpawner","PhonePress","PhoneTable","SmallTablePhoneWorkshop","AluminiumStorageRack","TrashBin10","TrashBin20","TrashBin30","RecycleBin","TrashCompactor","RecycleDeskSpawner","SmallGardenTable","SmallGardenBench","FenceBush","FoliagePlantA","FoliagePlantB","FoliagePlantC","FoliagePlantD","FoliagePlantE","FoliagePlantF","FoliagePlantG","FoliagePlantH","FlowersA","FlowersB","FlowersC","FlowersD","FlowersE","FlowersShared","FlowersMinsec","FlowersMedsec","FlowersMaxsec","FlowersPrsec","Bush1","Bush2","Buxus","SmallBuxus","FlowerPot1","FlowerPot2","FlowerPot3","FlowerPot4","FlowerPot5","FlowerPot6","Tulips1","Tulips2","Tulips3","Tulips4","BeeBox","SmallGardenTableFerti","GardenPotRemoteTomato","GardenPotRemoteCucumber","GardenPotRemoteRose","GardenPotRemoteLily","GardenPotRemoteIngredients","GardenPotRemotePotatoes","GardenPlantControlSpawner","ShedSpawner","AppleTree","CherryTree","OrangeTree","SmallTableManufactury","SewingStation","TextileMill","SmallGardenTablePlantation","CottonPlantSpawner","CottonPlantControlSpawner","SmallGardenTableCotton","SaunaBench","TeslaMatic2","TeslaMatic2b","MoneyTable","MoneySafe","ChinookPadDelivery","ChinookPadExports","ChinookIntakeTerminal","ChinookDeliveryTerminal","ChinookLandingStripSpawner","ZoneDesignator","ServoProxy","StatusLightProxy","RoadSensor","HalfRoadSensor","BoomBox","PingPongTable","CoffeeTable","DiningChair","DiningTable","SofaBlueLeft","SofaBlueRight","Sofa","SofaRight","SofaChair","SofaBeige","SofaBrown","LivingRoomTV","HouseDoor","BathTub","Cupboard","VanityTable","Mirror","BedsideCab1","BedsideCab2","DoubleBed","EvacBench","EvacChair","ExplosiveCharge666","Detonator666","BorderChanger","SmallRoadGate","BusStopSign","RoadMarker","StreetLightLeft","StreetLightRight","TrafficLightLeft","TrafficLightRight","BusStop","PrisonSign","MailBox","ExitSign","Hydrant","ElegantCar","CopCar","RedCar","BlackLimo","BlueLimo","RedLimo","PrisonerTruck","MedicalTruck","RiotTruck","ArmyTruck","FireTruck","CarTruck","CargoTruck","stopsign","parkingsign","NumberOne","NumberTwo","NumberThree","NumberFour","NumberFive","NumberSix","NumberSeven","NumberEight","NumberNine","NumberZero","ATag","BTag","CTag","DTag","ETag","FTag","GTag","HTag","ITag","JTag","KTag","LTag","MTag","NTag","OTag","PTag","QTag","RTag","STag","TTag","UTag","VTag","WTag","XTag","YTag","ZTag","EntryTag","ExitTag","1tileArrow","2tileArrow","3tileArrow","4tileArrow","5tileArrow","MinTag","MedTag","MaxTag","SuperTag","SuperTag","DeathRowTag","CellBlockTag","HoldingTag","DormitoryTag","FamilyCellTag","NurseryTag","SolitaryTag","StaffTag","AccountantTag","ChiefTag","ForemanTag","LawyerTag","OfficeTag","PsychologistTag","WardenTag","ArmouryTag","BarberyTag","BasketballCourtTag","BoxingTag","CanteenTag","CarpentryWorkshopTag","ChapelTag","ClassroomTag","CleaningTag","ColdStorageTag","CottonPlantationTag","CommonTag","DeliveriesTag","EvacuationTag","ExecutionTag","ExportsTag","GarageTag","GarbageTag","GardenTag","GreenhouseTag","ForestryTag","InfirmaryTag","KennelTag","KitchenTag","LandingZoneTag","LaundryTag","LibraryTag","MailRoomTag","ManufacturyTag","MorgueTag","OfficeTag","ParkingZoneTag","ParoleTag","PhoneWorkshopTag","ReceptionTag","RecyclingTag","SecurityTag","SaunaTag","ShopTag","ShowerTag","StaffTag","StaffRoomTag","StaffToiletsTag","StorageTag","TherapyTag","ToiletsTag","UtilityRoomTag","VisitationTag","WaterPumpTag","WaterPumpTag","YardTag","YogaroomTag","WorkshopTag","LockdownTag","PermanentTag","PowerTag","BackupTag","NoEntryTag"}

local entityGroup = { "Prisoner", "Workman", "Guard", "ArmedGuard",
				"Orderly", "Cook", "Gardener", "Janitor",
				"DogHandler", "Sniper", "Chief",
				"Foreman", "Psychologist", "Psychiatrist", "Accountant",
				"Lawyer", "Farmer", "SystemAdministrator", "ComputerNerd",
				"SimulationOfficeManager", "YogaMaster",
				"GraveDigger", "VendingManager",
				"ForestryWorker", "BarberChief",
				"Barber",
				"CarMechanic2", "CraneOperator2",
				"GardenWorker", "GreenhouseWorker", "PlantationWorker", "Tailor",
				"SmartPhoneGenius", "R4_GardenWorker", "R4_GreenhouseWorker",
				"R4_RecyclingWorker", "M4_PlantationWorker", "M4_Tailor",
				"TeslaMaticExpert", "ShadyTeslaDude",
				"TeslaMaticExpert3", "ShadyTeslaDude3",
				"PrisonFireman2Chief",
				"PrisonFiremanT1M1","PrisonFiremanT1M2","PrisonFiremanT1M3","PrisonFiremanT1M4",
				"PrisonFiremanT2M1","PrisonFiremanT2M2","PrisonFiremanT2M3","PrisonFiremanT2M4",
				"PrisonFiremanT3M1","PrisonFiremanT3M2","PrisonFiremanT3M3","PrisonFiremanT3M4",
				"PrisonFiremanT4M1","PrisonFiremanT4M2","PrisonFiremanT4M3","PrisonFiremanT4M4",
				"PrisonFiremanT5M1","PrisonFiremanT5M2","PrisonFiremanT5M3","PrisonFiremanT5M4",
				"PrisonFiremanT6M1","PrisonFiremanT6M2","PrisonFiremanT6M3","PrisonFiremanT6M4",
				"PrisonFiremanT7M1","PrisonFiremanT7M2","PrisonFiremanT7M3","PrisonFiremanT7M4",
				"PrisonFiremanT8M1","PrisonFiremanT8M2","PrisonFiremanT8M3","PrisonFiremanT8M4",
				"PrisonFiremanT9M1","PrisonFiremanT9M2","PrisonFiremanT9M3","PrisonFiremanT9M4",
				"PrisonFiremanT10M1","PrisonFiremanT10M2","PrisonFiremanT10M3","PrisonFiremanT10M4",
				"PrisonFiremanT11M1","PrisonFiremanT11M2","PrisonFiremanT11M3","PrisonFiremanT11M4",
				"PrisonFiremanT12M1","PrisonFiremanT12M2","PrisonFiremanT12M3","PrisonFiremanT12M4",
				"PrisonFiremanT13M1","PrisonFiremanT13M2","PrisonFiremanT13M3","PrisonFiremanT13M4",
				"PrisonFiremanT14M1","PrisonFiremanT14M2","PrisonFiremanT14M3","PrisonFiremanT14M4",
				"PrisonFiremanT15M1","PrisonFiremanT15M2","PrisonFiremanT15M3","PrisonFiremanT15M4",
				"PrisonFiremanT16M1","PrisonFiremanT16M2","PrisonFiremanT16M3","PrisonFiremanT16M4",
				"PrisonFiremanT17M1","PrisonFiremanT17M2","PrisonFiremanT17M3","PrisonFiremanT17M4",
				"PrisonFiremanT18M1","PrisonFiremanT18M2","PrisonFiremanT18M3","PrisonFiremanT18M4",
				"PrisonFiremanT19M1","PrisonFiremanT19M2","PrisonFiremanT19M3","PrisonFiremanT19M4",
				"PrisonFiremanT20M1","PrisonFiremanT20M2","PrisonFiremanT20M3","PrisonFiremanT20M4",
				"PrisonFiremanT21M1","PrisonFiremanT21M2","PrisonFiremanT21M3","PrisonFiremanT21M4",
				"PrisonFiremanT22M1","PrisonFiremanT22M2","PrisonFiremanT22M3","PrisonFiremanT22M4",
				"PrisonFiremanT23M1","PrisonFiremanT23M2","PrisonFiremanT23M3","PrisonFiremanT23M4",
				"PrisonFiremanT24M1","PrisonFiremanT24M2","PrisonFiremanT24M3","PrisonFiremanT24M4",
				"PrisonFiremanT25M1","PrisonFiremanT25M2","PrisonFiremanT25M3","PrisonFiremanT25M4",
				"PrisonFiremanT26M1","PrisonFiremanT26M2","PrisonFiremanT26M3","PrisonFiremanT26M4",
				"PrisonFiremanA0", "PrisonFiremanA1", "PrisonFiremanA2", "PrisonFiremanA3", "PrisonFiremanB0", "PrisonFiremanB1", "PrisonFiremanB2", "PrisonFiremanB3",
				"PrisonFiremanC0", "PrisonFiremanC1", "PrisonFiremanC2", "PrisonFiremanC3", "PrisonFiremanD0", "PrisonFiremanD1", "PrisonFiremanD2", "PrisonFiremanD3"
				 }

						
local ContrabandList = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 25, 28, 29, 30, 32, 33, 37, 42, 43, 44, 45, 46, 47 }

local GunsList = { 7, 42, 32, 45, }

local timeTotDayCheck = 0
local timePerDayCheck = 15
local timeToRiot = 0
local timeToMakePrisonersMad = 40

local cashCollected = 0
local prisonersNo = 0
local prisonersYes = 0
local prisonersNotSure = 0
local candidates = 0
local totalPrisoners = 0
local totalPrisonerMoney = 0

function Create()
	AdjustToWall = true
	Set(this,"TicketsSoldRequired",1000)
	Set(this,"CapacityMultiplier",2)
	Set(this,"TicketsSold",0)
	Set(this,"TotalStake",0)
	Set(this,"LastStake",0)
	Set(this,"Outcome","reportTooltip_VM2LotteryOutcome7")
	Set(this,"LotteryStart",math.floor(World.TimeIndex))
	
	currentDay = math.ceil(World.TimeIndex/1440)
	NextSpringStartsOnDay = (currentDay + (28 - math.mod(currentDay,28)))
	Set(this,"NextLotteryDay",NextSpringStartsOnDay - currentDay)
	daysUntilNextLottery = NextSpringStartsOnDay - currentDay
	
	Set(this,"LotteryDaysInterval",28)
	
	this.HasCustomReport = true
end

function FindOtherSafe()
	local nearbySafes = Find(this,"VendingLotterySafe",10000)
	if next(nearbySafes) then
		for thatSafe, dist in pairs(nearbySafes) do
			if thatSafe.Id.i ~= this.Id.i then
				if not Get(thatSafe,"LotteryCountdownStarted") then
					if thatSafe.SubType == 2 or thatSafe.SubType == 3 then	-- if both safes are Prison Safes, then takeover values
						if this.SubType == 2 then
							Set(this,"NextLotteryDay",thatSafe.NextLotteryDay)
							Set(this,"TicketsSold",thatSafe.TicketsSold)
							Set(this,"CapacityMultiplier",thatSafe.CapacityMultiplier)
							Set(this,"TicketsSoldRequired",thatSafe.TicketsSoldRequired)
							Set(this,"TotalStake",thatSafe.TotalStake)
							Set(this,"LastStake",thatSafe.LastStake)
							Set(this,"Outcome",thatSafe.Outcome)
							Set(this,"LotteryStart",thatSafe.LotteryStart)
							Set(this,"PrisonersPersuaded",thatSafe.PrisonersPersuaded)
						end
					elseif thatSafe.SubType == 0 or thatSafe.SubType == 1 then	-- if both safes are sylvester Safes, then takeover values
						if this.SubType == 0 then
							Set(this,"NextLotteryDay",thatSafe.NextLotteryDay)
							Set(this,"TicketsSold",thatSafe.TicketsSold)
							Set(this,"TicketsSoldRequired",1000)
							Set(this,"TotalStake",thatSafe.TotalStake)
							Set(this,"LastStake",thatSafe.LastStake)
							Set(this,"Outcome",thatSafe.Outcome)
							Set(this,"LotteryStart",thatSafe.LotteryStart)
							Set(this,"PrisonersPersuaded",thatSafe.PrisonersPersuaded)
						end
					end															-- else don't takeover values from other safe
					
					thatSafe.Delete()
				else
					this.Delete()
				end
			end
		end
	end
	Set(this,"FindOtherSafeDone",true)
end

function FindWarden()
	local nearbyWarden = Find(this,"Warden",10000)
	if next(nearbyWarden) then
		for thatWarden, dist in pairs(nearbyWarden) do
			MyWarden = thatWarden
		end
	end
end

function KeepMyWardenLoaded()
	if MyWarden == nil or MyWarden.SubType == nil then
		local nearbyWarden = Find(this,"Warden",10000)
		if next(nearbyWarden) then
			for thatWarden, dist in pairs(nearbyWarden) do
				MyWarden = thatWarden
			end
		end
		if MyWarden == nil or MyWarden.SubType == nil then 
			MyWarden = Object.Spawn("Warden",this.Pos.x-1,this.Pos.y+0.5)
			Set(MyWarden,"CarrierId.i",this.Slot3.i)
			Set(MyWarden,"CarrierId.u",this.Slot3.u)
			Set(MyWarden,"Loaded",true)
			Set(this,"Slot3.i",MyWarden.Id.i)
			Set(this,"Slot3.u",MyWarden.Id.u)
		end
	end
end

function FindLotteryOfficial()
	if MyLotteryOfficial == nil or MyLotteryOfficial.SubType == nil then 
		local nearbyLotteryOfficial = Find(this,"LotteryOfficial",10000)
		if next(nearbyLotteryOfficial) then
			for thatLotteryOfficial, dist in pairs(nearbyLotteryOfficial) do
				MyLotteryOfficial = thatLotteryOfficial
			end
		end
		if MyLotteryOfficial == nil or MyLotteryOfficial.SubType == nil then 
			MyLotteryOfficial = Object.Spawn("LotteryOfficial",this.Pos.x,this.Pos.y+1)
		end
	end
end

function SpawnGift(theType,theItem,theQuantity)
	local present = Object.Spawn(theType, this.Pos.x-1+math.random()+math.random(), this.Pos.y+0.5+math.random())
	if theQuantity ~= nil then present.Quantity = theQuantity end
	if theItem ~= nil then
		local BoxNr = 0
		for i = 1,2000 do
			Set(present,"Contents",i)
			if present.Contents == theItem then
				BoxNr = i
			end
			if BoxNr > 0 then
				break
			end
		end
		Set(present,"Tooltip","tooltip_VM2PresentWonAtLottery")
	else
		if theType == "PrisonLotterySuperJackpot" then
			Set(present,"Cash",10000)
			Set(present,"Tooltip","tooltip_VM2LotterySuperJackpot")
		elseif theType == "PrisonLotteryMegaJackpot" then
			Set(present,"Cash",100000)
			Set(present,"Tooltip","tooltip_VM2LotteryMegaJackpot")
		elseif theType == "SylvesterLotterySuperJackpot" then
			Set(present,"Cash",100000)
			Set(present,"Tooltip","tooltip_VM2SylvesterSuperJackpot")
		elseif theType == "SylvesterLotteryMegaJackpot" then
			Set(present,"Cash",4500000)
			Set(present,"Tooltip","tooltip_VM2SylvesterMegaJackpot")
		elseif theType == "Win5000" then
			Set(present,"Tooltip","tooltip_VM2Win5000")
		elseif theType == "Lost5000" then
			Set(present,"Tooltip","tooltip_VM2Lost5000")
		end
		if theType == "PrisonLotterySuperJackpot" or theType == "PrisonLotteryMegaJackpot" or theType == "SylvesterLotterySuperJackpot" or theType == "SylvesterLotteryMegaJackpot" then
			if MyWarden == nil or MyWarden.SubType == nil then FindWarden() end
			if MyWarden ~= nil and MyWarden.SubType ~= nil then
				Set(MyWarden,"Carrying.i",present.Id.i)
				Set(MyWarden,"Carrying.u",present.Id.u)
				Set(present,"CarrierId.i",MyWarden.Id.i)
				Set(present,"CarrierId.u",MyWarden.Id.u)
				Set(present,"Carried",4)
				if theType == "PrisonLotterySuperJackpot" or theType == "SylvesterLotterySuperJackpot" then
					MyWarden.Tooltip = { "tooltip_VM2WardenCarriesJackpotSuper",WithComma(this.Jackpot),"J" }
				elseif theType == "PrisonLotteryMegaJackpot" or theType == "SylvesterLotteryMegaJackpot" then
					MyWarden.Tooltip = { "tooltip_VM2WardenCarriesJackpotMega",WithComma(this.Jackpot),"J" }
				end
			end
		end
	end
end

function SpawnRoomInventory()
	local rndNr = math.random(1,26)
	if rndNr == 1 then
		local roomToSpawn = { "Bed", "Toilet", "JailDoor", "Bookshelf", "Tv", "Window", "Radio", "OfficeDesk", "Chair", "ShowerHead", "Drain" }	-- cell
		for i = 1, #roomToSpawn do
			SpawnGift("Box",roomToSpawn[i])
		end
	elseif rndNr == 2 then
		local roomToSpawn = { "Bench", "Toilet", "ShowerHead", "Drain", "PhoneBooth", "Bed" }	-- holdingcell
		for i = 1, #roomToSpawn do
			SpawnGift("Box",roomToSpawn[i])
		end
	elseif rndNr == 3 then
		local roomToSpawn = { "Bed", "BunkBed", "Toilet", "JailDoor", "Bookshelf", "Tv", "Window", "Radio", "PoolTable", "PhoneBooth", "ShowerHead", "Drain" }	-- dormitory
		for i = 1, #roomToSpawn do
			SpawnGift("Box",roomToSpawn[i])
		end
	elseif rndNr == 4 then
		local roomToSpawn = { "ServingTable", "Table", "Bench", "Bin" }	-- canteen
		for i = 1, #roomToSpawn do
			SpawnGift("Box",roomToSpawn[i])
		end
	elseif rndNr == 5 then
		local roomToSpawn = { "Cooker", "Fridge", "Sink", "Bin", "StaffDoor" }	-- kitchen
		for i = 1, #roomToSpawn do
			SpawnGift("Box",roomToSpawn[i])
		end
	elseif rndNr == 6 then
		local roomToSpawn = { "ShowerHead" }	-- shower
		for i = 1, #roomToSpawn do
			SpawnGift("Box",roomToSpawn[i])
		end
	elseif rndNr == 7 then
		local roomToSpawn = { "WeightsBench", "PhoneBooth" }	-- yard
		for i = 1, #roomToSpawn do
			SpawnGift("Box",roomToSpawn[i])
		end
	elseif rndNr == 8 then
		local roomToSpawn = { "OfficeDesk", "Table", "Chair" }	--intake
		for i = 1, #roomToSpawn do
			SpawnGift("Box",roomToSpawn[i])
		end
	elseif rndNr == 9 then
		local roomToSpawn = { "WorkshopSaw", "WorkshopPress", "Table", "CarpenterTable" }	-- workshop
		for i = 1, #roomToSpawn do
			SpawnGift("Box",roomToSpawn[i])
		end
	elseif rndNr == 10 then
		local roomToSpawn = { "OfficeDesk", "Chair", "FilingCabinet", "CctvMonitor", "DoorControlSystem", "PhoneMonitor" }	-- security
		for i = 1, #roomToSpawn do
			SpawnGift("Box",roomToSpawn[i])
		end
	elseif rndNr == 11 then
		local roomToSpawn = { "OfficeDesk", "Chair", "FilingCabinet", "StaffDoor" }	-- office
		for i = 1, #roomToSpawn do
			SpawnGift("Box",roomToSpawn[i])
		end
	elseif rndNr == 12 then
		local roomToSpawn = { "MedicalBed" }	-- infirmary
		for i = 1, #roomToSpawn do
			SpawnGift("Box",roomToSpawn[i])
		end
	elseif rndNr == 13 then
		local roomToSpawn = { "MorgueSlab" }	-- morgue
		for i = 1, #roomToSpawn do
			SpawnGift("Box",roomToSpawn[i])
		end
	elseif rndNr == 14 then
		local roomToSpawn = { "Bench", "PoolTable", "TvLarge", "TvSmall" }	-- commonroom
		for i = 1, #roomToSpawn do
			SpawnGift("Box",roomToSpawn[i])
		end
	elseif rndNr == 15 then
		local roomToSpawn = { "LaundryMachine", "LaundryBasket", "IroningBoard", "Table" }	--laundry
		for i = 1, #roomToSpawn do
			SpawnGift("Box",roomToSpawn[i])
		end
	elseif rndNr == 16 then
		local roomToSpawn = { "VisitorTable", "VisitorTableSecure" }	-- visitation
		for i = 1, #roomToSpawn do
			SpawnGift("Box",roomToSpawn[i])
		end
	elseif rndNr == 17 then
		local roomToSpawn = { "VisitorTable" }	-- parole
		for i = 1, #roomToSpawn do
			SpawnGift("Box",roomToSpawn[i])
		end
	elseif rndNr == 18 then
		local roomToSpawn = { "SolitaryDoor" }	-- solitary
		for i = 1, #roomToSpawn do
			SpawnGift("Box",roomToSpawn[i])
		end
	elseif rndNr == 19 then
		local roomToSpawn = { "DogCrate" }	-- kennel
		for i = 1, #roomToSpawn do
			SpawnGift("Box",roomToSpawn[i])
		end
	elseif rndNr == 20 then
		local roomToSpawn = { "WeaponRack", "GuardLocker", "Table" }	--armoury
		for i = 1, #roomToSpawn do
			SpawnGift("Box",roomToSpawn[i])
		end
	elseif rndNr == 21 then
		local roomToSpawn = { "SofaChairDouble", "DrinkMachine", "Radio", "ArcadeCabinet", "SofaChairSingle", "Toilet", "LargeTv", "SmallTv", "ServingTable" }	-- staffroom
		for i = 1, #roomToSpawn do
			SpawnGift("Box",roomToSpawn[i])
		end
	elseif rndNr == 22 then
		local roomToSpawn = { "LibraryBookshelf", "SortingTable" }	-- library
		for i = 1, #roomToSpawn do
			SpawnGift("Box",roomToSpawn[i])
		end
	elseif rndNr == 23 then
		local roomToSpawn = { "SchoolDesk", "OfficeDesk" }	-- classroom
		for i = 1, #roomToSpawn do
			SpawnGift("Box",roomToSpawn[i])
		end
	elseif rndNr == 24 then
		local roomToSpawn = { "Altar", "Pews", "PrayerMat" }	-- chapel
		for i = 1, #roomToSpawn do
			SpawnGift("Box",roomToSpawn[i])
		end
	elseif rndNr == 25 then
		local roomToSpawn = { "SortingTable", "Table" }	-- mailroom
		for i = 1, #roomToSpawn do
			SpawnGift("Box",roomToSpawn[i])
		end
	elseif rndNr == 26 then
		local roomToSpawn = { "Table", "ShopShelf", "ShopFront" }	-- shop
		for i = 1, #roomToSpawn do
			SpawnGift("Box",roomToSpawn[i])
		end
	end
end

function DoTheLotteryCountdown()		-- added interval to see the jackpot filling up while CollectLotteryCash() is busy
	timePerUpdate = 0.15 / myTimeWarpFactor
	KeepMyWardenLoaded()
	if CollectLotteryCash() == true then
		this.LotteryCountdownFinished = true
		if this.SubType == 1 or this.SubType == 3 then this.SubType = this.SubType - 1 end
		StartLotteryClicked()
		Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
	end
end

function CollectLotteryCash()		-- grab all the cash from the floor which has not been brought to the safe yet, but do it 1 at a time
	local cashFound = false
	if pendingVendingMachines == nil then pendingVendingMachines = Find(this,"VendingMachineLottery",10000) end
	for thatVending, dist in pairs(pendingVendingMachines) do		-- grab temp stored stake amount which hasn't been turned into VendingLotteryStake yet
		if thatVending.StoredStake > 0 then
			cashFound = true
			Set(this,"TotalStake",Get(this,"TotalStake") + Get(thatVending,"StoredStake"))
			Set(thatVending,"StoredStake",0)
			Interface.SetComponentProperties( "TotalStake", { Replacements = { A = WithComma( this.TotalStake ) } } )
			break
		end
	end
	if cashFound == false then
		if pendingVendingLotteryStakes == nil then pendingVendingLotteryStakes = Find(this,"VendingLotteryStake",10000) end
		for thatStake, dist in pairs(pendingVendingLotteryStakes) do	-- grab VendingLotteryStake from the Lottery Vault room which hasn't been brought to this safe yet
			cashFound = true
			Set(this,"TotalStake",Get(this,"TotalStake") + Get(thatVending,"StoredStake"))
			thatStake.Delete()
			Interface.SetComponentProperties( "TotalStake", { Replacements = { A = WithComma( this.TotalStake ) } } )
			break
		end
	end
	if cashFound == false then
		pendingVendingMachines = nil
		pendingVendingLotteryStakes = nil
		return true
	end
end

-- function CollectLotteryCash()		-- grab all the cash from the floor which has not been brought to the safe yet, but do it 1 at a time
	-- local cashFound = false
	-- if pendingLotteryCash == nil then pendingLotteryCash = Find(this,"Stack",10000) end
	-- for thatLotteryCash, dist in pairs(pendingLotteryCash) do
		-- if thatLotteryCash.Contents == "VendingLotteryCash" then
			-- cashFound = true
			-- Set(this,"TotalStake",Get(this,"TotalStake") + Get(thatLotteryCash,"Quantity"))
			-- thatLotteryCash.Delete()
			-- Interface.SetComponentProperties( "TotalStake", { Replacements = { A = WithComma( this.TotalStake ) } } )
			-- break
		-- end
	-- end
	-- if cashFound == false then
		-- pendingLotteryCash = nil
		-- return true
	-- end
-- end

function StartLotteryClicked()
	ResetLotteryVendings()
	Set(this,"LotteryEnd",math.floor(World.TimeIndex))
	Set(this,"WinningTicket",math.floor(math.random(this.LotteryStart,this.LotteryEnd)))
	Set(this,"LotteryDone",true)
	ScrollThroughTicketNumbers()
end

function ResetLotteryVendings()
	local nearbyVendings = Find(this,"TicketVendingMachine",10000)
	for thatVending, dist in pairs(nearbyVendings) do
		if not this.WeeklyLottery then
			thatVending.SubType = 0
		else
			thatVending.SubType = 1
		end
	end
	nearbyVendings = nil
end

function BuildSoldTicketsList()
	this.WeHaveAWinner = false
	LotteryTicketsSold = { }
	TotalValidTickets = 0
	CurrentTicketShown = 0
	for _, typ in pairs(entityGroup) do
		local entityType = Find(this,typ,10000)
		for thatEntity, _ in pairs(entityType) do
			if Get(thatEntity,"TicketsBought") ~= nil then
				for i=1,thatEntity.TicketsBought do
					--print("Checking ticket "..i.." with number "..Get(thatEntity,"T"..i).." of "..thatEntity.Type.." "..thatEntity.Id.i)
					LotteryTicketsSold[TotalValidTickets] = Get(thatEntity,"T"..i)
					ValidOrFake = "reportTooltip_VM2LotterySoldTicketValid"
					if not this.WeHaveAWinner and Get(thatEntity,"T"..i) == this.WinningTicket then
						LotteryWinner = thatEntity
						this.WeHaveAWinner = true
						--print("            THE WINNER IS: "..thatEntity.Type.." "..thatEntity.Id.i)
					elseif this.WeHaveAWinner == true and Get(thatEntity,"T"..i) == this.WinningTicket then
						ValidOrFake = "reportTooltip_VM2LotterySoldTicketFake"
					end
					TotalValidTickets = TotalValidTickets + 1
				end
				
				if entityType == "Prisoner" then
					if this.OtherWinner1 == nil and thatEntity.Needs.Food ~= nil and thatEntity.Needs.Food > 1 then
						Set(this,"OtherWinner1","Prisoner "..thatEntity.Id.i)
						Set(this,"OtherWinner1ID",thatEntity.Id.i)
						TheOtherWinner1 = thatEntity
					elseif this.OtherWinner2 == nil and thatEntity.Needs.Enviroment ~= nil and thatEntity.Needs.Enviroment > 1 then
						Set(this,"OtherWinner2","Prisoner "..thatEntity.Id.i)
						Set(this,"OtherWinner2ID",thatEntity.Id.i)
						TheOtherWinner2 = thatEntity
					elseif this.OtherWinner3 == nil and thatEntity.Needs.Freedom ~= nil and thatEntity.Needs.Freedom > 1 then
						Set(this,"OtherWinner3","Prisoner "..thatEntity.Id.i)
						Set(this,"OtherWinner3ID",thatEntity.Id.i)
						TheOtherWinner3 = thatEntity
					elseif this.OtherWinner4 == nil and thatEntity.Needs.Drugs ~= nil and thatEntity.Needs.Drugs > 1 then
						Set(this,"OtherWinner4","Prisoner "..thatEntity.Id.i)
						Set(this,"OtherWinner4ID",thatEntity.Id.i)
						TheOtherWinner4 = thatEntity
					elseif this.OtherWinner5 == nil and thatEntity.Needs.Alcohol ~= nil and thatEntity.Needs.Alcohol > 1 then
						Set(this,"OtherWinner5","Prisoner "..thatEntity.Id.i)
						Set(this,"OtherWinner5ID",thatEntity.Id.i)
						TheOtherWinner5 = thatEntity
					elseif this.OtherWinner6 == nil and thatEntity.Needs.Privacy ~= nil and thatEntity.Needs.Privacy > 1 then
						Set(this,"OtherWinner6","Prisoner "..thatEntity.Id.i)
						Set(this,"OtherWinner6ID",thatEntity.Id.i)
						TheOtherWinner6 = thatEntity
					end
				end
			end
		end
	end
	if TotalValidTickets == 0 then this.NoTicketsWereSold = true end
	if this.WeHaveAWinner == true then
		if LotteryWinner.Type == "Prisoner" then
			Set(this,"theLotteryWinner","reportTooltip_VM2LotteryWinnerPrisoner")
			Set(this,"TicketWasSold","reportTooltip_VM2LotterySoldTicketSold")
			Set(this,"Outcome","reportTooltip_VM2LotteryOutcome4")
		else
			LotteryWinner.Tooltip = "Has won $"..WithComma( this.TotalStake ).." and resigned instantly"
			LotteryWinner.LeaveMap()
			Set(this,"theLotteryWinner","reportTooltip_VM2LotteryWinnerStaffMember")
			Set(this,"TicketWasSold","reportTooltip_VM2LotterySoldTicketSold")
			Set(this,"Outcome","reportTooltip_VM2LotteryOutcome16")
		end
	else
		Set(this,"TicketWasSold","reportTooltip_VM2LotterySoldTicketNotSold")
		Set(this,"theLotteryWinner","reportTooltip_VM2LotteryWinnerWarden")
		Set(this,"Outcome","reportTooltip_VM2LotteryOutcome1")
	end
	timePerUpdate = 0.005 / myTimeWarpFactor
end

function ScrollThroughTicketNumbers()
	KeepMyWardenLoaded()
	if CurrentTicketShown == nil then BuildSoldTicketsList() end
	--print("showing "..CurrentTicketShown.." of "..TotalValidTickets)
	if this.StartedTicketsValidating then
		Object.CancelJob(this,"StartValidatingTickets")
		if not this.ValidatingTheTickets then
			if MyLotteryOfficial == nil or MyLotteryOfficial.SubType == nil then
				FindLotteryOfficial()
			end
			Object.CreateJob(this,"ValidateTickets")
		else
			if not this.ValidatingInterface then
				Interface.SetComponentProperties( "JackpotWinnerA", { Caption = "reportTooltip_VM2LotteryJackpotWinnerA", Replacements = { T = tostring( this.WinningTicket ), S = "reportTooltip_VM2LotterySoldTicketPending" } } )
			
				Interface.SetComponentProperties( "TicketValidation", { Replacements = { V = "reportTooltip_VM2LotterySoldTicketValidating" } } )
				this.ValidatingInterface = true
				if TotalValidTickets > 1000 then ShowFirstPart = 250 else ShowFirstPart = math.floor(TotalValidTickets / 4) end
				if TotalValidTickets - 150 > ShowFirstPart then ShowLastPart = TotalValidTickets - 150 else ShowLastPart = math.floor(TotalValidTickets * 0.75) end
			end
			Object.CreateJob(this,"ValidateTickets")
			if CurrentTicketShown < ShowFirstPart or (CurrentTicketShown >= ShowLastPart and CurrentTicketShown < TotalValidTickets) then
				timePerUpdate = 0.005 / myTimeWarpFactor
				Interface.SetComponentProperties( "ScrollingTickets", { Caption = "reportTooltip_VM2LotterySoldTicketNumber", Replacements = { C = tostring( CurrentTicketShown ), T = tostring( LotteryTicketsSold[CurrentTicketShown] ), V = tostring( ValidOrFake ) } } )
				CurrentTicketShown = CurrentTicketShown + 1
			elseif CurrentTicketShown >= ShowFirstPart and CurrentTicketShown < ShowLastPart then
				timePerUpdate = 0.75 / myTimeWarpFactor
				Interface.SetComponentProperties( "ScrollingTickets", { Caption = "reportTooltip_VM2LotterySoldTicketAFewMomentsLater" } )
				CurrentTicketShown = math.ceil(ShowLastPart)
				Object.CreateJob(this,"ValidateTickets")
			elseif CurrentTicketShown >= TotalValidTickets then
				this.ValidatingInterface = nil
				Interface.SetComponentProperties( "TicketValidation", { Replacements = { V = "reportTooltip_VM2LotterySoldTicketValidated" } } )
				Object.CancelJob(this,"ValidateTickets")
				this.ValidatingTheTickets = nil
				this.TicketsAreValidated = true
				
				Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
				
				if MyLotteryOfficial == nil or MyLotteryOfficial.SubType == nil then
					FindLotteryOfficial()
				end
				MyLotteryOfficial.Or.x = 0
				MyLotteryOfficial.Or.y = 1
				MyLotteryOfficial.NavigateTo(this.Pos.x-1+math.random()+math.random()+math.random(), this.Pos.y+0.5+math.random())
				
				LotteryTicketsSold = nil
				--print("reached "..CurrentTicketShown.." of "..TotalValidTickets)
				Set(this,"SoldTicketsListShown",true)
				if this.YourOwnBetPressedObject == true and not this.NoTicketsWereSold then
					if this.YourBetWinner == this.theLotteryWinner then
						if not this.MusicFxDisabled then this.Sound("__FoodFeud","FamilySuccession2") end
						if this.YourBetObject == "$ 5,000" or this.YourBetObject == "$5000" then
							SpawnGift("Win5000")
						else
							SpawnGift("Box","PowerStation")
						end
					else
						if not this.MusicFxDisabled then this.Sound("__ConvictionMorgan","MorganMusic4") end
						if this.YourBetObject == "$ 5,000" or this.YourBetObject == "$5000" then
							SpawnGift("Lost5000")
						else
							RndRemove("PowerStation")
						end
					end
				end
				Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
			end
		end
	else
		if MyLotteryOfficial == nil or MyLotteryOfficial.SubType == nil then
			FindLotteryOfficial()
		end
		Object.CreateJob(this,"StartValidatingTickets")
	end
end

function StartAftermath()
	if not this.YourBetResultShown then
		KeepMyWardenLoaded()
		return
	else
		this.ContinuedToResults = true
		LotteryOutcome()
		if this.WeHaveAWinner == false then
			if TotalValidTickets > 0 then
			--	timePerUpdate = 40									-- time for some music before the riot starts...
			--	timeToMakePrisonersMad = 40
				timeToRiot = 0
				timePerUpdate = 0
			end
		else
		--	timePerUpdate = 10 / myTimeWarpFactor
			timePerUpdate = 0
		end
		timeTot = 0
	end
end

function ResetPrisonerNeeds(thePrisoner)
	thePrisoner.StatusEffects.angst = 0
	thePrisoner.StatusEffects.suppressed  = 0
	thePrisoner.Needs.Bowels = 0
	thePrisoner.Needs.Bladder = 0
	thePrisoner.Needs.Clothing = 0
	thePrisoner.Needs.Comfort = 0
	thePrisoner.Needs.Enviroment = 0
	thePrisoner.Needs.Exercise = 0
	thePrisoner.Needs.Family = 0
	thePrisoner.Needs.Food = 0
	thePrisoner.Needs.Freedom = 0
	thePrisoner.Needs.Hygiene = 0
	thePrisoner.Needs.Literacy = 0
	thePrisoner.Needs.Privacy = 0
	thePrisoner.Needs.Recreation = 0
	thePrisoner.Needs.Safety = 0
	thePrisoner.Needs.Spirituality = 0
	thePrisoner.Needs.Warmth = 0
	thePrisoner.Needs.Luxuries = 0
	thePrisoner.Needs.Drugs = 0
	thePrisoner.Needs.Alcohol = 0
	thePrisoner.Needs.Barbery = 0
	thePrisoner.BoilingPoint = 0
end

function GiveOtherWinnersPrize(theNumber)
	if theNumber == 1 then
		if TheOtherWinner1 == nil then
			TheOtherWinner1 = getObject("Prisoner",this.OtherWinner1ID,10000)
		end
		if TheOtherWinner1 ~= nil then
		
			ResetPrisonerNeeds(TheOtherWinner1)
			
			TheOtherWinner1.StatusEffects.goodfood = 720
			TheOtherWinner1.Tooltip = "Winner1"
			--TheOtherWinner1.Pos.x,TheOtherWinner1.Pos.y = this.Pos.x,this.Pos.y+1
			--print("Winner 1 is at safe")
		end
	elseif theNumber == 2 then
		if TheOtherWinner2 == nil then
			TheOtherWinner2 = getObject("Prisoner",this.OtherWinner2ID,10000)
		end
		if TheOtherWinner2 ~= nil then
		
			ResetPrisonerNeeds(TheOtherWinner2)
			
			TheOtherWinner2.Tooltip = "Winner2"
			--TheOtherWinner2.Pos.x,TheOtherWinner2.Pos.y = this.Pos.x,this.Pos.y+1
			--print("Winner 2 is at safe")
		end
	elseif theNumber == 3 then
		if TheOtherWinner3 == nil then
			TheOtherWinner3 = getObject("Prisoner",this.OtherWinner3ID,10000)
		end
		if TheOtherWinner3 ~= nil then
		
			ResetPrisonerNeeds(TheOtherWinner3)
			
			TheOtherWinner3.Needs.Freedom = 200
			TheOtherWinner3.BoilingPoint = 100
			TheOtherWinner3.Misbehavior = 2
			TheOtherWinner3.Tooltip = "Winner3"
			--TheOtherWinner3.Pos.x,TheOtherWinner3.Pos.y = this.Pos.x,this.Pos.y+1
			--print("Winner 3 is at safe")
		end
	elseif theNumber == 4 then
		if TheOtherWinner4 == nil then
			TheOtherWinner4 = getObject("Prisoner",this.OtherWinner4ID,10000)
		end
		if TheOtherWinner4 ~= nil then
		
			ResetPrisonerNeeds(TheOtherWinner4)
			
			TheOtherWinner4.Needs.Drugs = 0
			if math.random() > 0.25 then
				TheOtherWinner4.StatusEffects.high = 60
			else
				TheOtherWinner4.StatusEffects.overdosed = 60
			end
			TheOtherWinner4.Tooltip = "Winner4"
			--TheOtherWinner4.Pos.x,TheOtherWinner4.Pos.y = this.Pos.x,this.Pos.y+1
			--print("Winner 4 is at safe")
		end
	elseif theNumber == 5 then
		if TheOtherWinner5 == nil then
			TheOtherWinner5 = getObject("Prisoner",this.OtherWinner5ID,10000)
		end
		if TheOtherWinner5 ~= nil then
		
			ResetPrisonerNeeds(TheOtherWinner5)

			TheOtherWinner5.Needs.Alcohol = 0
			TheOtherWinner5.StatusEffects.drunk = 60
			TheOtherWinner5.Tooltip = "Winner5"
			--TheOtherWinner5.Pos.x,TheOtherWinner5.Pos.y = this.Pos.x,this.Pos.y+1
			--print("Winner 5 is at safe")
		end
	elseif theNumber == 6 then
		if TheOtherWinner6 == nil then
			TheOtherWinner6 = getObject("Prisoner",this.OtherWinner6ID,10000)
		end
		if TheOtherWinner6 ~= nil then
		
			ResetPrisonerNeeds(TheOtherWinner6)

			TheOtherWinner6.Equipment = 2
			TheOtherWinner6.BoilingPoint = 100
			TheOtherWinner6.Misbehavior = 4
			TheOtherWinner6.Tooltip = "Winner6"
			--TheOtherWinner6.Pos.x,TheOtherWinner6.Pos.y = this.Pos.x,this.Pos.y+1
			--print("Winner 6 is at safe")
		end
	end
end

function LotteryOutcome()
	if not this.MusicFxDisabled then this.Sound("__FoodFeud","FamilySuccession1") end
	if this.WeHaveAWinner == true then									-- prisoner wins
		if not this.WeeklyLottery then									-- Sylvester Lottery
			local rndNr = math.random(1,100)							-- gimme da gift
			if rndNr < 22 then
				Set(this,"TotalStake",Get(this,"TotalStake") + 4500000)
				Set(this,"Outcome","reportTooltip_VM2LotteryOutcome5")
			elseif rndNr >= 22 and rndNr < 33 then
				SpawnRoomInventory()
			elseif rndNr >= 33 and rndNr < 44 then
				SpawnGift("Box",presents[math.random(#presents)])
			elseif rndNr >= 44 and rndNr < 55 then
				SpawnGift("Box","PowerStation")
			elseif rndNr >= 55 and rndNr < 66 then
				SpawnGift("Box","WaterPumpStation")
			elseif rndNr == 66 then
				Set(this,"TotalStake",Get(this,"TotalStake") + 10000000)
				Set(this,"Outcome","reportTooltip_VM2LotteryOutcome6")
			elseif rndNr > 66 and  rndNr < 77 then
				SpawnGift("Box",presents[math.random(#presents)])
			elseif rndNr >= 77 and rndNr < 88 then
				SpawnGift("Box","PowerStation")
			elseif rndNr >= 88 then
				SpawnGift("Box","WaterPumpStation")
			end
		else															-- Normal Lottery
			local rndNr = math.random(1,100)							-- gimme da gift
			if rndNr < 22 then
				Set(this,"TotalStake",Get(this,"TotalStake") + 1000000)
				Set(this,"Outcome","reportTooltip_VM2LotteryOutcome5")
			elseif rndNr >= 22 and rndNr < 33 then
				SpawnRoomInventory()
			elseif rndNr >= 33 and rndNr < 44 then
				SpawnGift("Box",presents[math.random(#presents)])
			elseif rndNr >= 44 and rndNr < 55 then
				SpawnGift("Box","PowerStation")
			elseif rndNr >= 55 and rndNr < 66 then
				SpawnGift("Box","WaterPumpStation")
			elseif rndNr == 66 then
				Set(this,"TotalStake",Get(this,"TotalStake") + 4500000)
				Set(this,"Outcome","reportTooltip_VM2LotteryOutcome6")
			elseif rndNr > 66 and  rndNr < 77 then
				SpawnGift("Box",presents[math.random(#presents)])
			elseif rndNr >= 77 and rndNr < 88 then
				SpawnGift("Box","PowerStation")
			elseif rndNr >= 88 then
				SpawnGift("Box","WaterPumpStation")
			end
		end
		if LotteryWinner.Type == "Prisoner" then
			LotteryWinner.AvailableMoney = LotteryWinner.AvailableMoney + this.TotalStake
			MyLotteryWinnerMarker = Object.Spawn("VendingLotteryWinnerMarker",LotteryWinner.Pos.x,LotteryWinner.Pos.y)
			Set(MyLotteryWinnerMarker,"Winner","Prisoner")
			Set(MyLotteryWinnerMarker,"WinnerID",LotteryWinner.Id.i)
			Set(MyLotteryWinnerMarker,"Tooltip","tooltip_VM2LotteryWinnerMarker")
		else
			if this.Outcome == "reportTooltip_VM2LotteryOutcome5" then
				Set(this,"Outcome","reportTooltip_VM2LotteryOutcome17")
			end
			if this.Outcome == "reportTooltip_VM2LotteryOutcome6" then
				Set(this,"Outcome","reportTooltip_VM2LotteryOutcome18")
			end
		end
		Set(this,"Jackpot",this.TotalStake)
		if this.WeeklyLottery == true then 
			Set(MyLotteryWinnerMarker,"WeeklyLottery",true)
		end
		if MyWarden == nil or MyWarden.SubType == nil then FindWarden() end
		if MyWarden ~= nil and MyWarden.SubType ~= nil then
			Set(this,"Slot3.i",-1)
			Set(this,"Slot3.u",-1)
			Set(MyWarden,"CarrierId.i",-1)
			Set(MyWarden,"CarrierId.u",-1)
			Set(MyWarden,"Loaded",false)
			MyWarden.NavigateTo(this.Pos.x,this.Pos.y+1)
		end
	elseif not this.NoTicketsWereSold then								-- warden wins
		Set(this,"Jackpot",this.TotalStake)
		if MyWarden == nil or MyWarden.SubType == nil then FindWarden() end
		if MyWarden ~= nil and MyWarden.SubType ~= nil then
			Set(MyWarden,"Jackpot",this.Jackpot)
			MyWarden.Tooltip = { "tooltip_VM2WardenCarriesJackpot",WithComma(this.Jackpot),"J" }
		end
		--SpawnGift("Stack","LotteryJackpot",this.TotalStake)				-- gimme da moneeyyy
		if not this.WeeklyLottery then									-- Sylvester Lottery
			local rndNr = math.random(1,100)								-- gimme da gift
			if rndNr < 22 then
				SpawnGift("SylvesterLotterySuperJackpot")
				Set(this,"Outcome","reportTooltip_VM2LotteryOutcome2")
			elseif rndNr >= 22 and rndNr < 33 then
				SpawnRoomInventory()
			elseif rndNr >= 33 and rndNr < 44 then
				SpawnGift("Box",presents[math.random(#presents)])
			elseif rndNr >= 44 and rndNr < 55 then
				SpawnGift("Box","PowerStation")
			elseif rndNr >= 55 and rndNr < 66 then
				SpawnGift("Box","WaterPumpStation")
			elseif rndNr == 66 then
				SpawnGift("SylvesterLotteryMegaJackpot")
				Set(this,"Outcome","reportTooltip_VM2LotteryOutcome3")
			elseif rndNr > 66 and  rndNr < 77 then
				SpawnGift("Box",presents[math.random(#presents)])
			elseif rndNr >= 77 and rndNr < 88 then
				SpawnGift("Box","PowerStation")
			elseif rndNr >= 88 then
				SpawnGift("Box","WaterPumpStation")
			elseif rndNr == 99 then
				if math.random() > 0.5 then
					SpawnGift("SylvesterLotterySuperJackpot")
					Set(this,"Outcome","reportTooltip_VM2LotteryOutcome2")
				else
					SpawnGift("SylvesterLotteryMegaJackpot")
					Set(this,"Outcome","reportTooltip_VM2LotteryOutcome3")
				end
			end
		else																-- Normal Lottery
			local rndNr = math.random(1,100)								-- gimme da gift
			if rndNr < 22 then
				SpawnGift("PrisonLotterySuperJackpot")
				Set(this,"Outcome","reportTooltip_VM2LotteryOutcome2")
			elseif rndNr >= 22 and rndNr < 33 then
				SpawnRoomInventory()
			elseif rndNr >= 33 and rndNr < 44 then
				SpawnGift("Box",presents[math.random(#presents)])
			elseif rndNr >= 44 and rndNr < 55 then
				SpawnGift("Box","PowerStation")
			elseif rndNr >= 55 and rndNr < 66 then
				SpawnGift("Box","WaterPumpStation")
			elseif rndNr == 66 then
				SpawnGift("PrisonLotteryMegaJackpot")
				Set(this,"Outcome","reportTooltip_VM2LotteryOutcome3")
			elseif rndNr > 66 and  rndNr < 77 then
				SpawnGift("Box",presents[math.random(#presents)])
			elseif rndNr >= 77 and rndNr < 88 then
				SpawnGift("Box","PowerStation")
			elseif rndNr >= 88 then
				SpawnGift("Box","WaterPumpStation")
			end
		end
		if MyWarden ~= nil and MyWarden.SubType ~= nil then
			MyWarden.Energy = 0		-- send him to a staffroom, so he has to walk in the prison
			Set(this,"Slot3.i",-1)
			Set(this,"Slot3.u",-1)
			Set(MyWarden,"CarrierId.i",-1)
			Set(MyWarden,"CarrierId.u",-1)
			Set(MyWarden,"Loaded",false)
			MyWarden.NavigateTo(this.Pos.x,this.Pos.y+1)
			MyLotteryWinnerMarker = Object.Spawn("VendingLotteryWinnerMarker",MyWarden.Pos.x,MyWarden.Pos.y)
			Set(MyLotteryWinnerMarker,"Jackpot",this.Jackpot)
			Set(MyLotteryWinnerMarker,"Winner","Warden")
			Set(MyLotteryWinnerMarker,"WinnerID",MyWarden.Id.i)
			if this.WeeklyLottery == true then 
				Set(MyLotteryWinnerMarker,"WeeklyLottery",true)
			end
		end
	else																-- no tickets sold (testing only)
		Set(this,"Jackpot","reportTooltip_VM2LotteryWinnerZeroCash")
		Set(this,"TicketWasSold","reportTooltip_VM2LotterySoldTicketNotSold")
		Set(this,"theLotteryWinner","reportTooltip_VM2LotteryWinnerNobody")
		Set(this,"Outcome","reportTooltip_VM2LotteryOutcome7")
		if MyWarden == nil or MyWarden.SubType == nil then FindWarden() end
		if MyWarden ~= nil and MyWarden.SubType ~= nil then
			Set(this,"Slot3.i",-1)
			Set(this,"Slot3.u",-1)
			Set(MyWarden,"CarrierId.i",-1)
			Set(MyWarden,"CarrierId.u",-1)
			Set(MyWarden,"Loaded",false)
			MyWarden.NavigateTo(this.Pos.x,this.Pos.y+1)
		end
	end
	local otherWinners = { "Warden","Foreman","Accountant","Lawyer","Chief","Psychologist","Workman","Cook","Janitor","Guard","Armed Guard","Doctor","Dog Handler","Dog","Gardener","Truck Driver","Teacher","Parole Officer","Parole Lawyer","Appeals Magistrate", "Orderly", "Psychiatrist" }
	if this.OtherWinner1 == nil then this.OtherWinner1 = otherWinners[math.random(#otherWinners)] else GiveOtherWinnersPrize(1) end
	if this.OtherWinner2 == nil then this.OtherWinner2 = otherWinners[math.random(#otherWinners)] else GiveOtherWinnersPrize(2) end
	if this.OtherWinner3 == nil then this.OtherWinner3 = otherWinners[math.random(#otherWinners)] else GiveOtherWinnersPrize(3) end
	if this.OtherWinner4 == nil then this.OtherWinner4 = otherWinners[math.random(#otherWinners)] else GiveOtherWinnersPrize(4) end
	if this.OtherWinner5 == nil then this.OtherWinner5 = otherWinners[math.random(#otherWinners)] else GiveOtherWinnersPrize(5) end
	if this.OtherWinner6 == nil then this.OtherWinner6 = otherWinners[math.random(#otherWinners)] else GiveOtherWinnersPrize(6) end
	
	if MyLotteryOfficial == nil or MyLotteryOfficial.SubType == nil then
		FindLotteryOfficial()
		MyLotteryOfficial.LeaveMap()
	else
		MyLotteryOfficial.LeaveMap()
	end
				
	Set(this,"LastStake",0)
	Set(this,"TotalStake",0)
	Set(this,"TicketsSold",0)
	Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
	if not this.WeeklyLottery then
		Set(this,"Tooltip","tooltip_VM2LotteryDone")
	else
		Set(this,"Tooltip","tooltip_VM2LotteryDoneWeekly")
	end
end

function MakePrisonersMad()
	if Get(this,"theLotteryWinner") == "reportTooltip_VM2LotteryWinnerWarden" and (not Get(this,"JackpotDonated") or (Get(this,"JackpotDonated") == true and Get(this,"JackpotUnavailable") == true or Get(this,"JackpotUnfair") == true )) then					-- uh oh...
		nearbyPrisoners = Find(this,"Prisoner",10000)
		if next(nearbyPrisoners) then							-- prisoners notice they got screwed...
			for thatPrisoner, dist in pairs(nearbyPrisoners) do	-- those who bought ticket will riot, and if warden wins SUPER/MEGA JACKPOT as well then all prisoners will riot
				if Get(thatPrisoner,"TicketsBought") ~= nil or Get(this,"Outcome") == "reportTooltip_VM2LotteryOutcome2" or Get(this,"Outcome") == "reportTooltip_VM2LotteryOutcome3" then
					thatPrisoner.StatusEffects.angst = 2500
					thatPrisoner.StatusEffects.suppressed  = 0
					thatPrisoner.Needs.Bowels = 200
					thatPrisoner.Needs.Bladder = 200
					thatPrisoner.Needs.Clothing = 200
					thatPrisoner.Needs.Comfort = 200
					thatPrisoner.Needs.Enviroment = 200
					thatPrisoner.Needs.Exercise = 200
					thatPrisoner.Needs.Family = 200
					thatPrisoner.Needs.Food = 200
					thatPrisoner.Needs.Freedom = 200
					thatPrisoner.Needs.Hygiene = 200
					thatPrisoner.Needs.Literacy = 200
					thatPrisoner.Needs.Privacy = 200
					thatPrisoner.Needs.Recreation = 200
					thatPrisoner.Needs.Safety = 200
					thatPrisoner.Needs.Spirituality = 200
					thatPrisoner.Needs.Warmth = 200
					thatPrisoner.Needs.Luxuries = 200
					thatPrisoner.Needs.Drugs = 200
					thatPrisoner.Needs.Alcohol = 200
					thatPrisoner.Needs.Barbery = 200
					thatPrisoner.BoilingPoint = 100
					thatPrisoner.Equipment = ContrabandList[math.random(#ContrabandList)]
					thatPrisoner.Misbehavior = 6
					if math.random() > 0.85 then
						local newFire = Object.Spawn("Fire",thatPrisoner.Pos.x-3+math.random()+math.random()+math.random(),thatPrisoner.Pos.y-3+math.random()+math.random()+math.random())
					end
				end
			end
		end
		nearbyPrisoners = nil
	end
	timePerUpdate = 0.25 / myTimeWarpFactor
	timeTot = 0
	Set(this,"PrisonersMad",true)
end

function GiveGuardsGuns()
	if Get(this,"theLotteryWinner") == "reportTooltip_VM2LotteryWinnerWarden" and (not Get(this,"JackpotDonated") or (Get(this,"JackpotDonated") == true and Get(this,"JackpotUnavailable") == true or Get(this,"JackpotUnfair") == true )) then
		local nearbyGuards = Find(this,"Guard",10000)
		if next(nearbyGuards) then
			for thatGuard, dist in pairs(nearbyGuards) do
				if math.random() > 0.5 then
					thatGuard.Equipment = 45					-- give assault rifle
				else
					thatGuard.Equipment = 46					-- give uzi
				end
			end
		end
		nearbyGuards = nil
		local nearbyDogHandlers = Find(this,"DogHandler",10000)
		if next(nearbyDogHandlers) then
			for DogHandler, dist in pairs(nearbyDogHandlers) do
				if math.random() > 0.5 then
					DogHandler.Equipment = 45
				else
					DogHandler.Equipment = 46
				end
			end
		end
		nearbyDogHandlers = nil
		local nearbyArmedGuards = Find(this,"ArmedGuard",10000)
		if next(nearbyArmedGuards) then
			for thatArmedGuard, dist in pairs(nearbyArmedGuards) do
				if math.random() > 0.5 then
					thatArmedGuard.Equipment = 45
				else
					thatArmedGuard.Equipment = 46
				end
			end
		end
		nearbyArmedGuards = nil
		timePerUpdate = 0
		if MyWarden == nil or MyWarden.SubType == nil then FindWarden() end
		Set(this,"Slot1.i",-1)
		Set(this,"Slot1.u",-1)
		Set(MyWarden,"CarrierId.i",-1)
		Set(MyWarden,"CarrierId.u",-1)
		Set(MyWarden,"Loaded",false)
	elseif Get(this,"theLotteryWinner") == "reportTooltip_VM2LotteryWinnerNobody" then
		timePerUpdate = 10 / myTimeWarpFactor
	else
		timePerUpdate = 0
	end
	Set(this,"GuardGunsUpgraded",true)
end

function Update(timePassed)
	if this.TimeWarp == nil then
		if not this.FindOtherSafeDone then FindOtherSafe() end
		Set(this,"TimeWarp",World.TimeWarpFactor)
		if AdjustToWall == true and Get(this,"Walls.y") == -1 then this.Pos.y = this.Pos.y-0.5 end
		Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
		return
	elseif timePerUpdate == nil then
		myTimeWarpFactor = World.TimeWarpFactor
		FindWarden()
		if not this.LotteryDone then
			timePerUpdate = 0
		elseif not this.LeftoversRemoved then
			timePerUpdate = 0.5 / myTimeWarpFactor
		elseif not this.PrisonersMad then
			timePerUpdate = 3 / myTimeWarpFactor
		elseif not this.GuardGunsUpgraded then
			timePerUpdate = 0.5 / myTimeWarpFactor
		else
			timePerUpdate = 0.25 / myTimeWarpFactor
		end
		
		timePerDayCheck = 15 / myTimeWarpFactor
		if this.WeeklyLottery == true then
			CheckWeeklyLotteryDay()
		else
			if this.NextLotteryDay == nil then
				--print("NextLotteryDay == nil, updating safe")
				currentDay = math.ceil(World.TimeIndex/1440)
				--print("day: "..currentDay)
				NextSpringStartsOnDay = (currentDay + (28 - math.mod(currentDay,28)))
				--print("NextSpringStartsOnDay: "..NextSpringStartsOnDay)
				Set(this,"NextLotteryDay",NextSpringStartsOnDay - currentDay)
				--print("NextLotteryDay: "..this.NextLotteryDay)
				daysUntilNextLottery = NextSpringStartsOnDay - currentDay
			end
			CheckSylvesterLotteryDay()
			Interface.SetComponentProperties( "TicketsSoldRequired", { Replacements = { X = WithComma( this.TicketsSoldRequired ) } } )
		end
		Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
		
		ResetLotteryVendings()	-- change subtype according to which safe was placed
	end
	
	timeTot= timeTot + timePassed
	timeTotDayCheck = timeTotDayCheck + timePassed
	if timeTot > timePerUpdate then
		timeTot=0
		if not this.LotteryCountdownStarted then
			GatherLotteryCash()
		elseif not this.LotteryCountdownFinished then
			GatherLotteryCash()
			DoTheLotteryCountdown()
		elseif not this.SoldTicketsListShown then
			ScrollThroughTicketNumbers()
		elseif not this.ContinuedToResults then
			StartAftermath()
		elseif not this.PrisonersMad then
			timeToRiot = timeToRiot + timePassed
			if timeToRiot > timeToMakePrisonersMad then
				MakePrisonersMad()
			end
		elseif not this.GuardGunsUpgraded then
			GiveGuardsGuns()
		end
		
		if Get(this,"UpdateFromMarker") == true then
			Interface.SetComponentProperties( "JackpotWinnerC", { Replacements = { X = tostring( this.Outcome ) } } )
			Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
		end
		this.UpdateFromMarker = nil
	end
	
	if timeTotDayCheck >= timePerDayCheck then
		timeTotDayCheck = 0
		if this.WeeklyLottery == true then
			CheckWeeklyLotteryDay()
		elseif not this.WeeklyLottery then
			CheckSylvesterLotteryDay()
		end
	end
end

function CheckWeeklyLotteryDay()
	if Get(this,"NextLotteryDay") > 0 then
		CalculatePrisonCapacity(this.CapacityMultiplier)
		this.LotteryEnabled = nil
		local startingDay = math.floor(this.LotteryStart/1440)
		local currentDay = math.floor(World.TimeIndex/1440)
		local daysUntilNextLottery = this.LotteryDaysInterval - (currentDay - startingDay)
		if daysUntilNextLottery < 0 then daysUntilNextLottery = 0 end
		Set(this,"NextLotteryDay",daysUntilNextLottery)
		Interface.SetComponentProperties( "NextLotteryDay", { Replacements = { X = tostring( this.NextLotteryDay ) } } )
	end
	if Get(this,"NextLotteryDay") == 0 then
		CheckLotteryHourAndMinute()
	end
end

function CheckSylvesterLotteryDay()
	if Get(this,"NextLotteryDay") > 0 then
		Set(this,"TicketsSoldRequired",1000)
		this.LotteryEnabled = nil
		currentDay = math.ceil(World.TimeIndex/1440)
		--print("day: "..currentDay)
		local TodayStartsSpring = math.mod(currentDay,28)
		if TodayStartsSpring == 2 then Set(this,"SylvesterLotteryDone",nil) end	-- reset at day 2 of spring
		NextSpringStartsOnDay = (currentDay + (28 - math.mod(currentDay,28)))
		--print("NextSpringStartsOnDay: "..NextSpringStartsOnDay)
		if TodayStartsSpring == 0 and not this.SylvesterLotteryDone then
			daysUntilNextLottery = 0
			Set(this,"NextLotteryDay",0)
		else
			Set(this,"NextLotteryDay",NextSpringStartsOnDay - currentDay)
			daysUntilNextLottery = NextSpringStartsOnDay - currentDay
		end
		--print("NextLotteryDay: "..this.NextLotteryDay)
		if daysUntilNextLottery < 0 then daysUntilNextLottery = 0 end
		Interface.SetComponentProperties( "NextLotteryDay", { Replacements = { X = tostring( this.NextLotteryDay ) } } )
	end
	if Get(this,"NextLotteryDay") == 0 then
		CheckLotteryHourAndMinute()
	end
end

function CheckLotteryHourAndMinute()
	if Get(this,"NextLotteryDay") == 0 then
		hours = math.floor(math.mod(World.TimeIndex,1440) /60)
		--print("hour: "..tonumber(hours))
		if tonumber(hours) >= 12 and tonumber(hours) <= 20 then		-- on lottery day, enable the lottery between 12:00 and 20:00
			timePerDayCheck = 15 / myTimeWarpFactor
			if this.TicketsSold >= this.TicketsSoldRequired then
				this.LotteryEnabled = true
				if not this.LotteryCountdownStarted then
					if not this.SoundFxDisabled then this.Sound("__RiotRoulette","RouletteMusic14") end
				end
			end
			if this.CountDownTheMinutes == true then
				this.CountDownTheMinutes = nil
				Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
			end
		elseif tonumber(hours) >= 11 and tonumber(hours) < 12 then	-- on lottery day, starting at 11:00, show countdown per minute
			this.ReportTabsSet = nil
			timePerDayCheck = 1 / myTimeWarpFactor
			minutes = math.floor(math.mod(World.TimeIndex,60))
			this.countdownToMinute = 60 - minutes
			if this.countdownToMinute < 0 then this.countdownToMinute = 0 end
			--print("countdownToMinute: "..tonumber(this.countdownToMinute))
			Interface.SetComponentProperties( "NextLotteryDay", { Replacements = { X = tostring( this.countdownToMinute ) } } )
			if this.CountDownTheMinutes == nil then
				this.CountDownTheMinutes = true
				Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
			end
		else
			this.LotteryEnabled = nil
			this.CountDownTheMinutes = nil
			timePerDayCheck = 15 / myTimeWarpFactor
			if hours >= 20 then this.countdownToHour = 34 - hours else this.countdownToHour = 12 - hours end
			if this.countdownToHour < 0 then this.countdownToHour = 0 end
			--print("countdownToHour: "..tonumber(this.countdownToHour))
			if not this.WeeklyLottery then
				if hours <= 20 then												-- starting at midnight on Sylvester, show countdown per hour
					Interface.SetComponentProperties( "NextLotteryDay", { Replacements = { X = tostring( this.countdownToHour ) } } )
					Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
					if not this.ReportTabsSet then
						Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
						this.ReportTabsSet = true
					end
				else															-- reset the button and countdown to next spring
					this.ReportTabsSet = nil
					currentDay = math.ceil(World.TimeIndex/1440)
					--print("day: "..currentDay)
					NextSpringStartsOnDay = (currentDay + (28 - math.mod(currentDay,28)))
					--print("NextSpringStartsOnDay: "..NextSpringStartsOnDay)
					Set(this,"NextLotteryDay",NextSpringStartsOnDay - currentDay)
					daysUntilNextLottery = NextSpringStartsOnDay - currentDay
					--print("NextLotteryDay: "..this.NextLotteryDay)
					Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
				end
			else														-- starting at midnight on prison lottery day, show countdown per hour
				Interface.SetComponentProperties( "NextLotteryDay", { Replacements = { X = tostring( this.countdownToHour ) } } )
				if not this.ReportTabsSet then
					Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
					this.ReportTabsSet = true
				end
				--Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
			end
		end
	end
end

function GatherLotteryCash()
	if this.Slot0.i > -1 then
		print("GatherLotteryCash")
		if not this.Opened then
			Object.CreateJob(this,"OpenLotterySafe")
			timePerUpdate = 0.25 / myTimeWarpFactor
		elseif this.SubType == 1 or this.SubType == 3 then
			Object.CreateJob(this,"StoreStakeInSafe")
		end
	end
	
	Interface.SetComponentProperties( "TicketsSold", { Replacements = { A = WithComma( this.TicketsSold ) } } )
	Interface.SetComponentProperties( "TotalStake", { Replacements = { A = WithComma( this.TotalStake ) } } )
	Interface.SetComponentProperties( "LastStake", { Replacements = { A = WithComma( this.LastStake ) } } )
	
	if this.WeeklyLottery == true then
		if this.NextLotteryDay > 0 then
			--Interface.SetComponentProperties( "NextLotteryDay", { Replacements = { X = tostring( this.NextLotteryDay ) } } )
			this.Tooltip = { "tooltip_VM2LotterySafeWeekly",WithComma(this.TicketsSold),"A",WithComma(this.TotalStake),"B",WithComma(this.LastStake),"C",this.NextLotteryDay,"D",WithComma(this.TicketsSoldRequired),"S" }
		else
			if tonumber(hours) >= 12 and tonumber(hours) <= 20 then		-- on lottery day, enable the lottery between 12:00 and 20:00
				if this.TicketsSold >= this.TicketsSoldRequired then
					this.Tooltip = { "tooltip_VM2LotterySafeWeeklyStart",WithComma(this.TicketsSold),"A",WithComma(this.TotalStake),"B",WithComma(this.LastStake),"C",WithComma(this.TicketsSoldRequired),"S" }
				else
					this.Tooltip = { "tooltip_VM2LotterySafeWeeklyNeedsSold",WithComma(this.TicketsSold),"A",WithComma(this.TotalStake),"B",WithComma(this.LastStake),"C",WithComma(this.TicketsSoldRequired-this.TicketsSold),"X" }
				end
			elseif tonumber(hours) >= 11 and tonumber(hours) < 12 then	-- on lottery day, starting at 11:00, show countdown per minute
				this.Tooltip = { "tooltip_VM2LotterySafeWeeklyMinutes",WithComma(this.TicketsSold),"A",WithComma(this.TotalStake),"B",WithComma(this.LastStake),"C",this.countdownToMinute,"D",WithComma(this.TicketsSoldRequired),"S" }
			else																-- starting at midnight on prison lottery day, show countdown per hour
				this.Tooltip = { "tooltip_VM2LotterySafeWeeklyHours",WithComma(this.TicketsSold),"A",WithComma(this.TotalStake),"B",WithComma(this.LastStake),"C",this.countdownToHour,"D",WithComma(this.TicketsSoldRequired),"S" }
			end
		end
	else
		if this.NextLotteryDay > 0 then
			this.Tooltip = { "tooltip_VM2LotterySafe",WithComma(this.TicketsSold),"A",WithComma(this.TotalStake),"B",WithComma(this.LastStake),"C",WithComma(NextSpringStartsOnDay),"D",WithComma(this.TicketsSoldRequired),"S" }
		else
			if tonumber(hours) >= 12 and tonumber(hours) <= 20 then		-- on lottery day, enable the lottery between 12:00 and 20:00
				if this.TicketsSold >= this.TicketsSoldRequired then
					this.Tooltip = { "tooltip_VM2LotterySafeStart",WithComma(this.TicketsSold),"A",WithComma(this.TotalStake),"B",WithComma(this.LastStake),"C",WithComma(this.TicketsSoldRequired),"S" }
				else
					this.Tooltip = { "tooltip_VM2LotterySafeNeedsSold",WithComma(this.TicketsSold),"A",WithComma(this.TotalStake),"B",WithComma(this.LastStake),"C",WithComma(this.TicketsSoldRequired-this.TicketsSold),"X" }
				end
			elseif tonumber(hours) >= 11 and tonumber(hours) < 12 then	-- on lottery day, starting at 11:00, show countdown per minute
				this.Tooltip = { "tooltip_VM2LotterySafeMinutes",WithComma(this.TicketsSold),"A",WithComma(this.TotalStake),"B",WithComma(this.LastStake),"C",this.countdownToMinute,"D",WithComma(this.TicketsSoldRequired),"S" }
			else
				if hours <= 20 then												-- starting at midnight on Sylvester, show countdown per hour
					this.Tooltip = { "tooltip_VM2LotterySafeHours",WithComma(this.TicketsSold),"A",WithComma(this.TotalStake),"B",WithComma(this.LastStake),"C",this.countdownToHour,"D",WithComma(this.TicketsSoldRequired),"S" }
				else															-- reset the button and countdown to next spring
					this.Tooltip = { "tooltip_VM2LotterySafe",WithComma(this.TicketsSold),"A",WithComma(this.TotalStake),"B",WithComma(this.LastStake),"C",WithComma(NextSpringStartsOnDay),"D",WithComma(this.TicketsSoldRequired),"S" }
				end
			end
		end
	end
end
			
function getObject(type,id,dist)
	objs = Object.GetNearbyObjects(type,dist or 1)
	for o,d in pairs(objs) do
		 if o.Id.i == id then
		 	return o
		 end
	end
end

function SetTabNames()
	Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2Lotterytab2","reportTab_VM2Lotterytab3")
end

function PopulateReport( tabIndex )
	tabIndex = tonumber( tabIndex)
    local w, h = Interface.GetReportWindowSize()
	if w == nil	or h == nil then return end
	
    w = w - 20  -- Top level canvas scrollbar
    
    local rowHeight = math.min(w, h) / 25.0
    local rowGap = rowHeight * 2
    local y = 0
    
    -- Title
	if not this.WeeklyLottery then
		Interface.AddReportComponent( { Type = "Title", Caption = "reportTitle_VM2Lottery" } )
	else
		Interface.AddReportComponent( { Type = "Title", Caption = "reportTitle_VM2LotteryWeekly" } )
	end
    if tabIndex == 1 then
		if not this.LotteryDone then
			if not this.WeeklyLottery then
				Interface.AddReportComponent( 
					{
						Type = "Image", 
						Name = "ImgBG", 
						X = 0,
						Y = y, 
						W = w, 
						H = h, 
						File = "report/report_VM2LotteryFireworks.png", 
						Colour = "White"
					}
				)
			else
				Interface.AddReportComponent( 
					{
						Type = "Image", 
						Name = "ImgBG", 
						X = 0,
						Y = y, 
						W = w, 
						H = h, 
						File = "report/report_VM2LotteryJackpot.png", 
						Colour = "White"
					}
				)
			end
			Interface.AddReportComponent( 
				{
					Type = "Caption", 
					X = 0, 
					Y = y, 
					W = w, 
					H = rowHeight*1.5, 
					Caption = "reportTooltip_VM2LotteryPrizes",
					Centred = true
				}
			)
			y = y + rowHeight*1.5
			Interface.AddReportComponent( 
				{
					Type = "MultiLineText", 
					Name = "Overview",
					X = (w / 3) / 8,
					Y = y, 
					W = w, 
					H = rowHeight*12, 
					LineSize = rowHeight*1.25, 
					Caption = "reportTooltip_VM2LotteryPrizesA"
				}
			)
			y = y + (rowHeight*12)
			Interface.AddReportComponent( 
				{
					Type = "Caption", 
					X = 0, 
					Y = y, 
					W = w, 
					H = rowHeight*1.5, 
					Caption = "reportTooltip_VM2LotteryPrizesB",
					Centred = true
				}
			)
			y = y + rowHeight*1.75
			Interface.AddReportComponent( 
				{
					Type = "Caption", 
					X = 0, 
					Y = y, 
					W = w, 
					H = rowHeight*1.25, 
					Caption = "reportTooltip_VM2LotteryPrizesC",
					Centred = true
				}
			)
			y = y + rowHeight
			Interface.AddReportComponent( 
				{
					Type = "Caption", 
					X = 0, 
					Y = y, 
					W = w, 
					H = rowHeight*1.25, 
					Caption = "reportTooltip_VM2LotteryPrizesD",
					Centred = true
				}
			)
			y = y + rowHeight + rowGap
			if not this.YourOwnBetPressedStart then
				Interface.AddReportComponent( 
					{
						Type = "Button", 
						Name = "PlaceYourOwnBetStart",
						X = w / 4, 
						Y = y, 
						W = w / 2, 
						H = rowHeight*1.5, 
						LineSize = rowHeight*1.5, 
						Caption = "reportButton_VM2PlaceYourBet"
					}
				)
			elseif not this.YourOwnBetPressedWinner then
				Interface.AddReportComponent( 
					{
						Type = "Caption", 
						X = 0, 
						Y = y, 
						W = w / 5, 
						H = rowHeight*1.25, 
						Caption = "reportTooltip_VM2WhoWillWin"
					}
				)
				Interface.AddReportComponent( 
					{
						Type = "Button", 
						Name = "PlaceYourOwnBetWardenIsWinner",
						X = (w / 4), 
						Y = y, 
						W = w / 5, 
						H = rowHeight*1.25, 
						LineSize = rowHeight, 
						Caption = "reportTooltip_VM2LotteryWinnerWarden"
					}
				)
				Interface.AddReportComponent( 
					{
						Type = "Button", 
						Name = "PlaceYourOwnBetPrisonerIsWinner",
						X = (w / 2), 
						Y = y, 
						W = w / 5, 
						H = rowHeight*1.25, 
						LineSize = rowHeight, 
						Caption = "reportTooltip_VM2LotteryWinnerPrisoner"
					}
				)
				Interface.AddReportComponent( 
					{
						Type = "Button", 
						Name = "PlaceYourOwnBetStaffMemberIsWinner",
						X = (w / 2) + (w / 4), 
						Y = y, 
						W = w / 5, 
						H = rowHeight*1.25, 
						LineSize = rowHeight, 
						Caption = "reportTooltip_VM2LotteryWinnerStaffMember"
					}
				)
			elseif not this.YourOwnBetPressedObject then
				Interface.AddReportComponent( 
					{
						Type = "Caption", 
						X = 0, 
						Y = y, 
						W = w / 5, 
						H = rowHeight*1.25, 
						Caption = "reportTooltip_VM2YourStake"
					}
				)
				Interface.AddReportComponent( 
					{
						Type = "Button", 
						Name = "PlaceYourOwnBetPowerStation",
						X = (w / 4), 
						Y = y, 
						W = w / 5, 
						H = rowHeight*1.25, 
						LineSize = rowHeight, 
						Caption = "reportButton_VM2BetPowerStation"
					}
				)
				Interface.AddReportComponent( 
					{
						Type = "Button", 
						Name = "PlaceYourOwnBet5K",
						X = (w / 2), 
						Y = y, 
						W = w / 5, 
						H = rowHeight*1.25, 
						LineSize = rowHeight, 
						Caption = "reportButton_VM2Bet5K"
					}
				)
				Interface.AddReportComponent( 
					{
						Type = "Button", 
						Name = "PlaceYourOwnBetCancelBet",
						X = (w / 2) + (w / 4), 
						Y = y, 
						W = w / 5, 
						H = rowHeight*1.25, 
						LineSize = rowHeight, 
						Caption = "reportButton_VM2CancelBet"
					}
				)
			else
				if this.YourBetObject == "$5000" then this.YourBetObject = "$ 5,000" end 
				Interface.AddReportComponent( 
					{
						Type = "Caption", 
						Name = "YourOwnBetIs",
						X = 0,
						Y = y, 
						W = w, 
						H = rowHeight*1.25,
						Caption = "reportTooltip_VM2YourBet",
						Replacements = { X = tostring( this.YourBetObject ), Y = tostring( this.YourBetWinner ) },
						Centred = true
					}
				)
			end
			y = y + rowHeight + rowGap
			Interface.AddReportComponent( 
				{
					Type = "Caption", 
					Name = "TicketsSold",
					X = 0,
					Y = y, 
					W = w, 
					H = rowHeight*1.5,
					Caption = "reportTooltip_VM2TicketsSold",
					Replacements = { A = WithComma( this.TicketsSold ) },
					Centred = true
				}
			)
			y = y + rowGap
			Interface.AddReportComponent( 
				{
					Type = "Caption", 
					Name = "TotalStake",
					X = 0,
					Y = y, 
					W = w, 
					H = rowHeight*2.25, 
					Caption = "reportTooltip_VM2TotalStake",
					Replacements = { A = WithComma( this.TotalStake ) },
					Centred = true
				}
			)
			y = y + rowGap*1.25
			Interface.AddReportComponent( 
				{
					Type = "Caption", 
					Name = "LastStake",
					X = 0,
					Y = y, 
					W = w, 
					H = rowHeight*1.5,
					Caption = "reportTooltip_VM2LastStake",
					Replacements = { A = WithComma( this.LastStake ) },
					Centred = true
				}
			)
			y = y + rowGap + rowHeight
			
			if not this.LotteryEnabled then
				if this.NextLotteryDay == nil then
					Interface.AddReportComponent( 
						{
							Type = "Caption", 
							Name = "NextLotteryDayInit",
							X = 0, 
							Y = y, 
							W = w, 
							H = rowHeight*1.5, 
							Caption = "reportTooltip_VM2NextLotteryDayInit",
							Centred = true
						}
					)
				elseif this.NextLotteryDay > 0 then
					Interface.AddReportComponent( 
						{
							Type = "Caption", 
							Name = "NextLotteryDay",
							X = 0, 
							Y = y, 
							W = w, 
							H = rowHeight*1.5, 
							Caption = "reportTooltip_VM2NextLotteryDay",
							Replacements = { X = tostring( this.NextLotteryDay ) },
							Centred = true
						}
					)
				else
					if not this.CountDownTheMinutes then
						Interface.AddReportComponent( 
							{
								Type = "Caption", 
								Name = "NextLotteryDay",
								X = 0, 
								Y = y, 
								W = w, 
								H = rowHeight*1.5, 
								Caption = "reportTooltip_VM2LotteryNoonHours",
								Replacements = { X = tostring( this.countdownToHour ) },
								Centred = true
							}
						)
					else
						Interface.AddReportComponent( 
							{
								Type = "Caption", 
								Name = "NextLotteryDay",
								X = 0, 
								Y = y, 
								W = w, 
								H = rowHeight*1.5, 
								Caption = "reportTooltip_VM2LotteryNoonMinutes",
								Replacements = { X = tostring( this.countdownToMinute ) },
								Centred = true
							}
						)

					end
				end
			else
				if not this.LotteryCountdownStarted then
					Interface.AddReportComponent( 
						{
							Type = "Button", 
							Name = "StartLottery",
							X = w / 4, 
							Y = y, 
							W = w / 2, 
							H = rowHeight*1.5, 
							LineSize = rowHeight*1.5, 
							Caption = "reportButton_VM2StartLottery"
						}
					)
				else
					Interface.AddReportComponent( 
						{
							Type = "Caption", 
							Name = "LotteryCountDown",
							X = 0, 
							Y = y, 
							W = w, 
							H = rowHeight*1.5, 
							Caption = "reportTooltip_VM2LotteryCollectLeftoverCash",
							Centred = true
						}
					)
				end
			end
			y = y + rowHeight*1.5
			Interface.AddReportComponent( 
				{
					Type = "Caption", 
					Name = "TicketsSoldRequired",
					X = 0, 
					Y = y, 
					W = w, 
					H = rowHeight*1.25, 
					Caption = "reportTooltip_VM2LotteryTicketsSoldRequired",
					Replacements = { X = WithComma(this.TicketsSoldRequired) },
					Centred = true
				}
			)
		else
			-- show lottery results
			if not this.WeeklyLottery then
				Interface.AddReportComponent( 
					{
						Type = "Image", 
						Name = "ImgBG", 
						X = 0,
						Y = y, 
						W = w, 
						H = h, 
						File = "report/report_VM2LotteryFireworks.png", 
						Colour = "White"
					}
				)
			else
				Interface.AddReportComponent( 
					{
						Type = "Image", 
						Name = "ImgBG", 
						X = 0,
						Y = y, 
						W = w, 
						H = h, 
						File = "report/report_VM2LotteryJackpot.png", 
						Colour = "White"
					}
				)
			end
			if not this.SoldTicketsListShown then
				Interface.AddReportComponent( 
					{
						Type = "Caption", 
						X = 0, 
						Y = y, 
						W = w, 
						H = rowHeight*1.5, 
						Caption = "reportTooltip_VM2LotteryPending",
						Centred = true
					}
				)
			else								-- show the results
				Interface.AddReportComponent( 
					{
						Type = "Caption", 
						X = 0, 
						Y = y, 
						W = w, 
						H = rowHeight*1.5, 
						Caption = "reportTooltip_VM2LotteryResultsA",
						Centred = true
					}
				)
			end
			y = y + rowHeight
				
			Interface.AddReportComponent( 
				{
					Type = "MultiLineText", 
					Name = "SylvesterLotteryResultsB",
					X = 0,
					Y = y, 
					W = w, 
					H = rowHeight*8, 
					LineSize = rowHeight*1.25, 
					Caption = "reportTooltip_VM2LotteryResultsB"
				}
			)
			if not this.SoldTicketsListShown then			-- show all the ticket numbers first
				
				Interface.AddReportComponent( 
					{
						Type = "MultiLineText", 
						Name = "SylvesterLotteryResultsC1",
						X = (w / 3)+(w / 3),
						Y = y, 
						W = w, 
						H = rowHeight*8, 
						LineSize = rowHeight*1.25, 
						Caption = "reportTooltip_VM2LotteryResultsC1"
					}
				)
				y = y + (rowHeight * 8)
				Interface.AddReportComponent( 
					{
						Type = "Caption", 
						Name = "TicketValidation",
						X = 0,
						Y = y, 
						W = w, 
						H = rowHeight*1.25, 
						Caption = "reportTooltip_VM2LotteryTicketValidation",
						Replacements = { V = "reportTooltip_VM2LotterySoldTicketWaiting" },
						Centred = true
					}
				)
				y = y + rowHeight
				if not this.TicketsAreValidated then
					Interface.AddReportComponent( 
						{
							Type = "Caption", 
							Name = "ScrollingTickets",
							X = 0,
							Y = y, 
							W = w, 
							H = rowHeight*1.25, 
							Caption = "reportTooltip_VM2LotterySoldTicketPleaseWait",
							Centred = true
						}
					)
				else
					Interface.AddReportComponent( 
						{
							Type = "Caption", 
							Name = "ScrollingTickets",
							X = 0,
							Y = y, 
							W = w, 
							H = rowHeight*1.25, 
							Caption = "reportTooltip_VM2LotterySoldTicketValidated",
							Centred = true
						}
					)
				end
				y = y + rowHeight*2
				Interface.AddReportComponent( 
					{
						Type = "Caption", 
						Name = "JackpotWinnerA",
						X = 0,
						Y = y, 
						W = w, 
						H = rowHeight*1.25, 
						Caption = "reportTooltip_VM2LotteryTicketDrawing",
						Centred = true
					}
				)
			elseif not this.YourBetResultShown then
				Interface.AddReportComponent( 
					{
						Type = "MultiLineText", 
						Name = "SylvesterLotteryResultsC1",
						X = (w / 3)+(w / 3),
						Y = y, 
						W = w, 
						H = rowHeight*8, 
						LineSize = rowHeight*1.25, 
						Caption = "reportTooltip_VM2LotteryResultsC1"
					}
				)
				y = y + (rowHeight * 8)
				
				Interface.AddReportComponent( 
					{
						Type = "Caption", 
						Name = "TicketValidation",
						X = 0,
						Y = y, 
						W = w, 
						H = rowHeight*1.25, 
						Caption = "reportTooltip_VM2LotteryTicketValidation",
						Replacements = { V = "reportTooltip_VM2LotterySoldTicketValidated" },
						Centred = true
					}
				)
				y = y + rowHeight
				Interface.AddReportComponent( 
					{
						Type = "Caption", 
						Name = "ScrollingTickets",
						X = 0,
						Y = y, 
						W = w, 
						H = rowHeight*1.25, 
						Caption = "reportTooltip_VM2LotterySoldTicketDone",
						Centred = true
					}
				)
				y = y + rowHeight*2
				if this.YourOwnBetPressedObject == true and not this.NoTicketsWereSold then
					Interface.AddReportComponent( 
						{
							Type = "Caption", 
							Name = "JackpotWinnerA",
							X = 0,
							Y = y, 
							W = w, 
							H = rowHeight*1.25, 
							Caption = "reportTooltip_VM2LotteryJackpotWinnerA",
							Replacements = { T = tostring( this.WinningTicket ), S = tostring( this.TicketWasSold )  },
							Centred = true
						}
					)
					y = y + rowHeight*1.5
					if this.YourBetWinner == this.theLotteryWinner then
						Interface.AddReportComponent( 
							{
								Type = "Caption", 
								Name = "YourOwnBetWin",
								X = 0,
								Y = y, 
								W = w, 
								H = rowHeight*1.25, 
								Caption = "reportTooltip_VM2PlaceYourOwnBetWin",
								Replacements = { X = tostring( this.YourBetObject ) },
								Centred = true
							}
						)
						y = y + rowHeight*1.5
					else
						Interface.AddReportComponent( 
							{
								Type = "Caption", 
								Name = "YourOwnBetLoose",
								X = 0,
								Y = y, 
								W = w, 
								H = rowHeight*1.25, 
								Caption = "reportTooltip_VM2PlaceYourOwnBetLoose",
								Replacements = { X = tostring( this.YourBetObject ) },
								Centred = true
							}
						)
						y = y + rowHeight*1.5
					end
					Interface.AddReportComponent( 
						{
							Type = "Button", 
							Name = "ContinueToResults",
							X = w / 4, 
							Y = y, 
							W = w / 2, 
							H = rowHeight*1.5, 
							LineSize = rowHeight*1.5, 
							Caption = "reportButton_VM2ContinueToResults"
						}
					)
					
				else
					this.YourBetResultShown = true
					if not this.WeeklyLottery then
						Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
					else
						Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
					end
				end
			else
				Interface.AddReportComponent( 
					{
						Type = "MultiLineText", 
						Name = "SylvesterLotteryResultsC2",
						X = (w / 3)+(w / 3),
						Y = y, 
						W = w, 
						H = rowHeight*8, 
						LineSize = rowHeight*1.25, 
						Caption = "reportTooltip_VM2LotteryResultsC2",
						Replacements = { A = tostring( this.OtherWinner1 ), B = tostring( this.OtherWinner2 ), C = tostring( this.OtherWinner3 ), D = tostring( this.OtherWinner4 ), E = tostring( this.OtherWinner5 ), F = tostring( this.OtherWinner6 ) }
					}
				)
				y = y + (rowHeight * 8)
				Interface.AddReportComponent( 
					{
						Type = "Caption", 
						X = 0, 
						Y = y, 
						W = w, 
						H = rowHeight*1.25, 
						Caption = "reportTooltip_VM2LotteryResultsThankYouA",
						Centred = true
					}
				)
				y = y + rowHeight
				Interface.AddReportComponent( 
					{
						Type = "Caption", 
						X = 0, 
						Y = y, 
						W = w, 
						H = rowHeight*1.25, 
						Caption = "reportTooltip_VM2LotteryResultsThankYouB",
						Centred = true
					}
				)
				y = y + rowGap
				Interface.AddReportComponent( 
					{
						Type = "Caption", 
						Name = "JackpotWinnerA",
						X = 0,
						Y = y, 
						W = w, 
						H = rowHeight*1.25, 
						Caption = "reportTooltip_VM2LotteryJackpotWinnerA",
						Replacements = { T = tostring( this.WinningTicket ), S = tostring( this.TicketWasSold )  },
						Centred = true
					}
				)
				y = y + rowHeight*1.25
				Interface.AddReportComponent( 
					{
						Type = "Caption", 
						Name = "JackpotWinnerB",
						X = 0,
						Y = y, 
						W = w, 
						H = rowHeight*1.75, 
						Caption = "reportTooltip_VM2LotteryJackpotWinnerB",
						Replacements = { W = tostring( this.theLotteryWinner ), Y = WithComma(this.Jackpot) },
						Centred = true
					}
				)
				if this.theLotteryWinner == "reportTooltip_VM2LotteryWinnerWarden" and not this.JackpotDonated then
					y = y + rowHeight*1.75
					Interface.AddReportComponent( 
						{
							Type = "Caption", 
							Name = "JackpotWinnerC",
							X = 0,
							Y = y, 
							W = w, 
							H = rowHeight*1.25, 
							Caption = "reportTooltip_VM2LotteryJackpotWinnerC",
							Replacements = { X = tostring( this.Outcome ) },
							Centred = true
						}
					)
					y = y + rowHeight
					Interface.AddReportComponent( 
						{
							Type = "Caption", 
							Name = "JackpotRegret",
							X = 0,
							Y = y, 
							W = w,
							H = rowHeight*1.25, 
							Caption = "reportTooltip_VM2LotteryResultsRegret",
							Centred = true
						}
					)
					y = y + rowHeight*2
				elseif this.theLotteryWinner == "reportTooltip_VM2LotteryWinnerWarden" then
					y = y + rowHeight*1.75
					Interface.AddReportComponent( 
						{
							Type = "Caption", 
							Name = "JackpotWinnerC",
							X = 0,
							Y = y, 
							W = w, 
							H = rowHeight*1.25, 
							Caption = "reportTooltip_VM2LotteryJackpotWinnerC",
							Replacements = { X = tostring( this.Outcome ) },
							Centred = true
						}
					)
					y = y + rowHeight
					if not this.JackpotUnavailable then
						if this.NotSpread then
							Interface.AddReportComponent( 
								{
									Type = "Caption", 
									Name = "JackpotWasNotSpread",
									X = 0,
									Y = y, 
									W = w, 
									H = rowHeight*1.25, 
									Caption = "reportTooltip_VM2LotteryJackpotWasNotSpread",
									Centred = true
								}
							)
						else
							if not this.JackpotUnfair then
								if this.Outcome == "reportTooltip_VM2LotteryOutcome8" then
									if not this.WeeklyLottery then
										Interface.AddReportComponent( 
											{
												Type = "Caption", 
												Name = "JackpotWasDonated",
												X = 0,
												Y = y, 
												W = w, 
												H = rowHeight*1.25,
												Caption = "reportTooltip_VM2LotteryJackpotWasDonated",
												Centred = true
											}
										)
									else
										Interface.AddReportComponent( 
											{
												Type = "Caption", 
												Name = "JackpotWasDonated",
												X = 0,
												Y = y, 
												W = w, 
												H = rowHeight*1.25,
												Caption = "reportTooltip_VM2LotteryJackpotWasDonatedWeekly",
												Centred = true
											}
										)
									end
								elseif this.Outcome == "reportTooltip_VM2LotteryOutcome20" then
									Interface.AddReportComponent( 
										{
											Type = "Caption", 
											Name = "JackpotWasReturned",
											X = 0,
											Y = y, 
											W = w, 
											H = rowHeight*1.25,
											Caption = "reportTooltip_VM2LotteryJackpotWasReturned",
											Centred = true
										}
									)
								end
							else
								if this.Outcome == "reportTooltip_VM2LotteryOutcome21" then
									Interface.AddReportComponent( 
										{
											Type = "Caption", 
											Name = "HoundsReleased",
											X = 0,
											Y = y, 
											W = w, 
											H = rowHeight*1.25,
											Caption = "reportTooltip_VM2LotteryHoundsReleased",
											Centred = true
										}
									)
								elseif this.Outcome == "reportTooltip_VM2LotteryOutcome22" then
									Interface.AddReportComponent( 
										{
											Type = "Caption", 
											Name = "BodyguardsReleased",
											X = 0,
											Y = y, 
											W = w, 
											H = rowHeight*1.25,
											Caption = "reportTooltip_VM2LotteryBodyguardsReleased",
											Centred = true
										}
									)
								else
									Interface.AddReportComponent( 
										{
											Type = "Caption", 
											Name = "JackpotUnfairPayback",
											X = 0,
											Y = y, 
											W = w, 
											H = rowHeight*1.25,
											Caption = "reportTooltip_VM2LotteryJackpotUnfairPayback",
											Centred = true
										}
									)
								end
							end
						end
					else
						Interface.AddReportComponent( 
							{
								Type = "Caption", 
								Name = "JackpotWasUnavailable",
								X = 0,
								Y = y, 
								W = w, 
								H = rowHeight*1.25,
								Caption = "reportTooltip_VM2LotteryJackpotUnavailable",
								Centred = true
							}
						)
					end
					y = y + rowHeight*2
				else
					y = y + rowHeight*1.75
					Interface.AddReportComponent( 
						{
							Type = "Caption", 
							Name = "JackpotWinnerC",
							X = 0,
							Y = y, 
							W = w, 
							H = rowHeight*1.25, 
							Caption = "reportTooltip_VM2LotteryJackpotWinnerC",
							Replacements = { X = tostring( this.Outcome ) },
							Centred = true
						}
					)
					y = y + rowHeight + rowGap
				end
				if not this.WeeklyLottery then
					Interface.AddReportComponent( 
						{
							Type = "Caption", 
							X = 0, 
							Y = y, 
							W = w / 2, 
							H = rowHeight*1.5, 
							Caption = "reportTooltip_VM2LotteryResultsThankYou1",
							Centred = true
						}
					)
					Interface.AddReportComponent( 
						{
							Type = "Image", 
							Name = "ImgOverview", 
							X = (w / 2),
							Y = y, 
							W = w / 2,
							H = w / 2,
							File = "report/report_VM2LotteryChampagne.png", 
							Colour = "White"
						}
						)
					y = y + rowHeight
					Interface.AddReportComponent( 
						{
							Type = "Caption", 
							X = 0, 
							Y = y, 
							W = w / 2, 
							H = rowHeight*1.5, 
							Caption = "reportTooltip_VM2LotteryResultsThankYou2",
							Centred = true
						}
					)
					y = y + rowHeight + rowGap
					Interface.AddReportComponent( 
						{
							Type = "Caption", 
							X = 0, 
							Y = y, 
							W = w / 2, 
							H = rowHeight*1.5, 
							Caption = "reportTooltip_VM2LotteryResultsThankYou3",
							Centred = true
						}
					)
					y = y + rowHeight
					Interface.AddReportComponent( 
						{
							Type = "Caption", 
							X = 0, 
							Y = y, 
							W = w / 2, 
							H = rowHeight*1.5, 
							Caption = "reportTooltip_VM2LotteryResultsThankYou4",
							Centred = true
						}
					)
					y = y + rowHeight + rowGap
					Interface.AddReportComponent( 
						{
							Type = "Caption", 
							X = 0, 
							Y = y, 
							W = (w / 2), 
							H = rowHeight*1.5, 
							Caption = "reportTooltip_VM2LotteryResultsThankYou5",
							Centred = true
						}
					)
					y = y + rowHeight
					Interface.AddReportComponent( 
						{
							Type = "Caption", 
							X = 0, 
							Y = y, 
							W = (w / 2), 
							H = rowHeight*1.5, 
							Caption = "reportTooltip_VM2LotteryResultsThankYou6",
							Centred = true
						}
					)
					y = y + rowHeight
					Interface.AddReportComponent( 
						{
							Type = "Caption", 
							X = 0, 
							Y = y, 
							W = (w / 2), 
							H = rowHeight*1.5, 
							Caption = "reportTooltip_VM2LotteryResultsThankYou7",
							Centred = true
						}
					)
					y = y + rowHeight*2.25
					Interface.AddReportComponent( 
						{
							Type = "Button", 
							Name = "ResetLotterySafe",
							X = w / 3, 
							Y = y, 
							W = w / 3, 
							H = rowHeight*1.25, 
							LineSize = rowHeight, 
							Caption = "reportButton_VM2ResetLotterySafe",
							Centred = true
						}
					)
					if this.DecideFirst == true then
						y = y + rowHeight*1.25
						if this.WeHaveAWinner == true then
							Interface.AddReportComponent( 
								{
									Type = "Caption", 
									X = 0, 
									Y = y, 
									W = w, 
									H = rowHeight, 
									Caption = "reportTooltip_VM2LotteryDecideFirstPrisoner",
									Centred = true
								}
							)
						else
							Interface.AddReportComponent( 
								{
									Type = "Caption", 
									X = 0, 
									Y = y, 
									W = w, 
									H = rowHeight, 
									Caption = "reportTooltip_VM2LotteryDecideFirstWarden",
									Centred = true
								}
							)
						end
					end
				else
					y = y + rowHeight*5 + rowGap
					y = y + rowHeight*2.25
					Interface.AddReportComponent( 
						{
							Type = "Caption", 
							X = 0, 
							Y = y, 
							W = w, 
							H = rowHeight*1.25, 
							Caption = "reportTooltip_VM2LotteryResultsThankYouWeekly",
							Centred = true
						}
					)
					y = y + rowHeight*1.5
					Interface.AddReportComponent( 
						{
							Type = "Button", 
							Name = "ResetLotterySafe",
							X = w / 3, 
							Y = y, 
							W = w / 3, 
							H = rowHeight*1.25, 
							LineSize = rowHeight, 
							Caption = "reportButton_VM2ResetLotterySafe",
							Centred = true
						}
					)
					if this.DecideFirst == true then
						y = y + rowHeight*1.25
						if this.WeHaveAWinner == true then
							Interface.AddReportComponent( 
								{
									Type = "Caption", 
									X = 0, 
									Y = y, 
									W = w, 
									H = rowHeight, 
									Caption = "reportTooltip_VM2LotteryDecideFirstPrisoner",
									Centred = true
								}
							)
						else
							Interface.AddReportComponent( 
								{
									Type = "Caption", 
									X = 0, 
									Y = y, 
									W = w, 
									H = rowHeight, 
									Caption = "reportTooltip_VM2LotteryDecideFirstWarden",
									Centred = true
								}
							)
						end
					end
				end
			end
		end
    end
	
    if tabIndex == 2 then
		if not this.WeeklyLottery then
			Interface.AddReportComponent( 
				{
					Type = "Image", 
					Name = "ImgBG", 
					X = 0,
					Y = y, 
					W = w, 
					H = h, 
					File = "report/report_VM2LotteryFireworks.png", 
					Colour = "White"
				}
			)
		else
			Interface.AddReportComponent( 
				{
					Type = "Image", 
					Name = "ImgBG", 
					X = 0,
					Y = y, 
					W = w, 
					H = h, 
					File = "report/report_VM2LotteryJackpot.png", 
					Colour = "White"
				}
			)
		end
		Interface.AddReportComponent( 
			{
				Type = "Caption", 
				X = 0, 
				Y = y, 
				W = w, 
				H = rowHeight*1.5, 
				Caption = "reportTooltip_VM2LotteryFunding",
				Centred = true
			}
		)
		y = y + rowHeight*3
		Interface.AddReportComponent( 
			{
				Type = "MultiLineText", 
				Name = "PrisonLotteryPrisonerFundDescription",
				X = 0,
				Y = y, 
				W = w, 
				H = rowHeight*20, 
				LineSize = rowHeight*1.25, 
				Caption = "reportTooltip_VM2PrisonerFundDescription"
			}
		)
		y = y + rowHeight*20
		Interface.AddReportComponent( 
			{
				Type = "Button", 
				Name = "CountTheTotalCash",
				X = (w / 4) + (w / 4)+ (w / 4), 
				Y = y, 
				W = w / 5, 
				H = rowHeight*1.5, 
				LineSize = rowHeight*1.5, 
				Caption = "reportButton_VM2CountTheTotalCash"
			}
		)
		Interface.AddReportComponent( 
			{
				Type = "Caption", 
				Name = "PrisonLotteryTotalCashResults1",
				X = 0, 
				Y = y, 
				W = w, 
				H = rowHeight*1.25, 
				Caption = "reportTooltip_VM2CountTheTotalCash1"
			}
		)
		y = y + rowHeight*1.5
		if totalPrisonerMoney > 0 then
			Interface.AddReportComponent( 
				{
					Type = "Caption", 
					Name = "PrisonLotteryTotalCashResults2",
					X = 0, 
					Y = y, 
					W = w, 
					H = rowHeight*1.25, 
					Caption = "reportTooltip_VM2TotalCashResults",
					Replacements = { X = WithComma( math.floor(totalPrisonerMoney) ), Y = tostring( totalPrisoners ), Z = WithComma( math.floor(totalPrisonerMoney / totalPrisoners) ) },
					Centred = true
				}
			)
		else
			Interface.AddReportComponent( 
				{
					Type = "Caption", 
					Name = "PrisonLotteryTotalCashResults2",
					X = 0, 
					Y = y, 
					W = w, 
					H = rowHeight*1.25, 
					Caption = "reportTooltip_VM2CountTheTotalCash2",
					Centred = true
				}
			)
		end
		y = y + rowHeight + rowGap
		if not this.PrisonersPersuaded then
			Interface.AddReportComponent( 
				{
					Type = "Button", 
					Name = "PersuadePrisoners",
					X = (w / 4) + (w / 4)+ (w / 4), 
					Y = y, 
					W = w / 5, 
					H = rowHeight*1.5, 
					LineSize = rowHeight*1.5, 
					Caption = "reportButton_VM2PersuadePrisoners"
				}
			)
			Interface.AddReportComponent( 
				{
					Type = "Caption", 
					Name = "PrisonLotteryPersuade",
					X = 0, 
					Y = y, 
					W = w, 
					H = rowHeight*1.25, 
					Caption = "reportTooltip_VM2LotteryPersuade"
				}
			)
			y = y + rowHeight*1.5
			Interface.AddReportComponent( 
				{
					Type = "Caption", 
					Name = "PrisonLotteryPersuadeResultsCash",
					X = 0, 
					Y = y, 
					W = w, 
					H = rowHeight*1.25, 
					Caption = "reportTooltip_VM2PersuadeResultsCash1",
					Replacements = { M = WithComma( cashCollected ), N = tostring( candidates ) },
					Centred = true
				}
			)
			y = y + rowHeight
			Interface.AddReportComponent( 
				{
					Type = "Caption", 
					Name = "PrisonLotteryPersuadeResults",
					X = 0, 
					Y = y, 
					W = w, 
					H = rowHeight*1.25, 
					Caption = "reportTooltip_VM2PersuadeResults1",
					Replacements = { X = tostring( prisonersYes ), Y = tostring( prisonersNo ), Z = tostring( prisonersNotSure ) },
					Centred = true
				}
			)
		else
			if cashCollected > 0 then
				Interface.AddReportComponent( 
					{
						Type = "Caption", 
						Name = "PrisonLotteryPersuadeResultsCash",
						X = 0, 
						Y = y, 
						W = w, 
						H = rowHeight*1.25, 
						Caption = "reportTooltip_VM2PersuadeResultsCash2",
						Replacements = { M = WithComma( cashCollected ), N = tostring( candidates ) },
						Centred = true
					}
				)
				y = y + rowHeight
				Interface.AddReportComponent( 
					{
						Type = "Caption", 
						Name = "PrisonLotteryPersuadeResults",
						X = 0, 
						Y = y, 
						W = w, 
						H = rowHeight*1.25, 
						Caption = "reportTooltip_VM2PersuadeResults2",
						Replacements = { X = tostring( prisonersYes ), Y = tostring( prisonersNo ), Z = tostring( prisonersNotSure ) },
						Centred = true
					}
				)
			else
				Interface.AddReportComponent( 
					{
						Type = "Caption", 
						Name = "PrisonLotteryPersuadeResultsCash",
						X = 0, 
						Y = y, 
						W = w, 
						H = rowHeight*1.25, 
						Caption = "reportTooltip_VM2PersuadeResultsCash3",
						Centred = true
					}
				)
				y = y + rowHeight
				Interface.AddReportComponent( 
					{
						Type = "Caption", 
						Name = "PrisonLotteryPersuadeResults",
						X = 0, 
						Y = y, 
						W = w, 
						H = rowHeight*1.25, 
						Caption = "reportTooltip_VM2PersuadeResults3",
						Centred = true
					}
				)
			end
		end
	end
    if tabIndex == 3 then
		if not this.WeeklyLottery then
			Interface.AddReportComponent( 
				{
					Type = "Image", 
					Name = "ImgBG", 
					X = 0,
					Y = y, 
					W = w, 
					H = h, 
					File = "report/report_VM2LotteryFireworks.png", 
					Colour = "White"
				}
			)
		else
			Interface.AddReportComponent( 
				{
					Type = "Image", 
					Name = "ImgBG", 
					X = 0,
					Y = y, 
					W = w, 
					H = h, 
					File = "report/report_VM2LotteryJackpot.png", 
					Colour = "White"
				}
			)
		end
		Interface.AddReportComponent( 
			{
				Type = "Caption", 
				X = 0, 
				Y = y, 
				W = w, 
				H = rowHeight*1.5, 
				Caption = "reportTooltip_VM2LotterySettings",
				Centred = true
			}
		)
		y = y + rowHeight*3
		Interface.AddReportComponent( 
			{
				Type = "Button", 
				Name = "DeleteSafe",
				X = 0, 
				Y = y, 
				W = w / 5, 
				H = rowHeight*1.5, 
				LineSize = rowHeight*1.5, 
				Caption = "reportButton_VM2DeleteSafe"
			}
		)
		if not this.MusicFxDisabled then
			Interface.AddReportComponent( 
				{
					Type = "Caption", 
					Name = "LotterySettingsMusic",
					X = 0, 
					Y = y, 
					W = w, 
					H = rowHeight*1.25, 
					Caption = "reportTooltip_VM2LotterySettingsMusic",
					Replacements = { X = "reportTooltip_VM2LotterySettingsMusicON" },
					Centred = true
				}
			)
		else
			Interface.AddReportComponent( 
				{
					Type = "Caption", 
					Name = "LotterySettingsMusic",
					X = 0, 
					Y = y, 
					W = w, 
					H = rowHeight*1.25, 
					Caption = "reportTooltip_VM2LotterySettingsMusic",
					Replacements = { X = "reportTooltip_VM2LotterySettingsMusicOFF" },
					Centred = true
				}
			)
		end
		Interface.AddReportComponent( 
			{
				Type = "Button", 
				Name = "ToggleMusic",
				X = (w / 4) + (w / 4)+ (w / 4), 
				Y = y, 
				W = w / 5, 
				H = rowHeight*1.5, 
				LineSize = rowHeight*1.5, 
				Caption = "reportButton_VM2ToggleMusicOnOff"
			}
		)
		y = y + rowHeight*3
		if not this.SoundFxDisabled then
			Interface.AddReportComponent( 
				{
					Type = "Caption", 
					Name = "LotterySettingsSound",
					X = 0, 
					Y = y, 
					W = w, 
					H = rowHeight*1.25, 
					Caption = "reportTooltip_VM2LotterySettingsSound",
					Replacements = { X = "reportTooltip_VM2LotterySettingsSoundON" },
					Centred = true
				}
			)
		else
			Interface.AddReportComponent( 
				{
					Type = "Caption", 
					Name = "LotterySettingsSound",
					X = 0, 
					Y = y, 
					W = w, 
					H = rowHeight*1.25, 
					Caption = "reportTooltip_VM2LotterySettingsSound",
					Replacements = { X = "reportTooltip_VM2LotterySettingsSoundOFF" },
					Centred = true
				}
			)
		end
		Interface.AddReportComponent( 
			{
				Type = "Button", 
				Name = "ToggleSound",
				X = (w / 4) + (w / 4)+ (w / 4), 
				Y = y, 
				W = w / 5, 
				H = rowHeight*1.5, 
				LineSize = rowHeight*1.5, 
				Caption = "reportButton_VM2ToggleSoundOnOff"
			}
		)
		--if this.WeeklyLottery == true then
			y = y + rowHeight*3
			Interface.AddReportComponent( 
				{
					Type = "Caption", 
					Name = "LotterySettingsInterval",
					X = 0, 
					Y = y, 
					W = w, 
					H = rowHeight*1.25, 
					Caption = "reportTooltip_VM2LotterySettingsInterval",
					Replacements = { X = tostring( this.LotteryDaysInterval ) }
				}
			)
			y = y + rowHeight*2
			if this.TicketsSold >= this.TicketsSoldRequired then
				Interface.AddReportComponent( 
					{
						Type = "Button", 
						Name = "ToggleLotteryInterval0",
						X = 0, 
						Y = y, 
						W = w / 5, 
						H = rowHeight*1.5, 
						LineSize = rowHeight*1.5, 
						Caption = "reportButton_VM2ToggleLotteryInterval0"
					}
				)
			else
				Interface.AddReportComponent( 
					{
						Type = "Button", 
						Name = "ToggleLotteryInterval0",
						X = 0, 
						Y = y, 
						W = w / 5, 
						H = rowHeight*1.5, 
						LineSize = rowHeight*1.5, 
						Caption = "reportButton_VM2ToggleLotteryInterval0disabled"
					}
				)
			end
			Interface.AddReportComponent( 
				{
					Type = "Button", 
					Name = "ToggleLotteryInterval7",
					X = w / 4, 
					Y = y, 
					W = w / 5, 
					H = rowHeight*1.5, 
					LineSize = rowHeight*1.5, 
					Caption = "reportButton_VM2ToggleLotteryInterval7"
				}
			)
			Interface.AddReportComponent( 
				{
					Type = "Button", 
					Name = "ToggleLotteryInterval14",
					X = (w / 4) + (w / 4), 
					Y = y, 
					W = w / 5, 
					H = rowHeight*1.5, 
					LineSize = rowHeight*1.5, 
					Caption = "reportButton_VM2ToggleLotteryInterval14"
				}
			)
			Interface.AddReportComponent( 
				{
					Type = "Button", 
					Name = "ToggleLotteryInterval28",
					X = (w / 4) + (w / 4)+ (w / 4), 
					Y = y, 
					W = w / 5, 
					H = rowHeight*1.5, 
					LineSize = rowHeight*1.5, 
					Caption = "reportButton_VM2ToggleLotteryInterval28"
				}
			)
			y = y + rowHeight*2
			Interface.AddReportComponent( 
				{
					Type = "Caption", 
					X = 0, 
					Y = y, 
					W = w, 
					H = rowHeight*1.25, 
					Caption = "reportTooltip_VM2LotterySettingsIntervalForce1",
					Centred = true
				}
			)
			y = y + rowHeight
			Interface.AddReportComponent( 
				{
					Type = "Caption", 
					X = 0, 
					Y = y, 
					W = w, 
					H = rowHeight*1.25, 
					Caption = "reportTooltip_VM2LotterySettingsIntervalForce2",
					Centred = true
				}
			)
			y = y + rowHeight*2
			Interface.AddReportComponent( 
				{
					Type = "Caption", 
					Name = "ToggleCapacityMultiplier",
					X = 0, 
					Y = y, 
					W = w, 
					H = rowHeight*1.25, 
					Caption = "reportTooltip_VM2LotterySettingsSoldTickets",
					Replacements = { C = tostring( this.CapacityMultiplier ), S = tostring( this.TicketsSoldRequired ) }
				}
			)
			y = y + rowHeight*2
			Interface.AddReportComponent( 
				{
					Type = "Button", 
					Name = "ToggleSoldTicketsX2",
					X = 0, 
					Y = y, 
					W = w / 5, 
					H = rowHeight*1.5, 
					LineSize = rowHeight*1.5, 
					Caption = "reportButton_VM2ToggleSoldTicketsX2"
				}
			)
			Interface.AddReportComponent( 
				{
					Type = "Button", 
					Name = "ToggleSoldTicketsX5",
					X = w / 4, 
					Y = y, 
					W = w / 5, 
					H = rowHeight*1.5, 
					LineSize = rowHeight*1.5, 
					Caption = "reportButton_VM2ToggleSoldTicketsX5"
				}
			)
			Interface.AddReportComponent( 
				{
					Type = "Button", 
					Name = "ToggleSoldTicketsX10",
					X = (w / 4) + (w / 4), 
					Y = y, 
					W = w / 5, 
					H = rowHeight*1.5, 
					LineSize = rowHeight*1.5, 
					Caption = "reportButton_VM2ToggleSoldTicketsX10"
				}
			)
			Interface.AddReportComponent( 
				{
					Type = "Button", 
					Name = "ToggleSoldTicketsX50",
					X = (w / 4) + (w / 4)+ (w / 4), 
					Y = y, 
					W = w / 5, 
					H = rowHeight*1.5, 
					LineSize = rowHeight*1.5, 
					Caption = "reportButton_VM2ToggleSoldTicketsX50"
				}
			)
			if World.CheatsEnabled then
				y = y + rowHeight*3
				Interface.AddReportComponent( 
					{
						Type = "Caption", 
						X = 0, 
						Y = y, 
						W = w, 
						H = rowHeight*1.25, 
						LineSize = rowHeight*2,
						Caption = "reportTooltip_VM2LotterySettingsCheats",
						Centred = true
					}
				)
				y = y + rowHeight*1.5
				Interface.AddReportComponent( 
					{
						Type = "Caption", 
						X = 0, 
						Y = y, 
						W = w, 
						H = rowHeight*1.25, 
						LineSize = rowHeight*1.5,
						Caption = "reportTooltip_VM2LotterySettingsTickets",
						Centred = true
					}
				)
				y = y + rowHeight*2
				Interface.AddReportComponent( 
					{
						Type = "Caption", 
						X = 0, 
						Y = y, 
						W = w, 
						H = rowHeight*1.25, 
						Caption = "reportTooltip_VM2LotterySettingsGiveTickets"
					}
				)
				Interface.AddReportComponent( 
					{
						Type = "Button", 
						Name = "ToggleGiveTickets",
						X = (w / 4) + (w / 4)+ (w / 4), 
						Y = y, 
						W = w / 5, 
						H = rowHeight*1.5, 
						LineSize = rowHeight*1.5, 
						Caption = "reportButton_VM2ToggleGiveTickets"
					}
				)
				y = y + rowHeight*3
				Interface.AddReportComponent( 
					{
						Type = "Caption", 
						X = 0, 
						Y = y, 
						W = w, 
						H = rowHeight*1.25, 
						Caption = "reportTooltip_VM2ResetPrisonerMoney"
					}
				)
				Interface.AddReportComponent( 
					{
						Type = "Button", 
						Name = "ToggleResetPrisonerMoney",
						X = (w / 4) + (w / 4)+ (w / 4), 
						Y = y, 
						W = w / 5, 
						H = rowHeight*1.5, 
						LineSize = rowHeight*1.5, 
						Caption = "reportButton_VM2ToggleResetPrisonerMoney"
					}
				)
				y = y + rowHeight*3
				Interface.AddReportComponent( 
					{
						Type = "Caption", 
						X = 0, 
						Y = y, 
						W = w, 
						H = rowHeight*1.25, 
						Caption = "reportTooltip_VM2SettingsResetNeedsAndASafe"
					}
				)
				Interface.AddReportComponent( 
					{
						Type = "Button", 
						Name = "ToggleResetNeedsAndASafe",
						X = (w / 4) + (w / 4)+ (w / 4), 
						Y = y, 
						W = w / 5, 
						H = rowHeight*1.5, 
						LineSize = rowHeight*1.5, 
						Caption = "reportButton_VM2ToggleResetNeedsAndASafe"
					}
				)
			end
		--end
	end
end

function ButtonPressed_DeleteSafe()
	this.Delete()
end

function ButtonPressed_ToggleMusic()
	if this.MusicFxDisabled == nil then
		this.MusicFxDisabled = true
		Interface.SetComponentProperties( "LotterySettingsMusic", { Replacements = { X = "reportTooltip_VM2LotterySettingsMusicOFF"} } )
	else
		this.MusicFxDisabled = nil
		Interface.SetComponentProperties( "LotterySettingsMusic", { Replacements = { X = "reportTooltip_VM2LotterySettingsMusicON" } } )
	end
end

function ButtonPressed_ToggleSound()
	if this.SoundFxDisabled == nil then
		this.SoundFxDisabled = true
		Interface.SetComponentProperties( "LotterySettingsSound", { Replacements = { X = "reportTooltip_VM2LotterySettingsSoundOFF"} } )
	else
		this.SoundFxDisabled = nil
		Interface.SetComponentProperties( "LotterySettingsSound", { Replacements = { X = "reportTooltip_VM2LotterySettingsSoundON" } } )
	end
end

function ButtonPressed_ToggleLotteryInterval0()
	if this.TicketsSold >= this.TicketsSoldRequired then
		CalculateDaysLeft(0)
		CheckSylvesterLotteryDay()
	end
	this.WeeklyLottery = true
	this.SubType = 2
	Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
end

function ButtonPressed_ToggleLotteryInterval7()
	CalculateDaysLeft(7)
	this.WeeklyLottery = true
	this.SubType = 2
	Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
end

function ButtonPressed_ToggleLotteryInterval14()
	CalculateDaysLeft(14)
	this.WeeklyLottery = true
	this.SubType = 2
	Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
end

function ButtonPressed_ToggleLotteryInterval28()
	CalculateDaysLeft(28)
	this.WeeklyLottery = nil
	this.SubType = 0
	Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
end

function ButtonPressed_ToggleSoldTicketsX2()
	CalculatePrisonCapacity(2)
	if this.TicketsSold >= this.TicketsSoldRequired then
		Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
	end
end

function ButtonPressed_ToggleSoldTicketsX5()
	CalculatePrisonCapacity(5)
	if this.TicketsSold >= this.TicketsSoldRequired then
		Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
	end
end

function ButtonPressed_ToggleSoldTicketsX10()
	CalculatePrisonCapacity(10)
	if this.TicketsSold >= this.TicketsSoldRequired then
		Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
	end
end

function ButtonPressed_ToggleSoldTicketsX50()
	CalculatePrisonCapacity(50)
	if this.TicketsSold >= this.TicketsSoldRequired then
		Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
	end
end

function ButtonPressed_ToggleGiveTickets()
	for _, typ in pairs(entityGroup) do
		local entityType = Find(this,typ,10000)
		for thatEntity, _ in pairs(entityType) do
		
			for j = 1,this.CapacityMultiplier do
				if Get(thatEntity,"TicketsBought") == nil then
					Set(thatEntity,"TicketsBought",1)
					Set(thatEntity,"T1",math.floor(World.TimeIndex))
				else
					Set(thatEntity,"TicketsBought",Get(thatEntity,"TicketsBought")+1)
					Set(thatEntity,"T"..thatEntity.TicketsBought,math.floor(World.TimeIndex))
				end
				this.TicketsSold = this.TicketsSold + 1
				this.TotalStake = this.TotalStake+math.random(2,250)
			end
		end
	end
	CalculateDaysLeft(0)
	CheckLotteryHourAndMinute()
	Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
end

function ButtonPressed_ToggleResetPrisonerMoney()
	nearbyPrisoners = Find(this,"Prisoner",10000)
	if next(nearbyPrisoners) then
		for thatPrisoner, dist in pairs(nearbyPrisoners) do
			thatPrisoner.AvailableMoney = 10
		end
	end
	nearbyPrisoners = nil
	Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
end

function ButtonPressed_ToggleResetNeedsAndASafe()
	nearbyPrisoners = Find(this,"Prisoner",10000)
	if next(nearbyPrisoners) then
		for thatPrisoner, dist in pairs(nearbyPrisoners) do
			ResetPrisonerNeeds(thatPrisoner)
			thatPrisoner.Equipment = 0
			thatPrisoner.Misbehavior = 0
		end
	end
	nearbyPrisoners = nil
	ResetLotterySafeAndTickets()
end

function ButtonPressed_CountTheTotalCash()
	totalPrisonerMoney = 0
	totalPrisoners = 0
	if nearbyPrisoners == nil then nearbyPrisoners = Find(this,"Prisoner",10000) end
	if next(nearbyPrisoners) then
		for thatPrisoner, dist in pairs(nearbyPrisoners) do
			if thatPrisoner.SubType == nil then
				refreshPrisoners = true
			else
				totalPrisonerMoney = totalPrisonerMoney + thatPrisoner.AvailableMoney
				totalPrisoners = totalPrisoners + 1
			end
		end
		Interface.SetComponentProperties( "PrisonLotteryTotalCashResults2", { Caption = "reportTooltip_VM2TotalCashResults", Replacements = { X = WithComma( math.floor(totalPrisonerMoney) ), Y = tostring( totalPrisoners ), Z = WithComma( math.floor(totalPrisonerMoney / totalPrisoners) ) } } )
	end
	if refreshPrisoners == true then
		nearbyPrisoners = nil
		timeTotDayCheck = timePerDayCheck
		refreshPrisoners = nil
	end
end

function ButtonPressed_PersuadePrisoners()
	if not this.PrisonersPersuaded then
		cashCollected = 0
		prisonerSpends = 0
		persuasionChance = 0
		candidates = 0
		prisonersYes = 0
		prisonersNo = 0
		prisonersNotSure = 0
		totalPrisonerMoney = 0
		totalPrisoners = 0
		nearbyPrisoners = Find(this,"Prisoner",10000)
		if next(nearbyPrisoners) then
			for thatPrisoner, dist in pairs(nearbyPrisoners) do
				totalPrisonerMoney = totalPrisonerMoney + thatPrisoner.AvailableMoney
				totalPrisoners = totalPrisoners + 1
				if thatPrisoner.TicketsBought ~= nil and thatPrisoner.AvailableMoney >= 10 then
					candidates = candidates + 1
					persuasionChance = math.random()
					if persuasionChance >= .66 then
						prisonerSpends = math.random(10,math.floor(thatPrisoner.AvailableMoney))
						cashCollected = cashCollected + prisonerSpends
						thatPrisoner.AvailableMoney = thatPrisoner.AvailableMoney - prisonerSpends
						Set(this,"LastStake",prisonerSpends)
						prisonersYes = prisonersYes + 1
					elseif persuasionChance >= .33 then
						prisonersNo = prisonersNo + 1
					else
						prisonersNotSure = prisonersNotSure + 1
					end
				end
			end
		end
		nearbyPrisoners = nil
		if totalPrisoners == 0 then totalPrisoners = 1 end
		Set(this,"TotalStake",this.TotalStake + cashCollected)
		Interface.SetComponentProperties( "PrisonLotteryTotalCashResults2", { Caption = "reportTooltip_VM2TotalCashResults", Replacements = { X = WithComma( math.floor(totalPrisonerMoney) ), Y = tostring( totalPrisoners ), Z = WithComma( math.floor(totalPrisonerMoney / totalPrisoners) ) } } )
		Interface.SetComponentProperties( "PrisonLotteryPersuadeResultsCash", { Caption = "reportTooltip_VM2PersuadeResultsCash2", Replacements = { M = WithComma( cashCollected ), N = tostring( candidates ) } } )
		Interface.SetComponentProperties( "PrisonLotteryPersuadeResults", { Caption = "reportTooltip_VM2PersuadeResults2", Replacements = { X = tostring( prisonersYes ), Y = tostring( prisonersNo ), Z = tostring( prisonersNotSure ) } } )
		if candidates > 0 then
			Set(this,"PrisonersPersuaded",true)
		end
		Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
	end
end

function ButtonPressed_PlaceYourOwnBetStart()
	this.YourOwnBetPressedStart = true
	Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
end

function ButtonPressed_PlaceYourOwnBetWardenIsWinner()
	Set(this,"YourBetWinner","reportTooltip_VM2LotteryWinnerWarden")
	this.YourOwnBetPressedWinner = true
	Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
end

function ButtonPressed_PlaceYourOwnBetPrisonerIsWinner()
	Set(this,"YourBetWinner","reportTooltip_VM2LotteryWinnerPrisoner")
	this.YourOwnBetPressedWinner = true
	Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
end

function ButtonPressed_PlaceYourOwnBetStaffMemberIsWinner()
	Set(this,"YourBetWinner","reportTooltip_VM2LotteryWinnerStaffMember")
	this.YourOwnBetPressedWinner = true
	Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
end

function ButtonPressed_PlaceYourOwnBetPowerStation()
	if not this.MusicFxDisabled then this.Sound("__FoodFeud","FamilySuccession5") end
	Set(this,"YourBetObject","a PowerStation")
	this.YourOwnBetPressedObject = true
	Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
end

function ButtonPressed_PlaceYourOwnBet5K()
	if not this.MusicFxDisabled then this.Sound("__FoodFeud","FamilySuccession5") end
	Set(this,"YourBetObject","$ 5,000")
	this.YourOwnBetPressedObject = true
	Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
end

function ButtonPressed_PlaceYourOwnBetCancelBet()
	if not this.MusicFxDisabled then this.Sound("__FoodFeud","FamilySuccession4") end
	this.YourOwnBetPressedStart = nil
	this.YourOwnBetPressedWinner = nil
	this.YourOwnBetPressedObject = nil
	Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
end

function ButtonPressed_StartLottery()
	if this.TicketsSold >= this.TicketsSoldRequired then
		if not this.WeeklyLottery then this.SylvesterLotteryDone = true end
		this.CountDownTheMinutes = nil
		KeepMyWardenLoaded()
		Set(MyWarden,"CarrierId.i",this.Slot3.i)
		Set(MyWarden,"CarrierId.u",this.Slot3.u)
		Set(MyWarden,"Loaded",true)
		Set(this,"Slot3.i",MyWarden.Id.i)
		Set(this,"Slot3.u",MyWarden.Id.u)
		MyLotteryOfficial = Object.Spawn("LotteryOfficial",this.Pos.x,this.Pos.y+1)
		Object.CreateJob(this,"StartValidatingTickets")
		DoTheLotteryCountdown()
		this.LotteryCountdownStarted = true
		Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
	else
		if not this.MusicFxDisabled then this.Sound("__RiotRoulette","RouletteMusic17") end
	end
end

function ButtonPressed_ContinueToResults()
	this.YourBetResultShown = true
	Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
end

function ButtonPressed_ResetLotterySafe()
	ResetLotterySafeAndTickets()
	Interface.SetReportTabs("reportTab_VM2LotteryTab1","reportTab_VM2LotteryTab2","reportTab_VM2LotteryTab3")
end

function RndRemove(theObject)
	local nearbyObject = Find(this,theObject,10000)
	if next(nearbyObject) then
		maxObj = 0
		for thatObject, dist in pairs(nearbyObject) do
			maxObj = maxObj + 1
		end
		--print(maxObj.."  "..theObject)
		rndObject = math.random(1,maxObj)
		i = 0
		for thatObject, dist in pairs(nearbyObject) do
			i = i + 1
			if i == rndObject then
				thatObject.Damage = 1
				thatObject.Powered = false
				thatObject.On = false
			end
		end
	end
end

function WithComma(theAmount)
	if theAmount ~= nil then
		local n = tonumber(theAmount)
		local left,num,right = string.match(n,'^([^%d]*%d)(%d*)(.-)$')
		return left..(num:reverse():gsub('(%d%d%d)','%1,'):reverse())..right
	else
		return 0,00
	end
end

function CalculateDaysLeft(theInterval)
	this.LotteryDaysInterval = theInterval
	local startingDay = math.floor(this.LotteryStart/1440)
	local currentDay = math.floor(World.TimeIndex/1440)
	local daysUntilNextLottery = this.LotteryDaysInterval - (currentDay - startingDay)
	if daysUntilNextLottery < 0 then daysUntilNextLottery = 0 end
	Set(this,"NextLotteryDay",daysUntilNextLottery)
	Interface.SetComponentProperties( "LotterySettingsInterval", { Replacements = { X = tostring( this.NextLotteryDay ) } } )
	Interface.SetComponentProperties( "NextLotteryDay", { Replacements = { X = tostring( this.NextLotteryDay ) } } )
end

function CalculatePrisonCapacity(theNumber)
	this.CapacityMultiplier = theNumber
	local MaxCapacity = World.NumPrisoners
	local TicketsRequired = (MaxCapacity.Normal + MaxCapacity.Protected + MaxCapacity.MinSec + MaxCapacity.MaxSec + MaxCapacity.DeathRow + MaxCapacity.SuperMax) * this.CapacityMultiplier
	Set(this,"TicketsSoldRequired",TicketsRequired)
	
	Interface.SetComponentProperties( "ToggleCapacityMultiplier", { Replacements = { C = tostring( this.CapacityMultiplier ), S = tostring( this.TicketsSoldRequired ) } } )
	
	Interface.SetComponentProperties( "TicketsSoldRequired", { Replacements = { X = tostring( this.TicketsSoldRequired ) } } )
end

function ResetLotterySafeAndTickets()
	if MyLotteryWinnerMarker == nil then
		local LotteryWinnerMarkers = Find(this,"LotteryWinnerMarker",10000)
		if next(LotteryWinnerMarkers) then
			for thatMarker, dist in pairs(LotteryWinnerMarkers) do
				if Get(thatMarker,"WinnerID") ~= nil then
					MyLotteryWinnerMarker = thatMarker
				end
			end
		end
		LotteryWinnerMarkers = nil
	end
	if MyLotteryWinnerMarker == nil or MyLotteryWinnerMarker.SubType == nil then
		if this.LotteryDaysInterval == nil or this.LotteryDaysInterval == 0 then Set(this,"LotteryDaysInterval",28) end
		if this.CapacityMultiplier == nil then Set(this,"CapacityMultiplier",2) end
		
		if not this.WeeklyLottery then
			currentDay = math.ceil(World.TimeIndex/1440)
			--print("day: "..currentDay)
			NextSpringStartsOnDay = (currentDay + (28 - math.mod(currentDay,28)))
			--print("NextSpringStartsOnDay: "..NextSpringStartsOnDay)
			Set(this,"NextLotteryDay",NextSpringStartsOnDay - currentDay)
			daysUntilNextLottery = NextSpringStartsOnDay - currentDay
			--print("NextLotteryDay: "..this.NextLotteryDay)
		else
			Set(this,"LotteryStart",math.floor(World.TimeIndex))
			startingDay = math.floor(this.LotteryStart/1440)
			currentDay = math.floor(World.TimeIndex/1440)
			daysUntilNextLottery = this.LotteryDaysInterval - (currentDay - startingDay)
			Set(this,"NextLotteryDay",daysUntilNextLottery)
		end
		
		if daysUntilNextLottery < 0 then daysUntilNextLottery = 0 end
		Set(this,"TicketsSold",0)
		if not this.WardenReturns then
			Set(this,"TotalStake",0)
		else
			Set(this,"TotalStake",this.WardenReturns)
			Set(this,"WardenReturns",nil)
		end
		Set(this,"LastStake",0)
		Set(this,"Outcome","reportTooltip_VM2LotteryOutcome7")
		Set(this,"LotteryEnd",nil)
		Set(this,"LotteryCountdownStarted",nil)
		Set(this,"LotteryCountdownFinished",nil)
		Set(this,"SoldTicketsListShown",nil)
		Set(this,"LeftoversRemoved",nil)
		Set(this,"ContinuedToResults",nil)
		Set(this,"PrisonersMad",nil)
		Set(this,"GuardGunsUpgraded",nil)
		Set(this,"WeHaveAWinner",nil)
		Set(this,"YourOwnBetPressedObject",nil)
		Set(this,"YourBetObject",nil)
		Set(this,"WinningTicket",nil)
		Set(this,"LotteryEnd",nil)
		Set(this,"LotteryDone",nil)
		Set(this,"TicketWasSold",nil)
		Set(this,"theLotteryWinner",nil)
		Set(this,"YourBetWinner",nil)
		Set(this,"YourBetResultShown",nil)
		Set(this,"Jackpot",nil)
		Set(this,"JackpotDonated",nil)
		Set(this,"JackpotUnavailable",nil)
		Set(this,"JackpotUnfair",nil)
		Set(this,"YourOwnBetPressedStart",nil)
		Set(this,"YourOwnBetPressedWinner",nil)
		Set(this,"LotteryEnabled",nil)
		Set(this,"NotSpread",nil)
		Set(this,"OtherWinner1",nil)
		Set(this,"OtherWinner2",nil)
		Set(this,"OtherWinner3",nil)
		Set(this,"OtherWinner4",nil)
		Set(this,"OtherWinner5",nil)
		Set(this,"OtherWinner6",nil)
		Set(this,"OtherWinner1ID",nil)
		Set(this,"OtherWinner2ID",nil)
		Set(this,"OtherWinner3ID",nil)
		Set(this,"OtherWinner4ID",nil)
		Set(this,"OtherWinner5ID",nil)
		Set(this,"OtherWinner6ID",nil)
		Set(this,"DecideFirst",nil)
		Set(this,"NoTicketsWereSold",nil)
		Set(this,"StartedTicketsValidating",nil)
		Set(this,"ValidatingInterface",nil)
		Set(this,"ValidatingTheTickets",nil)
		Set(this,"TicketsAreValidated",nil)
		Set(this,"PrisonersPersuaded",nil)
		Set(this,"ReportTabsSet",nil)
		Set(this,"CountDownTheMinutes",nil)
		Set(this,"countdownToHour",nil)
		Set(this,"countdownToMinute",nil)
		cashCollected = 0
		prisonerSpends = 0
		persuasionChance = 0
		candidates = 0
		prisonersYes = 0
		prisonersNo = 0
		prisonersNotSure = 0
		for _, typ in pairs(entityGroup) do
			local entityType = Find(this,typ,10000)
			for thatEntity, _ in pairs(entityType) do
				if Get(thatEntity,"TicketsBought") ~= nil then
					for i=1,thatEntity.TicketsBought do
						Set(thatEntity,"T"..i,nil)
					end
					Set(thatEntity,"TicketsBought",nil)
				end
			end
		end
		FindWarden()
		MyWarden.Carrying.i = -1
		MyWarden.Carrying.u = -1
		MyWarden.Tooltip = ""
		CurrentTicketShown = nil
		if not this.WeeklyLottery then
			Set(this,"TicketsSoldRequired",1000)
		else
			CalculatePrisonCapacity(this.CapacityMultiplier)
		end
		Interface.SetComponentProperties( "TicketsSold", { Replacements = { A = WithComma( this.TicketsSold ) } } )
		Interface.SetComponentProperties( "TotalStake", { Replacements = { A = WithComma( this.TotalStake ) } } )
		Interface.SetComponentProperties( "LastStake", { Replacements = { A = WithComma( this.LastStake ) } } )
		Interface.SetComponentProperties( "NextLotteryDay", { Replacements = { X = tostring( this.NextLotteryDay ) } } )
		timePerUpdate = 0
	else
		this.DecideFirst = true
	end
end

function JobComplete_OpenLotterySafe()
	this.Opened = true
	this.SubType = this.SubType + 1
end

function JobComplete_StoreStakeInSafe()
	this.SubType = this.SubType - 1
	myStack = getObject("Stack",this.Slot0.i,2)
	if myStack ~= nil then
		Set(this,"TotalStake",Get(this,"TotalStake") + Get(myStack,"Quantity"))
		this.Slot0.i = -1
		this.Slot0.u = -1
		myStack.CarrierId.i = -1
		myStack.CarrierId.u = -1
		myStack.Loaded = false
		myStack.Delete()
		myStack = nil
	end
	timePerUpdate = 0
	this.Opened = nil
end

function JobComplete_StartValidatingTickets()
	this.StartedTicketsValidating = true
end

function JobComplete_ValidateTickets()
	this.ValidatingTheTickets = true
end
