evento = {};
VarPosOriginal= {x = 381075.66519277, z = -350696.1185350};
VarPosInicialPlayer= {x = VarPosOriginal.x, z = VarPosOriginal.z};
missionType = 0;
missionSubType = 0;
originComboy = nil;
destinationComboy = nil;
comboyAllyGroup = nil;
nameComboyGroup = "";
isComboyCreated = false;
comboyAttackerGroup = nil;
timer1 = 0;
counterCAP = 0;
isRandomInProgress = false;
isMissionEnded = false;
isMissionWin = false;
isMissionLose = false;
isComboyMoving = false;
isEnemyComboyCreated = false;
strRandoms = "";
isPlayerRefueling = false;
isPlayerInRangeCAP = false;

CampStaticTarget = nil;
CampDefencesTarget = nil;
CampSAMTarget = nil;
varCampTargetName = "";
isEnemyCampCreated = false;
isCampRecon = false;
isNotReconInit = true;

CampSAMRoute = nil;

isMarkCapAdded = false;

airAllyBombers = nil;
nameAllyBombersGroup = "";

airAllyAir = nil;
nameAllyAirGroup = "";
local nameAllySEADGroup = "";


hostileAirGroup = nil;
nameHostileAirGroup = "";
hostileBomberGroup = nil
nameHostileBomberGroup = "";			
isHostilesAirGroupCreated = false;
isHostilesBomberGroupCreated = false;
isShirazBombed = false;

hostileAirGroupExtra = nil;
nameHostileAirGroupExtra = "";
isHostilesAirGroupExtraCreated = false;

hostileAirSwarm1 = nil;
nameHostileSwarm1 = "";
hostileAirSwarm2 = nil;
nameHostileSwarm2 = "";
hostileAirSwarm3 = nil;
nameHostileSwarm3 = "";
hostileAirSwarm4 = nil;
nameHostileSwarm4 = "";
isHostilesAirSwarmCreated = false;

hostileDefenderAirGroup = nil;
nameHostileDefenderAirGroup = "";
isHostilesDefenderAirGroupCreated = false;

civilAirGroup = nil;
nameCivilAirGroup = "";
isCivilAirGroupCreated = false;
isCivilIntercepted = false;
isCheckCivil = false;
isCivilEscortInterceptorsCreated = false;
isCivilEscortInterceptorsExtraCreated = false;
ROECivilEscortInterceptors = "HOSTILE"

notHostileAirGroup = nil;
nameNotHostileAirGroup = "";
isNotHostileAirGroupCreated = false;
typeNotHostileInDestiny = 0;
WP1NotHostile = nil;
WP2NotHostile = nil;

allyTroopsGroup = nil;
nameAllyTroopsGroup = nil;

cargo1 = nil
cargo2 = nil
cargo3 = nil
isCargo1FarAwayWarned = false
isCargo2FarAwayWarned = false
isCargo3FarAwayWarned = false


PlayerWP1 = nil;		
PlayerWP2 = nil;

briefingCounter = 0;

AccountingBalance = 50000;
bombsAlreadyCharged = "";

isSoundBogeiDone = false;


isPlayingMusic = false;
continueMusic = true;
isFirstPlayer = true;

Mission1Done = false
Mission2Done = false
Mission3Done = false
Mission4Done = false
Mission5Done = false
Mission6Done = false
Mission7Done = false
Mission8Done = false
Mission9Done = false
Mission10Done = false
Mission11Done = false
Mission12Done = false
Mission13Done = false
Mission14Done = false
Mission15Done = false
Mission16Done = false
Mission17Done = false
Mission18Done = false
Mission19Done = false
Mission21Done = false
Mission22Done = false
Mission23Done = false
Mission24Done = false
Mission25Done = false
Mission26Done = false
Mission27Done = false
Mission28Done = false
Mission29Done = false
Mission30Done = false


function getPlayersNames()
	local Players = coalition.getPlayers(coalition.side.BLUE)	 
	local playerNames = ""
	for i = 1, #Players do		
		playerNames = playerNames .. Players[i]:getName() .. ";"
	end	
	return playerNames
end


function getPlayersTypes()
	local Players = coalition.getPlayers(coalition.side.BLUE)	 
	local playerTypes = ""
	for i = 1, #Players do		
		playerTypes = playerTypes .. Players[i]:getTypeName() .. ";"
	end	
	return playerTypes
end


function SaveInFile(fileName, text, needDelete)	
	
		local fdir = lfs.writedir() .. [[Missions\Campaigns\en\Area18\Status\]] .. fileName
		
		if needDelete == true then
			io.open(fdir,"w"):close()
		end

		local f,err = io.open(fdir,"a")
		if not f then
				local errmsg = "Error: Need to create new folder " .. fdir
				trigger.action.outText(errmsg, 10)
				return print(err)
		end
		
		
		f:write(text)
		f:close()
end


function getCostLaunchedWeapon(weapon)
	local cost = 0
	local weapCategory = ""
	local weapGuidance = ""
	local warHead = nil
	local bombExplosiveMass = 0
	weapCategory = weapon:getCategory()
	weapCategory = weapon:getDesc()["category"]
	weapMissCategory = weapon:getDesc()["missileCategory"]
	weapGuidance = weapon:getDesc()["guidance"]
	warHead = weapon:getDesc()["warhead"]
	if warHead ~= nil then
		bombExplosiveMass = warHead["explosiveMass"]
	end
	
	--si son cargos, lanzarlos no cuesta dinero
	if weapon:getTypeName() ~= nil and string.match(weapon:getTypeName(), "weapons.bombs.IFV BMD") then			
		return 0
	end
	
	
	if weapCategory == 0 then --shells
		cost = 20
		
	elseif weapCategory == 1 then ---------missiles
		if weapGuidance == 1  then --INS (mavs)
			cost = 50
		elseif weapGuidance == 2 then --IR
			cost = 80
		elseif weapGuidance == 3 then -- RADAR_ACTIVE (AIM-120)
			cost = 400
		elseif weapGuidance == 4 then -- RADAR_SEMI_ACTIVE (AIM-7)
			cost = 200
		elseif weapGuidance == 5 then -- RADAR_PASSIVE (AIM-9)
			cost = 100
		elseif weapGuidance == 6 then -- TV
		
		elseif weapGuidance == 7 then -- LASER
			cost = 80
		else --OTHERS
			cost = 30
		end	
		
	elseif weapCategory == 2 then ------------rockets
		cost = 0		
	elseif weapCategory == 3 then ----------bombs
		if weapGuidance == 1  then --INS
			cost = 50
		elseif weapGuidance == 2 then --IR
			cost = 80
		elseif weapGuidance == 3 then -- RADAR_ACTIVE
			cost = 400
		elseif weapGuidance == 4 then -- RADAR_SEMI_ACTIVE
			cost = 200
		elseif weapGuidance == 5 then -- RADAR_PASSIVE
			cost = 100
		elseif weapGuidance == 6 then -- TV
		
		elseif weapGuidance == 7 then -- LASER
			cost = 80
		else --OTHERS
			cost = 30
		end	
		
		if bombExplosiveMass ~= nil and bombExplosiveMass >= 100 then
			cost = cost*1.5
		end
		
	end
		trigger.action.outText("Weapon IBCs cost: ".. cost, 10)
		--tableVals(weapon:getDesc())
	return cost
end


--meter en un trigger continuo
function checkPlayerBombing()
	local Players = coalition.getPlayers(coalition.side.BLUE)	 
	for i = 1, #Players do
		chargeBombLaunched(Players[i]:getName())
	end	
end


local ifFoundBomb = function(weapon, val)	 	
	local weapCategory = weapon:getDesc()["category"]		 	
	local weapName = weapon:getName()
	local cost = 0
	
	if not string.match(bombsAlreadyCharged:gsub("%-", "_"), weapName:gsub("%-", "_") .. ";") then
		if weapCategory == 3 then --solo bombas. Los misiles a través de un evento
			cost = getCostLaunchedWeapon(weapon)	
		end
		
		if cost > 0 then		
			--trigger.action.outText("Weapon launched type: ".. weapon:getTypeName(), 10)
			SaveInFile("financings.lua", "\n AccountingBalance = AccountingBalance - " .. cost .. " -- weapon spend: " .. weapon:getTypeName(), false)		
			bombsAlreadyCharged = bombsAlreadyCharged .. weapName  .. ";" -- para que no cobre 2 veces la misma bomba
			AccountingBalance = AccountingBalance - cost		
			trigger.action.outText("Weapon IBCs cost: ".. cost, 10)
		end	
	end	
	
	 --tableVals(weapon:getDesc())
 end


function chargeBombLaunched(unitName)
	local unidad = Unit.getByName(unitName)
	if unidad ~= nil then		
		local volS = {
				id = world.VolumeType.SPHERE,
				params = {
					point = unidad:getPoint(),
					radius = 5
				}
			} 		 
		world.searchObjects(Object.Category.WEAPON, volS, ifFoundBomb)
	end	
end


function evento:onEvent(event)	

--trigger.action.outText("tipo evento: ".. world.event.S_EVENT_SHOT, 10)
	
	if (world.event.S_EVENT_SHOT == event.id) then
		-- Comprobar si el que dispara es un jugador
		local initiatorAircraft = event.initiator:getName()
		if string.match(getPlayersNames():gsub("%-", "_"), initiatorAircraft:gsub("%-", "_") .. ";" ) then
			local _weapon = event.weapon								
			local cost = getCostLaunchedWeapon(_weapon)
			
			if cost > 0 then
				--trigger.action.outText("Weapon launched type: ".. _weapon:getTypeName(), 10)
				SaveInFile("financings.lua", "\n AccountingBalance = AccountingBalance - " .. cost .. " -- weapon spend: " .. _weapon:getTypeName(), false)									
				AccountingBalance = AccountingBalance - cost		
			end
				--tableVals(_weapon:getDesc())
		end	
		
	elseif (world.event.S_EVENT_UNIT_LOST == event.id) then	
			
		if event.initiator ~= nil and event.initiator:getName() ~= nil and event.initiator:getTypeName() ~= nil and event.initiator:getCategory() ~= nil then
			local initiatorObject = event.initiator:getName()
			local unitType = string.upper(event.initiator:getTypeName())
			local unitCategory = event.initiator:getCategory()
			
			local unitCoalition = 7
			
			if unitCategory == Object.Category.STATIC or unitCategory == Object.Category.UNIT then
				unitCoalition = event.initiator:getCoalition()
			end
			
			
			--trigger.action.outText("unidadDestruida: ".. initiatorObject, 10)
			--trigger.action.outText("tipoUnidad: ".. unitType, 10)		
			--trigger.action.outText("coalicion: ".. unitCoalition, 10)
			--trigger.action.outText("categoria: ".. unitCategory, 10)
				
			local cost = 0	
				
			if unitCoalition == coalition.side.RED then --coalicion roja
				if event.initiator:getCategory() == Object.Category.STATIC then
					cost = 3000
				elseif event.initiator:getCategory() == Object.Category.UNIT then
					if unitType == "BTR-80" then
						cost = 7500
					elseif unitType == "M 818" then				
						cost = 2000
					elseif unitType == "URAL-375 ZU-23 INSURGENT" then				
						cost = 6000
					elseif unitType == "M1043 HMMWV ARMAMENT" then				
						cost = 4500
					elseif unitType == "INFANTRY AK INS" then				
						cost = 100
					elseif unitType == "LAND_ROVER_109_S3" then				
						cost = 2000
					elseif unitType == "ZU-23 CLOSED INSURGENT" then				
						cost = 6000
					elseif unitType == "IGLA MANPAD INS" then				
						cost = 4000
					elseif unitType == "SA-18 IGLA COMM" then				
						cost = 2000
					elseif unitType == "T-55" then				
						cost = 9000
					elseif unitType == "KUB 1S91 STR" then				
						cost = 7000
					elseif unitType == "KUB 2P25 LN" then				
						cost = 5000
					elseif unitType == "SA-11 BUK CC 9S470M1" then				
						cost = 5000
					elseif unitType == "SA-11 BUK SR 9S18M1" then				
						cost = 7000
					elseif unitType == "SA-11 BUK LN 9A310M1" then				
						cost = 5000
					elseif unitType == "MIG-29A" then				
						cost = 17000
					elseif unitType == "F-16C_50" or unitType == "F-16C BL.50" then	--	F-16C BL.50		
						cost = 17000
					elseif unitType == "A10C" or unitType == "A-10C" then				
						cost = 12000
					elseif unitType == "SU-25" then				
						cost = 12000
					elseif unitType == "MIG-19P" then				
						cost = 8000
					elseif unitType == "F-4E" then				
						cost = 8000
					else
						cost = 3000
					end	
				end
				
				if cost > 0 then
						trigger.action.outText("Enemy unit destroyed. Earned IBCs: ".. cost, 10)
						SaveInFile("financings.lua", "\n AccountingBalance = AccountingBalance + " .. cost .. " -- Target Destroyed: " .. unitType, false)									
						AccountingBalance = AccountingBalance + cost					
				end
				
			elseif unitCoalition == coalition.side.BLUE	then -- coalicion azul	
				--comprobamos si el obj destruido es un jugador
				if string.match(getPlayersNames():gsub("%-", "_"), initiatorObject:gsub("%-", "_") .. ";") and unitType ~= "VNAO_READY_ROOM" then						
					if unitType == "A10A" or unitType == "A-10A" then
						cost = 17000
					elseif unitType == "A10C" or unitType == "A-10C" then				
						cost = 20000
					elseif unitType == "SU-25T" or unitType == "SU-25" then				
						cost = 17000
					elseif unitType == "FA-18C_HORNET" then				
						cost = 40000
					elseif unitType == "F-14B" or unitType == "F-14A-135-GR"  then				
						cost = 35000
					elseif unitType == "AV8BNA" then				
						cost = 25000
					elseif unitType == "SU-33" or unitType == "SU-27" then				
						cost = 20000
					elseif unitType == "F15-C" then
						cost = 20000
					elseif unitType == "SA342L" then
						cost = 12000
					elseif unitType == "SA342M" then
						cost = 16000
					elseif unitType == "SA342MISTRAL" then
						cost = 12000
					elseif unitType == "SA342MINIGUN" then
						cost = 8000
					elseif unitType == "KA-50" then
						cost = 32000
					elseif unitType == "MI-8MT" then
						cost = 15000
					elseif unitType == "UH-1H" then
						cost = 15000
					elseif unitType == "MQ9_PREDATOR_B" or unitType ==  "MQ9_PREDATOR" then
						cost = 5000
					elseif unitType == "A10C" or unitType == "A-10C" then				
						cost = 33000
					elseif unitType == "JF-17" then				
						cost = 38000
					elseif unitType == "F-16C_50" or unitType == "F-16C BL.50" then				
						cost = 38000			
					elseif unitType == "AJS37" then				
						cost = 15000
					elseif unitType == "C-101CC" or unitType == "C-101EB" then				
						cost = 13000
					elseif unitType == "F-5E-3" or unitType == "F-5E" then			
						cost = 16000
					elseif unitType == "F-86F SABRE" then				
						cost = 15000
					elseif unitType == "M-2000C" then				
						cost = 18500
					elseif unitType == "HERCULES" then
						cost = 20000
					elseif unitType == "MB-339PAN" then
						cost = 10000	
					elseif unitType == "T-45" then
						cost = 11000		
					else				
						cost = 13000	
					end
					
					if cost > 0 then
						trigger.action.outText("Player unit destroyed. Lost IBCs: ".. cost, 10)
						SaveInFile("financings.lua", "\n AccountingBalance = AccountingBalance - " .. cost .. " -- aircraft lost: " .. unitType, false)									
						AccountingBalance = AccountingBalance - cost					
					end
				end
			
			end		
		end	
	elseif (world.event.S_EVENT_TAKEOFF == event.id) then		
		local _aircraftName = event.initiator:getName()
				
		if string.match(getPlayersNames():gsub("%-", "_"), _aircraftName:gsub("%-", "_")) and missionType == 1 and missionSubType == 4 and isHostilesAirSwarmCreated == false then				
			    --trigger.action.outText("aeronave: ".. _aircraftName, 10)			
			-- Swarm hostiles attack
				local attackers = createHostilesSwarm({x = VarPosOriginal.x, y = VarPosOriginal.z}, 120000, 180000)			
				hostileAirSwarm1 = attackers.Group1
				hostileAirSwarm2 = attackers.Group2
				hostileAirSwarm3 = attackers.Group3
				hostileAirSwarm4 = attackers.Group4
							
				isHostilesAirSwarmCreated = true;	
				
				local randomtime = math.random(20,5)
				
				setMessageDelayed("[AREA18 COMMAND]: India group. Command. Hostile group has been detected heading for Shiraz. Intercept and destroy them.", 10, randomtime)					
				setSoundDelayed("DELINDIAHostilegroupdetectedheadingR.ogg", randomtime)
		end	
		
		if string.match(getPlayersNames():gsub("%-", "_"), _aircraftName:gsub("%-", "_")) and
			(missionType == 1 and missionSubType == 5) and isCivilAirGroupCreated == true and isSoundBogeiDone == false then
		-- intercepcion civil						
				setMessageDelayed("[AREA18 COMMAND]:India-25. Command. The bogie does not respond to our require calls for intentification. Contact Overlord to get target's position. Track and identify visualy it as soon as possible. You are not clear to Attack as they do not attack you. Out.", 40, 5, true)
				setMessageDelayed("TIP:(Get near the bogie and use F10 radio menu to request intercept it)", 40, 5, false)
				setSoundDelayed("INDIABogeidoesnotrespondR.ogg", 10)
				isSoundBogeiDone = true
		end		
						
		if string.match(getPlayersNames():gsub("%-", "_"), _aircraftName:gsub("%-", "_")) and isPlayingMusic == true then
			--detiene la musica de taxi			
			timer.scheduleFunction(stopTaxiMusic, nil, timer.getTime() + 15)						
		end
			
	elseif (world.event.S_EVENT_LAND == event.id ) then
		local _aircraftName = event.initiator:getName()
		if string.match(getPlayersNames():gsub("%-", "_"), _aircraftName:gsub("%-", "_")) and isMissionWin == true
			and event.place:getCoalition() == coalition.side.BLUE and isPlayingMusic == false then
				setMessageDelayed("Congratulations for a sucessful mission!", 10, 6)					
				isPlayingMusic = true
				setSoundDelayed("Victory1.ogg", 5)
				--setReturnMusic()
		end
	elseif (world.event.S_EVENT_BIRTH == event.id) then		
		if ((missionType == 4 and missionSubType == 1)) and isMissionEnded == false then
			--trigger.action.outText("tipo: ".. event.initiator:getTypeName(), 10)
			if event.initiator:getTypeName() == "BMD-1" then
				if cargo1 == nil then
					cargo1 = event.initiator:getGroup()
				elseif cargo2 == nil then
					cargo2 = event.initiator:getGroup()
				elseif cargo3 == nil then
					cargo3 = event.initiator:getGroup()
				end
			end						
		end	
	elseif (world.event.S_EVENT_PLAYER_ENTER_UNIT == event.id ) then
		local unitType = string.upper(event.initiator:getTypeName())
		
		if unitType ~= "VNAO_READY_ROOM" and isFirstPlayer == true then
			trigger.action.setUserFlag(11,1) --detiene la musica del briefing
			trigger.action.outText("", 1, true)			
			if ((missionType == 1 and missionSubType == 4)) then --swarm attack
				setMessageDelayed("[BRAVO]: India Group. Bravo 1-1. We are ready to take off at your orders if you need us. Over ", 8, 3, false)
				setSoundDelayed("INDIABravoReady.ogg", 3)
			
				setMessageDelayed("[AREA18 ATC]: India Group. Area 18 ATC. Your mission is priority one. Ignore Shiraz instructions. All runways has been cleared. Take off ASAP from the nearest runway entrance. Over ", 20, 13, false)
				setSoundDelayed("INDIARunwaysCleared.ogg", 13)
				
				isFirstPlayer = false
			elseif  ((missionType == 1 and missionSubType == 1)) or 
					((missionType == 1 and missionSubType == 2)) or	--attack on Shiraz
					((missionType == 1 and missionSubType == 5)) then	--civil aircraft
				setMessageDelayed("[AREA18 ATC]: India Group. Area 18 ATC. Your mission is priority one. Ignore Shiraz instructions. All runways has been cleared. Take off ASAP from the nearest runway entrance. Over ", 20, 13, false)
				setSoundDelayed("INDIARunwaysCleared.ogg", 13)				
				isFirstPlayer = false
			elseif  (missionType == 2 and missionSubType == 4) then				
				setRandomTakeof()				
				if	unitType == 'MB-339PAN' or
					unitType == 'T-45' then
					sayHipsterInitMission()					
				else
					setTaxiRadioMessages1()					
				end
				isFirstPlayer = false	
			else
				if	unitType ~= 'MB-339PAN' and
					 unitType ~= 'T-45' and
					 unitType ~= 'HERCULES'
					 then
					setTaxiRadioMessages1()					
				end				
				setRandomTakeof()
				isFirstPlayer = false				
			end
		elseif string.upper(event.initiator:getTypeName()) == "VNAO_READY_ROOM" and isFirstPlayer == true then					
				trigger.action.outSoundForCoalition(coalition.side.BLUE, "setMission.ogg")
		end
	end	
end;


function playerIsMoving()

	local Players = coalition.getPlayers(coalition.side.BLUE)	 
	local isMoving = false
	for i = 1, #Players do
		local velx = Players[i]:getVelocity().x
		local vely = Players[i]:getVelocity().y
		local velz = Players[i]:getVelocity().z			
		if velx >= 1 or velx <= -1 or
			vely >= 1 or vely <= -1 or
			velz >= 1 or velz <= -1 then
			isMoving = true
		--	trigger.action.outText(velx .. ";" .. vely .. "; " .. velz, 15)
		--else
		--	trigger.action.outText(velx .. ";" .. vely .. "; " .. velz, 15)
		end		
	end	

	return isMoving

end


function launchTaxiMusic()
	local allPlayersHaveRadio
	
	if string.match(getPlayersTypes():gsub("%-", "_"), "MB_339PAN" .. ";" ) or
		string.match(getPlayersTypes():gsub("%-", "_"), "T_45" .. ";" ) or
		string.match(string.upper(getPlayersTypes()):gsub("%-", "_"), "HERCULES" .. ";" )then		
		--trigger.action.outText(" No radio ", 10)
		allPlayersHaveRadio = false
	else
		--trigger.action.outText(" hay radio ", 10)
		allPlayersHaveRadio = true
		setTaxiRadioMessages2()
	end
	
	if ((missionType == 1 and missionSubType == 4)) or --swarm attack
			((missionType == 1 and missionSubType == 1)) or --attack on Shiraz
			((missionType == 1 and missionSubType == 2)) or	--attack on Shiraz		
			((missionType == 1 and missionSubType == 5)) then	--civil aircraft		
		timer.scheduleFunction(setTaxiMusicDark, allPlayersHaveRadio, timer.getTime() + 5)			
		isPlayingMusic = true		
	else
		timer.scheduleFunction(setTaxiMusic, allPlayersHaveRadio, timer.getTime() + 5)			
		isPlayingMusic = true
	end

end

world.addEventHandler(evento);


function SaveLog(cadena)
		
		local fdir = lfs.writedir() .. [[Missions\]] .. "log.lua"

		local f,err = io.open(fdir,"a")
		if not f then
				local errmsg = "Error: Need to create new folder " .. fdir
				trigger.action.outText(errmsg, 10)
				return print(err)
		end		
		
		f:write(cadena .. "\n")						
					
		f:close()
		
end	


function tableVals(T)   
  for a,b in pairs(T) do 		
		if a ~= nil then
			trigger.action.outText(" dato " .. type(b) .. ": " .. a, 10)
			SaveLog(" dato (" .. type(b) .. "): " .. a)
			else
			trigger.action.outText(" dato nulo", 10)
			SaveLog(" dato nulo")
		end
		if b ~= nil then
			--trigger.action.outText(type(b), 10)
			if type(b) == "table" then
				trigger.action.outText(" inicio tabla ", 10)
				SaveLog(" inicio tabla ")
				tableVals(b)
				trigger.action.outText(" fin tabla ", 10)
				SaveLog(" fin tabla ")
			else
				if type(b) == "boolean"	 then
					trigger.action.outText(" valor " .. (b and 'true' or 'false'), 10)					
					SaveLog(" valor " .. (b and 'true' or 'false'))
				else
					trigger.action.outText(" valor " .. b, 10)					
					SaveLog(" valor " .. b)
				end
			end
				
			else
			trigger.action.outText(" valor nulo", 10)
			SaveLog(" valor nulo")
		end
  end
  return count
end


function doSEAD(attackingGroup, objetiveGroup)

		--objetiveGroup = Group.getByName("testSAM")
		--trigger.action.outText("attack_Group: " .. attackingGroup:getID(), 30)    		
		--trigger.action.outText("victim_Group: " .. objetiveGroup:getID(), 30)    		
				
	if objetiveGroup ~= nil then	
				
		local routePoints = {}
		
		local AttackGroup = { 
		  id = 'AttackGroup', 
		  params = { 
			groupId = objetiveGroup:getID(),    
		  } 
		}
		
		--trigger.action.markToAll(1, "Starting point", {x = 25, y = 23, z = 060})												
			routePoints[1] = {
					action = "Fly Over Point",
					type= "Turning Point",
					x = attackingGroup:getUnit(1):getPoint().x,
					y = attackingGroup:getUnit(1):getPoint().z,
					alt = 5000,
					alt_type = "RADIO",
					speed = 350,
					ETA = 100,
					ETA_locked = false,
					name = "Starting point", 
					task = nil,
					}	
		
			routePoints[2] = {
					action = "Fly Over Point",
					type= "Turning Point",
					x = objetiveGroup:getUnit(1):getPoint().x,
					y = objetiveGroup:getUnit(1):getPoint().z,
					alt = 6000,
					alt_type = "BARO",
					speed = 350,
					ETA = 100,
					ETA_locked = false,
					name = "WP1", 
					task = nil,
					}
			
		--trigger.action.markToAll(2, "Destination point", {x = xDestiny, y = 0, z = yDestiny})
		
		
		local _mission = { 
            id = 'Mission', 
            params = { 
				airborne = true,
                route = { 
                    points = routePoints
                }, 
            } 
        }
		
			
		local _controller = attackingGroup:getController();
		_controller:setOption( AI.Option.Air.id.ROE, AI.Option.Air.val.ROE.WEAPON_FREE )
		_controller:setOption( AI.Option.Air.id.REACTION_ON_THREAT, AI.Option.Air.val.REACTION_ON_THREAT.EVADE_FIRE )
		_controller:pushTask(_mission)
		--trigger.action.outText("ataque asignado", 30)	
		
	end
	
end


function doGroupBombing(attackingGroup, objetiveGroup)

		trigger.action.outText("doGroupBombing", 30)    		

		trigger.action.outText("attack_Group: " .. attackingGroup:getID(), 30)    		
		trigger.action.outText("victim_Group: " .. objetiveGroup:getID(), 30)    		
					
		local routePoints = {}
		
		local AttackGroup = { 
		  id = 'AttackGroup', 
		  params = { 
			groupId = objetiveGroup:getID(),    
		  } 
		}
		
		--trigger.action.markToAll(1, "Starting point", {x = 25, y = 23, z = 060})												
			routePoints[1] = {
					action = "Fly Over Point",
					type= "Turning Point",
					x = attackingGroup:getUnit(1):getPoint().x,
					y = attackingGroup:getUnit(1):getPoint().z,
					alt = 5000,
					alt_type = "RADIO",
					speed = 350,
					ETA = 100,
					ETA_locked = false,
					name = "Starting point", 
					task = nil,
					}	
		
			routePoints[2] = {
					action = "Fly Over Point",
					type= "Turning Point",
					x = attackingGroup:getUnit(1):getPoint().x + 100,
					y = attackingGroup:getUnit(1):getPoint().z + 0,
					alt = 8000,
					alt_type = "BARO",
					speed = 350,
					ETA = 100,
					ETA_locked = false,
					name = "WP1", 
					task = AttackGroup,
					}
			
		--trigger.action.markToAll(2, "Destination point", {x = xDestiny, y = 0, z = yDestiny})
		
		
		local _mission = { 
            id = 'Mission', 
            params = { 
				airborne = true,
                route = { 
                    points = routePoints
                }, 
            } 
        }
		
		local _controller = attackingGroup:getController();
		Controller.setOption(_controller, AI.Option.Ground.id.ALARM_STATE, AI.Option.Ground.val.ALARM_STATE.RED)
		_controller:setTask(_mission)
		--trigger.action.outText("ataque asignado", 30)		
end;


function hostileAttackAWACS(attackingGroup, objetiveGroup)

		--trigger.action.outText("attack_Group: " .. attackingGroup:getUnit(1):getPoint().x, 3)    		
		--trigger.action.outText("victim_Group: " .. objetiveGroup:getUnit(1):getPoint().z, 3)    		
					
		local routePoints = {}
		
		local AttackGroup = { 
		  id = 'AttackGroup', 
		  params = { 
			groupId = objetiveGroup:getID(),    
		  } 
		}
		
		--trigger.action.markToAll(1, "Starting point", {x = 25, y = 23, z = 060})												
			routePoints[1] = {
					action = "Fly Over Point",
					type= "Turning Point",
					x = attackingGroup:getUnit(1):getPoint().x,
					y = attackingGroup:getUnit(1):getPoint().z,
					alt = 5000,
					alt_type = "RADIO",
					speed = 350,
					ETA = 100,
					ETA_locked = false,
					name = "Starting point", 
					task = nil,
					}	
			
			routePoints[2] = {
					action = "Fly Over Point",
					type= "Turning Point",
					x = (attackingGroup:getUnit(1):getPoint().x) + ((VarPosOriginal.x - attackingGroup:getUnit(1):getPoint().x) / 1.2) ,
					y = (attackingGroup:getUnit(1):getPoint().z) + ((VarPosOriginal.z - attackingGroup:getUnit(1):getPoint().z) / 1.2),
					alt = 8000,
					alt_type = "BARO",
					speed = 350,
					ETA = 100,
					ETA_locked = false,
					name = "WP1", 
					task = nil,
					}
			
		--trigger.action.markToAll(2, "Destination point", {x = xDestiny, y = 0, z = yDestiny})
		
		
		local _mission = { 
            id = 'Mission', 
            params = { 
				airborne = true,
                route = { 
                    points = routePoints
                }, 
            } 
        }
		
		local _controller = attackingGroup:getController();
		--Controller.setOption(_controller, AI.Option.Ground.id.ALARM_STATE, AI.Option.Ground.val.ALARM_STATE.RED)
		_controller:setTask(_mission)
		--trigger.action.outText("ataque asignado", 3)		
end;


function hostileAttackPlayer(attackingGroup)

		--trigger.action.outText("hostileAttackPlayer ", 20)    				
					
		local routePoints = {}
		local targetGroup = coalition.getPlayers(coalition.side.BLUE)[1]: getGroup()
		
		local AttackGroup = { 
		  id = 'AttackGroup', 
		  params = { 
			groupId = targetGroup:getID(),    
		  } 
		}
				
		--trigger.action.outText("hostileAttackPlayer2 ", 20)    								
				
			routePoints[1] = {
					action = "Fly Over Point",
					type= "Turning Point",
					x = attackingGroup:getUnit(1):getPoint().x,
					y = attackingGroup:getUnit(1):getPoint().z,
					alt = 10000,
					alt_type = "RADIO",
					speed = 350,
					ETA = 100,
					ETA_locked = false,
					name = "Starting point", 
					task = nil,
					}	
			
			routePoints[2] = {
					action = "Fly Over Point",
					type= "Turning Point",
					x = targetGroup:getUnit(1):getPoint().x,
					y = targetGroup:getUnit(1):getPoint().z,
					alt = 10000,
					alt_type = "BARO",
					speed = 350,
					ETA = 100,
					ETA_locked = false,
					name = "WP1", 
					task = nil,
					}
			
					--trigger.action.outText("hostileAttackPlayer3 ", 20)    								
				
				
		local _mission = { 
            id = 'Mission', 
            params = { 
				airborne = true,
                route = { 
                    points = routePoints
                }, 
            } 
        }
		
		local _controller = attackingGroup:getController();
		--Controller.setOption(_controller, AI.Option.Ground.id.ALARM_STATE, AI.Option.Ground.val.ALARM_STATE.RED)
		_controller:setTask(_mission)
		--trigger.action.outText("ataque asignado", 20)		
end;


function markTargetsBombing()
	--trigger.action.outText("markTargetsBombing groupTarget: " .. CampDefencesTarget:getName(), 10)	
	if isGroupSpottedbyPlayers(CampDefencesTarget) then
		local PosTarget = CampDefencesTarget:getUnit(1):getPoint()
		local lat, long, alt = coord.LOtoLL(PosTarget)
		local coordSTR = getCoordinatesSTR(lat, long)
		menuSpotTargets = missionCommands.removeItem(menuSpotTargets)	
		airAllyBombers = createAllyBombingGroup({x = PosTarget.x, y = PosTarget.z}, 15000, 1)		
		setMessageDelayed("[".. string.upper(nameAllyBombersGroup) .. "]: Romeo group." .. nameAllyBombersGroup .. ". Copied targets for bombing at following coordinates " .. coordSTR.lat .. " " .. coordSTR.long .. ". Standby for run attack. Over", 20, 2)	
		setSoundDelayed("DELROMEOCopiedtargetsbombingcoordinatesR.ogg", 2)
		doGroupBombing(airAllyBombers, CampDefencesTarget)		
		setMessageDelayed("[".. string.upper(nameAllyBombersGroup) .. "]: Romeo group." .. nameAllyBombersGroup .. ". In the target area. Initiating attack. Over", 20, 50)		
		setSoundDelayed("DELROMEOBombergrouptargetareaR.ogg", 50)
		
	else
		trigger.action.outText("(Target is not on sight or you are too far away. You can't mark the target yet)", 10)
		trigger.action.outSoundForCoalition(coalition.side.BLUE, "Beep.wav")
	end
end


function isGroupSpottedbyPlayers(spottedGroup)
	-- no funciona --> desde player hacia enemigos
	-- no funciona --> desde unidades que no tengan armamento (static, o unarmed) hacia enemigos 
	-- no funciona --> desde grupo a grupo 
	-- el truco es que utilizarlo desde el enemigo(grupo), hacia el player(unidad)
	

	--local cosa = Controller.getDetectedTargets(Unit.getByName("unitTest"):getController(), 'VISUAL')
	
	
	local Players = coalition.getPlayers(coalition.side.BLUE)	 
	local isPlayerInRange = false
	for i = 1, #Players do		
		if (spottedGroup:getController():isTargetDetected(Players[i], 'VISUAL') and getDistanceGroups(Players[i]:getGroup(), spottedGroup) < 3000) then
			isPlayerInRange = true
		end
	end	
	
	return isPlayerInRange
		
--	if (Unit.getByName("UH1h_1_1") ~= nil and spottedGroup:getController():isTargetDetected(Unit.getByName("UH1h_1_1"), 'VISUAL') and getDistanceGroups(Group.getByName("UH1h_1"), spottedGroup) < 3000)
--		or (Unit.getByName("UH1h_2_1") ~= nil and spottedGroup:getController():isTargetDetected(Unit.getByName("UH1h_2_1"), 'VISUAL') and getDistanceGroups(Group.getByName("UH1h_2"), spottedGroup) < 3000)
--		or (Unit.getByName("SA342Mg_1_1") ~= nil and spottedGroup:getController():isTargetDetected(Unit.getByName("SA342Mg_1_1"), 'VISUAL') and getDistanceGroups(Group.getByName("SA342Mg_1"), spottedGroup) < 3000)
--		or (Unit.getByName("SA342Mg_2_1") ~= nil and spottedGroup:getController():isTargetDetected(Unit.getByName("SA342Mg_2_1"), 'VISUAL') and getDistanceGroups(Group.getByName("SA342Mg_2"), spottedGroup) < 3000)
--		or (Unit.getByName("SA342Mist_1_1") ~= nil and spottedGroup:getController():isTargetDetected(Unit.getByName("SA342Mist_1_1"), 'VISUAL') and getDistanceGroups(Group.getByName("SA342Mist_1"), spottedGroup) < 3000)
--		or (Unit.getByName("SA342Mist_2_1") ~= nil and spottedGroup:getController():isTargetDetected(Unit.getByName("SA342Mist_2_1"), 'VISUAL') and getDistanceGroups(Group.getByName("SA342Mist_2"), spottedGroup) < 3000)
--		or (Unit.getByName("SA342M_1_1") ~= nil and spottedGroup:getController():isTargetDetected(Unit.getByName("SA342M_1_1"), 'VISUAL') and getDistanceGroups(Group.getByName("SA342M_1"), spottedGroup) < 3000)
--		or (Unit.getByName("SA342M_2_1") ~= nil and spottedGroup:getController():isTargetDetected(Unit.getByName("SA342M_2_1"), 'VISUAL') and getDistanceGroups(Group.getByName("SA342M_2"), spottedGroup) < 3000)
--		or (Unit.getByName("SA342L_1_1") ~= nil and spottedGroup:getController():isTargetDetected(Unit.getByName("SA342L_1_1"), 'VISUAL') and getDistanceGroups(Group.getByName("SA342L_1"), spottedGroup) < 3000)
--		or (Unit.getByName("SA342L_2_1") ~= nil and spottedGroup:getController():isTargetDetected(Unit.getByName("SA342L_2_1"), 'VISUAL') and getDistanceGroups(Group.getByName("SA342L_2"), spottedGroup) < 3000)
--		or (Unit.getByName("Mi8_1_1") ~= nil and spottedGroup:getController():isTargetDetected(Unit.getByName("Mi8_1_1"), 'VISUAL') and getDistanceGroups(Group.getByName("Mi8_1"), spottedGroup) < 3000)
--		or (Unit.getByName("Mi8_2_1") ~= nil and spottedGroup:getController():isTargetDetected(Unit.getByName("Mi8_2_1"), 'VISUAL') and getDistanceGroups(Group.getByName("Mi8_2"), spottedGroup) < 3000)
--		or (Unit.getByName("Ka50_1_1") ~= nil and spottedGroup:getController():isTargetDetected(Unit.getByName("Ka50_1_1"), 'VISUAL') and getDistanceGroups(Group.getByName("Ka50_1"), spottedGroup) < 3000)
--		or (Unit.getByName("Ka50_2_1") ~= nil and spottedGroup:getController():isTargetDetected(Unit.getByName("Ka50_2_1"), 'VISUAL') and getDistanceGroups(Group.getByName("Ka50_2"), spottedGroup) < 3000)
--	then
--		return true;			
--	else
--		--trigger.action.outText("isGroupSpottedbyPlayers: " .. getDistanceGroups(Group.getByName("SA342M_1"), spottedGroup) , 10)
--		return false;
--	end
	
--	if cosa then
--		trigger.action.outText("vista!!!" , 10)
--	else
--		trigger.action.outText("NO vista!!!" , 10)
--	end

end


function showUnitPos(nombre)
	local PosGroupAlly = Unit.getByName(nombre):getPoint();
	--trigger.action.outText("posicion: " .. PosGroupAlly.x .. "; " .. PosGroupAlly.z , 10)
end


function getDistanceGroups(group1, group2)	
	-- la distancia devuelta es en Km
	if group1 ~= nil and group1:getUnit(1) ~= nil and group2 ~= nil and group2:getUnit(1) ~= nil then
		local distance = math.abs(((group1:getUnit(1):getPoint().x  - group2:getUnit(1):getPoint().x)^2 + (group1:getUnit(1):getPoint().z  - group2:getUnit(1):getPoint().z)^2)^(0.5))
		--trigger.action.outText("getDistanceGroups: " .. distance, 10)
		return distance
	else
		--trigger.action.outText("getDistanceGroups: infinito", 10)
		return 100000000000000
	end
	
end


function getDistancePoint(group, point)	
	-- la distancia devuelta es en Km
	if group ~= nil and group:getUnit(1) ~= nil and point ~= nil then
		local distance = math.abs(((group:getUnit(1):getPoint().x  - point.x)^2 + (group:getUnit(1):getPoint().z  - point.y)^2)^(0.5))
		--trigger.action.outText("distancia: " .. distance, 5)
		return distance
	else
		return 100000000000000
	end
	
end


function getDistancePointPoint(point1, point2)	
	-- la distancia devuelta es en Km
	if point1 ~= nil and point2 ~= nil then
		local distance = math.abs(((point1.x  - point2.x)^2 + (point1.y  - point2.y)^2)^(0.5))
		--trigger.action.outText("distancia entre puntos: " .. distance, 5)
		return distance
	else
		return 100000000000000
	end
	
end


function getCoordinatesSTR(decLat, decLong)
	local lat1, latF1 = math.modf(decLat)
	local latF2, latF3 = math.modf(latF1 * 60)
	
	
	local long1, longF1 = math.modf(decLong)
	local longF2, longF3 = math.modf(longF1 * 60)
	return {lat = string.format("%02d", lat1) .. "º " .. string.format("%02d",latF2) .. "' " .. string.format("%02d",math.floor(latF3 * 60)) .. "''N", 
					long = string.format("%02d", long1) .. "º " .. string.format("%02d",longF2) .. "' " .. string.format("%02d",math.floor(longF3 * 60)) .. "''E"}
	
end


function getCallsign()
	local nameRND = math.random(1,10)
	local CallSign = ""
	
	if nameRND == 1 then
		CallSign = "Badger " .. math.random(0,9) .. "-" .. math.random(0,10)
	elseif  nameRND == 2 then
		CallSign = "Bull " .. math.random(0,9) .. "-" .. math.random(0,10)
	elseif  nameRND == 3 then
		CallSign = "Warpig " .. math.random(0,9)	.. "-" .. math.random(0,10)		
	elseif  nameRND == 4 then
		CallSign = "Rhino " .. math.random(0,9) .. "-" .. math.random(0,10)
	elseif  nameRND == 5 then
		CallSign = "Bear " .. math.random(0,9) .. "-" .. math.random(0,10)
	elseif  nameRND == 6 then
		CallSign = "Bison " .. math.random(0,9) .. "-" .. math.random(0,10)
	elseif  nameRND == 7 then
		CallSign = "Buffalo " .. math.random(0,9) .. "-" .. math.random(0,10)
	elseif  nameRND == 8 then
		CallSign = "Wolverine " .. math.random(0,9) .. "-" .. math.random(0,10)
	elseif  nameRND == 9 then
		CallSign = "Wolf " .. math.random(0,9) .. "-" .. math.random(0,10)
	elseif  nameRND == 10 then
		CallSign = "Anvil " .. math.random(0,9) .. "-" .. math.random(0,10)
	end
	
	return CallSign
end		


function getAirCallsign()
	local nameRND = math.random(1,10)
	local CallSign = ""
	
	if nameRND == 1 then
		CallSign = "Lightning " .. math.random(0,20)
	elseif  nameRND == 2 then
		CallSign = "Thunder " .. math.random(0,20)
	elseif  nameRND == 3 then
		CallSign = "Dragon " .. math.random(0,20)
	elseif  nameRND == 4 then
		CallSign = "Cyclon " .. math.random(0,20)
	elseif  nameRND == 5 then
		CallSign = "Storm " .. math.random(0,20)
	elseif  nameRND == 6 then
		CallSign = "Boreas " .. math.random(0,20)
	elseif  nameRND == 7 then
		CallSign = "Vampire " .. math.random(0,20)
	elseif  nameRND == 8 then
		CallSign = "Whirlwind " .. math.random(0,20)
	elseif  nameRND == 9 then
		CallSign = "Zephyr " .. math.random(0,20)
	elseif  nameRND == 10 then
		CallSign = "Hummingbird" .. math.random(0,20)
	end
	
	return CallSign
end	


function setDestiny(groundGroup, minDistance, isOnRoad, factorHelo)
	local numTries = 0
	local PosGroup = groundGroup:getUnit(1):getPoint()
	local xDestiny
	local yDestiny
	local tableDestiny
	local landType
		
	repeat
		--trigger.action.outText("setDestiny, min: " .. minDistance, 5)    
		
		
		local signDestiny1 = 1
		local signDestiny2 = 1
			
		if math.random() >= 0.5 then 
				signDestiny1 = -1
		end;
		if math.random() >= 0.5 then 
				signDestiny2 = -1
		end;
			
		xDestiny = PosGroup.x + (signDestiny1 * math.random(5000,20000 * factorHelo))
		yDestiny = PosGroup.z + (signDestiny2 * math.random(5000,20000 * factorHelo))
		
		if (isOnRoad) then
			local offsetx, offsety = land.getClosestPointOnRoads("roads", xDestiny, yDestiny)
			xDestiny = offsetx
			yDestiny = offsety
			tableDestiny = {x = xDestiny, y = yDestiny}	
			--trigger.action.outText("onroad", 3)    
		else --si no es onroad
			repeat
				xDestiny = PosGroup.x + (signDestiny1 * math.random(1000,1500))
				yDestiny = PosGroup.z + (signDestiny2 * math.random(1000,1500))
				tableDestiny = {x = xDestiny, y = yDestiny}	
				landType = land.getSurfaceType(tableDestiny)	
				--trigger.action.outText("landType " .. landType, 5)    
			until(landType ~= 2 and landType ~= 3)
			tableDestiny = {x = xDestiny, y = yDestiny}	
			--trigger.action.outText("outroad", 3)    
		end;
		numTries = numTries + 1
		
	until getDistancePoint(groundGroup, tableDestiny) >= minDistance or numTries >= 10

	
	return tableDestiny;		
	
end;


function setGroundRoute(groundGroup, tableOrigin, tableDestiny, speedGroupmxs, isOnRoad)

		--trigger.action.outText("setGroundRoute0", 3)    		
					
		local routePoints = {}
		
		local pAction = "Off Road"
		if isOnRoad then
			pAction = "On Road"
		end;
		
		--trigger.action.markToAll(1, "Starting point", {x = 25, y = 23, z = 060})												
			routePoints[1] = {
					action = pAction,
					type= "Turning Point",
					x = tableOrigin.x,
					y = tableOrigin.y,
					speed = speedGroupmxs,
					ETA = 100,
					ETA_locked = false,
					name = "Starting point", 
					task = nil}	
		
			routePoints[2] = {
					action = pAction,
					type= "Turning Point",
					x = tableDestiny.x,
					y = tableDestiny.y,
					speed = speedGroupmxs,
					ETA = 100,
					ETA_locked = false,
					name = "Destination point", 
					task = nil}
			
		--trigger.action.markToAll(2, "Destination point", {x = xDestiny, y = 0, z = yDestiny})
		
		
		local _mission = { 
            id = 'Mission', 
            params = { 
				airborne = false,
                route = { 
                    points = routePoints
                }, 
            } 
        }
		
		local _controller = groundGroup:getController();
		Controller.setOption(_controller, AI.Option.Ground.id.ALARM_STATE, AI.Option.Ground.val.ALARM_STATE.RED)
		_controller:setTask(_mission)
		--trigger.action.outText("ruta asignada", 3)
		return tableDestiny
end;


function requestStopComboy()
	setMessageDelayed("[".. string.upper(nameComboyGroup) .. "]: Eco group. " .. nameComboyGroup .. ". WILCO. We will stay put until further orders. Over", 20, 2)
	setSoundDelayed("DELECOwilcostayputR.ogg", 2)
	setComboyStop(comboyAllyGroup)
end


function setComboyStop(groundGroup)
--	trigger.action.outText("setComboyStop", 30)

	local _controller = groundGroup:getController();	
	_controller:setOnOff(false)
	isComboyMoving = false;
end 


function requestContinueComboy()
	setMessageDelayed("[".. string.upper(nameComboyGroup) .. "]: Eco group. " .. nameComboyGroup .. ". Oscar-Mike and reasuming mission. Over", 20, 2)	
	setSoundDelayed("DELECOOscarMikereasumingmissionR.ogg", 2)
	resetRouteAllyComboy()
end


function resetRouteAllyComboy()	
--	local PosGroup = comboyAllyGroup:getUnit(1):getPoint()		
--	originComboy = {x = PosGroup.x, y = PosGroup.z}		
--	setGroundRoute(comboyAllyGroup, originComboy, destinationComboy, 40, true)		
	
	
	local _controller = comboyAllyGroup:getController();
	Controller.setOption(_controller, AI.Option.Ground.id.ALARM_STATE, AI.Option.Ground.val.ALARM_STATE.RED)
	_controller:setOnOff(true)
		
	isComboyMoving = true;
end;


function getHeading(unit)
		local pos = unit:getPosition()
		if pos then
			local Heading = math.atan2(pos.x.z, pos.x.x)			
			if Heading < 0 then
				Heading = Heading + 2*math.pi
			end
			return Heading
		end
end


function getBearing(pointRef, PointBearing)
	--trigger.action.outText("getBearing", 10) 
	local p = {}
    p.x = PointBearing.x - pointRef.x
    p.z = PointBearing.z - pointRef.z
 
    local r = math.atan2(p.z, p.x)*180/math.pi
	if r < 0 then 
		r = 360 + r
	end
    --trigger.action.outText("bearing: " .. r .. "º", 10) 
	return math.floor(r + 0.5)
end


function setAirRoute(AirGroup, tableOrigin, tableDestiny, speed)
	if AirGroup ~= nil then
		--trigger.action.outText("setAirRoute", 3) 
			
		local routePoints = {}		
							
			routePoints[1] = {
								["alt"] = tableOrigin.z,
                                ["type"] = "Turning Point",
								["action"] = "Turning Point",
								["alt_type"] = "BARO",
                                ["formation_template"] = "",
                                ["ETA"] = 0,
                                ["y"] = tableOrigin.y,
                                ["x"] = tableOrigin.x,
								["speed"] = speed,
                                ["ETA_locked"] = false,                                
                                ["speed_locked"] = true,			
								}	
		
			routePoints[2] = {
								["alt"] = tableDestiny.z,
                                ["type"] = "Turning Point",
								["action"] = "Turning Point",
								["alt_type"] = "BARO",
                                ["formation_template"] = "",
                                ["ETA"] = 0,
                                ["y"] = tableDestiny.y,
                                ["x"] = tableDestiny.x,
								["speed"] = speed,
                                ["ETA_locked"] = false,                                
                                ["speed_locked"] = true,			
								}
							
			
		--trigger.action.markToAll(2, "Destination point", {x = xDestiny, y = 0, z = yDestiny})
		
		
		local _mission = { 
            id = 'Mission', 
            params = { 
				airborne = true,
                route = { 
                    points = routePoints
                }, 
            } 
        }
		
		local _controller = AirGroup:getController();
		Controller.setOption(_controller, AI.Option.Ground.id.ALARM_STATE, AI.Option.Ground.val.ALARM_STATE.RED)		
		_controller:resetTask()
		_controller:setTask(_mission)
		--trigger.action.outText("ruta aerea asignada", 3)
	end	
end;


function setPlayerCAP(playerGroup, Wp1, Wp2)

	if playerGroup ~= nil then
		--trigger.action.outText("setPlayerCAP", 3) 
					
		local routePoints = {}	
							
			routePoints[1] = {
								["alt"] = Wp1.y,
                                ["type"] = "Turning Point",
								["action"] = "Turning Point",
								["alt_type"] = "BARO",
                                ["formation_template"] = "",
                                ["ETA"] = 0,
                                ["y"] = Wp1.z,
                                ["x"] = Wp1.x,
								["speed"] = 250,
                                ["ETA_locked"] = false,                                
                                ["speed_locked"] = true,			
								}	
		
			routePoints[2] = {
								["alt"] = Wp2.y,
                                ["type"] = "Turning Point",
								["action"] = "Turning Point",
								["alt_type"] = "BARO",
                                ["formation_template"] = "",
                                ["ETA"] = 0,
                                ["y"] = Wp2.z,
                                ["x"] = Wp2.x,
								["speed"] = 250,
                                ["ETA_locked"] = false,                                
                                ["speed_locked"] = true,			
								}
				
		local _mission = { 
            id = 'Mission', 
            params = { 
				airborne = true,
                route = { 
                    points = routePoints
                }, 
            } 
        }
		
		local _controller = playerGroup:getController();
		Controller.setOption(_controller, AI.Option.Ground.id.ALARM_STATE, AI.Option.Ground.val.ALARM_STATE.RED)
		_controller:setTask(_mission)
		--trigger.action.outText("ruta CAP player asignada", 3)
	end	
end;


function createComboyAttackers(originAttackers, isOnRoad, pComboyType)
	--trigger.action.outText("createComboyAttackers " .. pComboyType, 10)        	
		
		local heading = math.random(259)
		
		if (isOnRoad) then
			--trigger.action.outText("onroad1", 5)        	
			local offsetx, offsety = land.getClosestPointOnRoads("roads", originAttackers.x, originAttackers.y)
			originAttackers.x = offsetx
			originAttackers.y = offsety
			--trigger.action.outText("onroad2", 5)        	
		end	
		
		
		local _groundtype = ""
		local _groundtype2 = ""
		local _country = nil
		local _numberOfInitialUnits = 4
         

		if pComboyType == 1 then
			 _groundtype = "BTR-80" --BTR-80. comboy hostil de inicio (avion)
			 _groundtype2 = "BTR-80" --BTR-80. comboy hostil de inicio (avion)
			 _country = country.id.IRAN
		elseif pComboyType == 2 then
			_groundtype = "Land_Rover_109_S3" --M818. Comboy neutral hasta identificar
			_groundtype2 = "M818" --M818. Comboy neutral hasta identificar
			_country = country.id.GEORGIA
		elseif pComboyType == 3 then			
			_groundtype = "M1043 HMMWV Armament" --Ural-375 ZU-23 Insurgent. Comboy neutral identificado hostil
			_groundtype2 = "Ural-375 ZU-23 Insurgent" --Ural-375 ZU-23 Insurgent. Comboy neutral identificado hostil
			_country = country.id.IRAN
		elseif pComboyType == 4 then			
			_groundtype = "M818" --M818, comboy hostil de inicio(helicoptero)
			_groundtype2 = "M1043 HMMWV Armament" --M1043 HMMWV Armament, comboy hostil de inicio(helicoptero)
			_country = country.id.IRAQ
		elseif pComboyType == 5 then			
			_groundtype = "Infantry AK Ins" --Infantry AK Ins. Emboscada insurgentes
			_groundtype2 = "Infantry AK Ins" --Infantry AK Ins. Emboscada insurgentes
			_country = country.id.IRAQ		
		elseif pComboyType == 6 then
			_groundtype = "M818" --M818. Comboy neutral hasta identificar (helicoptero)
			_groundtype2 = "Land_Rover_109_S3" --Land_Rover_109_S3. Comboy neutral hasta identificar (helicoptero)
			_country = country.id.GEORGIA
		elseif pComboyType == 7 then			
			_groundtype = "M818" --M818, comboy identificado como hostil(helicoptero)
			_groundtype2 = "M1043 HMMWV Armament" --M1043 HMMWV Armament, comboy identificado como hostil(helicoptero)
			_country = country.id.IRAQ
		elseif pComboyType == 8 then
			_groundtype = "BTR-80" --M818, Comboy enemigo objetivo directo (helicoptero)
			_groundtype2 = "M818" --M818 Comboy enemigo objetivo directo (helicoptero)
			_country = country.id.IRAN
		end
		
		local _attackersdata = nil
		
		 
        if pComboyType == 1 or pComboyType == 2 or pComboyType == 4 or pComboyType == 6 or pComboyType == 8 then    
			       			
			_attackersdata =     {
                                ["modulation"] = 0,
                                ["tasks"] = 
                                {
                                }, -- end of ["tasks"]
                                ["task"] = "",
                                ["uncontrolled"] = false,
                                ["groupId"] = 500 + math.random(1001, 2000),
                                ["hidden"] = false,
                                ["units"] = 
                                {
                                    [1] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = heading,                                        
                                        ["type"] = _groundtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = originAttackers.y,
                                        ["x"] = originAttackers.x,                                        
                                        ["name"] =  "enemyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]
								[2] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = heading,                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = originAttackers.y + 20,
                                        ["x"] = originAttackers.x + 20,
                                        ["name"] =  "enemyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]
								[3] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = heading,                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = originAttackers.y + 40,
                                        ["x"] = originAttackers.x + 40,                                        
                                        ["name"] =  "enemyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]  
								[4] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = heading,                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = originAttackers.y + 60,
                                        ["x"] = originAttackers.x + 60,                                        
                                        ["name"] =  "enemyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]  
                                }, -- end of ["units"]
                                ["y"] = originAttackers.y,
                                ["x"] = originAttackers.x,
                                ["name"] =  "U002" .. math.random(9999,99999),
                                ["communication"] = true,
                                ["start_time"] = 0,
                                ["frequency"] = 124,
                    }
					
					if pComboyType == 8 then --Comboy enemigo objetivo directo (+4 unidades)						       			
						_numberOfInitialUnits = 8
						_attackersdata["units"][5] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = heading,                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = originAttackers.y + 80,
                                        ["x"] = originAttackers.x + 80,                                       
                                        ["name"] =  "enemyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }
						_attackersdata["units"][6] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = heading,                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = originAttackers.y + 100,
                                        ["x"] = originAttackers.x + 100,                                       
                                        ["name"] =  "enemyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }
						_attackersdata["units"][7] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = heading,                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = originAttackers.y + 120,
                                        ["x"] = originAttackers.x + 120,                                       
                                        ["name"] =  "enemyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }
						_attackersdata["units"][8] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = heading,                                        
                                        ["type"] = _groundtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = originAttackers.y + 140,
                                        ["x"] = originAttackers.x + 140,                                       
                                        ["name"] =  "enemyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }
					end
					      			
			local numberPlayers = getNumberOfPlayers()			
			if numberPlayers >= 2 then
				for i = 0, (numberPlayers -1) do
							_attackersdata["units"][(_numberOfInitialUnits + 1) + (i * 3)] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = heading,                                        
                                        ["type"] = _groundtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = originAttackers.y + 160 + (30 * i),
                                        ["x"] = originAttackers.x + 160 + (30 * i),                                       
                                        ["name"] =  "enemyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }                                  
								
							_attackersdata["units"][(_numberOfInitialUnits + 2) + (i * 3)] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = heading,                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = originAttackers.y + 170 + (30 * i),
                                        ["x"] = originAttackers.x + 170 + (30 * i),                                        
                                        ["name"] =  "enemyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }
							_attackersdata["units"][(_numberOfInitialUnits + 3) + (i * 3)] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = heading,                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = originAttackers.y + 180 + (30 * i),
                                        ["x"] = originAttackers.x + 180 + (30 * i),                                        
                                        ["name"] =  "enemyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }
				end
			end
					
		elseif pComboyType == 3 or pComboyType == 7 then -- clonar comboy neutral como hostil
				   	
				_attackersdata =     {
                                ["modulation"] = 0,
                                ["tasks"] = 
                                {
                                }, -- end of ["tasks"]
                                ["task"] = "",
                                ["uncontrolled"] = false,
                                ["groupId"] = 500 + math.random(1001, 2000),
                                ["hidden"] = false,
                                ["units"] = 
                                {
                                    [1] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = getHeading(comboyAttackerGroup:getUnit(1)),                                        
                                        ["type"] = _groundtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = comboyAttackerGroup:getUnit(1):getPoint().z,
                                        ["x"] = comboyAttackerGroup:getUnit(1):getPoint().x,
                                        ["name"] =  "enemyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]
								[2] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = getHeading(comboyAttackerGroup:getUnit(2)),                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = comboyAttackerGroup:getUnit(2):getPoint().z,
                                        ["x"] = comboyAttackerGroup:getUnit(2):getPoint().x,
                                        ["name"] =  "enemyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]
								[3] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = getHeading(comboyAttackerGroup:getUnit(3)),                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = comboyAttackerGroup:getUnit(3):getPoint().z,
                                        ["x"] = comboyAttackerGroup:getUnit(3):getPoint().x,                                        
                                        ["name"] =  "enemyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]  
								[4] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = getHeading(comboyAttackerGroup:getUnit(4)),                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = comboyAttackerGroup:getUnit(4):getPoint().z,
                                        ["x"] = comboyAttackerGroup:getUnit(4):getPoint().x,                                        
                                        ["name"] =  "enemyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]  
                                }, -- end of ["units"]
                                ["y"] = comboyAttackerGroup:getUnit(1):getPoint().z,
                                ["x"] = comboyAttackerGroup:getUnit(1):getPoint().y,
                                ["name"] =  "U002" .. math.random(9999,99999),
                                ["communication"] = true,
                                ["start_time"] = 0,
                                ["frequency"] = 124,
                    }
				comboyAttackerGroup:destroy()	
				
			local numberPlayers = getNumberOfPlayers()
			if numberPlayers >= 2 then
				for i = 0, (numberPlayers -1) do
							_attackersdata["units"][5 + (i * 3)] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = getHeading(comboyAttackerGroup:getUnit(5 + (i * 3))),                                        
                                        ["type"] = _groundtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = comboyAttackerGroup:getUnit(5 + (i * 3)):getPoint().z,
                                        ["x"] = comboyAttackerGroup:getUnit(5 + (i * 3)):getPoint().x,
                                        ["name"] =  "enemyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }                                  
								
							_attackersdata["units"][6 + (i * 3)] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = getHeading(comboyAttackerGroup:getUnit(6 + (i * 3))),                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = comboyAttackerGroup:getUnit(6 + (i * 3)):getPoint().z,
                                        ["x"] = comboyAttackerGroup:getUnit(6 + (i * 3)):getPoint().x,                                        
                                        ["name"] =  "enemyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }
							_attackersdata["units"][7 + (i * 3)] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = getHeading(comboyAttackerGroup:getUnit(7 + (i * 3))),                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = comboyAttackerGroup:getUnit(7 + (i * 3)):getPoint().z,
                                        ["x"] = comboyAttackerGroup:getUnit(7 + (i * 3)):getPoint().x,                                        
                                        ["name"] =  "enemyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }
				end
			end
		elseif pComboyType == 5 then -- emboscada insurgentes			
			_attackersdata =     {
                                ["modulation"] = 0,
                                ["tasks"] = 
                                {
                                }, -- end of ["tasks"]
                                ["task"] = "",
                                ["uncontrolled"] = false,
                                ["groupId"] = 500 + math.random(1001, 2000),
                                ["hidden"] = false,
                                ["units"] = 
                                {
                                    [1] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = heading,                                        
                                        ["type"] = _groundtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = originAttackers.y,
                                        ["x"] = originAttackers.x,                                        
                                        ["name"] =  "enemyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]
								[2] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = heading,                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = originAttackers.y + 3,
                                        ["x"] = originAttackers.x + 3,
                                        ["name"] =  "enemyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]
								[3] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = heading,                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = originAttackers.y + 3,
                                        ["x"] = originAttackers.x + 6,                                        
                                        ["name"] =  "enemyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]  
								[4] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = heading,                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = originAttackers.y + 3,
                                        ["x"] = originAttackers.x + 9,                                        
                                        ["name"] =  "enemyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]
								[5] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = heading,                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = originAttackers.y + 6,
                                        ["x"] = originAttackers.x + 3,                                        
                                        ["name"] =  "enemyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1] 
								[6] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = heading,                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = originAttackers.y + 6,
                                        ["x"] = originAttackers.x + 9,                                        
                                        ["name"] =  "enemyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]
								[7] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = heading,                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = originAttackers.y + 9,
                                        ["x"] = originAttackers.x + 3,                                        
                                        ["name"] =  "enemyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]
								[8] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = heading,                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = originAttackers.y + 9,
                                        ["x"] = originAttackers.x + 6,                                        
                                        ["name"] =  "enemyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1] 
								[9] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = heading,                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = originAttackers.y + 9,
                                        ["x"] = originAttackers.x + 9,                                        
                                        ["name"] =  "enemyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]
								[10] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = heading,                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = originAttackers.y + 9,
                                        ["x"] = originAttackers.x + 12,                                        
                                        ["name"] =  "enemyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1] 
                                }, -- end of ["units"]
                                ["y"] = originAttackers.y,
                                ["x"] = originAttackers.x,
                                ["name"] =  "U002" .. math.random(9999,99999),
                                ["communication"] = true,
                                ["start_time"] = 0,
                                ["frequency"] = 124,
                    }
		end      
                			            
		return coalition.addGroup(_country, Group.Category.GROUND, _attackersdata)     						
end;


function cleanArea(origin)
	--trigger.action.outText("cleanArea ", 10)        
	local foundUnits = {}
	 local volS = {
	   id = world.VolumeType.SPHERE,
	   params = {
		 point = origin,
		 radius = 20
	   }
	 }	        
	 
	 local ifFound = function(foundItem, val)
		--trigger.action.outText("nombre: " .. foundItem:getName(), 10)
		foundItem:destroy()
		return true
	 end
	 
	 world.searchObjects(Object.Category.SCENERY, volS, ifFound)
 end
 
 
function isPOSBuilding(origin)
	local foundUnits = {}
	local volS = {
	   id = world.VolumeType.SPHERE,
	   params = {
		 point = origin,
		 radius = 0.01
	   }
	 }
	 
	 local ifFound = function(foundItem, val)		
		return true
	 end
	 
	foundUnits = world.searchObjects(Object.Category.SCENERY, volS, ifFound)
	
	if foundUnits > 0 then
		return true
	else
		return false
	end
 end


function createHostileCampament(posOrigin, forzarSAM, factorLejos, tipoCampamento)	
	--trigger.action.outText(" createHostileCampament: ", 10)        
	local _typeObj = "" -- Workshop A -- house2arm --Shelter -- Farm B -- Comms tower M -- house1arm -- Chemical tank A  --Pump station
	local _typeSub1 = "" -- Workshop A -- house2arm --Shelter -- Farm B -- Comms tower M -- house1arm -- Chemical tank A  
	local _typeSub2 = "" -- Workshop A -- house2arm --Shelter -- Farm B -- Comms tower M -- house1arm -- Chemical tank A  
	local _typeSub3 = "" -- Workshop A -- house2arm --Shelter -- Farm B -- Comms tower M -- house1arm -- Chemical tank A  
	local _typeSub4 = "" -- Workshop A -- house2arm --Shelter -- Farm B -- Comms tower M -- house1arm -- Chemical tank A  
	local _typeSub5 = "" -- Workshop A -- house2arm --Shelter -- Farm B -- Comms tower M -- house1arm -- Chemical tank A  
    
	local _country = country.id.IRAN 
	local _shapeObj = ""
	
	local haySAMs = false
	
	if forzarSAM ~= -1 then
		if math.random() >= 0.5 or forzarSAM == 1 then 
			haySAMs = true	
		end 
	else
		haySAMs = false
	end
	
	--trigger.action.outText(" createHostileCampament1 ", 10)
	
	local typeObjetive = math.random(1,6) --rndOBJ
	if typeObjetive == 1 then
		_typeObj = "Workshop A"
		varCampTargetName = "workshop building"
	elseif typeObjetive == 2 then
		_typeObj = "Shelter"
		varCampTargetName = "shelter building"
	elseif typeObjetive == 3 then
		_typeObj = ".Command Center"
		_shapeObj = "ComCenter"
		varCampTargetName = "command center building"
	elseif typeObjetive == 4 then
		_typeObj = "Comms tower M"
		varCampTargetName = "Comms tower array"
	elseif typeObjetive == 5 then
		_typeObj = "Pump station"
		varCampTargetName = "Oil pump station"		
	elseif typeObjetive == 6 then
		_typeObj = "Tech combine"
		varCampTargetName = "Tech combine building"
	end
		
	local typeSubsidiary1 = math.random(1,5) --rndOBJ
	if typeSubsidiary1 == 1 then
		_typeSub1 = "Chemical tank A"
	elseif typeSubsidiary1 == 2 then
		_typeSub1 = "house1arm"
	elseif typeSubsidiary1 == 3 then
		_typeSub1 = "Boiler-house A"
	elseif typeSubsidiary1 == 4 then
		_typeSub1 = "Military staff"
	elseif typeSubsidiary1 == 5 then
		_typeSub1 = "Subsidiary structure 2"			
	end
	
	local typeSubsidiary2 = math.random(1,5) --rndOBJ
	if typeSubsidiary2 == 1 then
		_typeSub2 = "Chemical tank A"
	elseif typeSubsidiary2 == 2 then
		_typeSub2 = "house1arm"
	elseif typeSubsidiary2 == 3 then
		_typeSub2 = "Boiler-house A"
	elseif typeSubsidiary2 == 4 then
		_typeSub2 = "Military staff"
	elseif typeSubsidiary2 == 5 then
		_typeSub2 = "Subsidiary structure 2"
	end
	
	local typeSubsidiary3 = math.random(1,5) --rndOBJ
	if typeSubsidiary3 == 1 then
		_typeSub3 = "Chemical tank A"
	elseif typeSubsidiary3 == 2 then
		_typeSub3 = "house1arm"
	elseif typeSubsidiary3 == 3 then
		_typeSub3 = "Boiler-house A"
	elseif typeSubsidiary3 == 4 then
		_typeSub3 = "Military staff"
	elseif typeSubsidiary3 == 5 then
		_typeSub3 = "Subsidiary structure 2"
	end
	
	local typeSubsidiary4 = math.random(1,5) --rndOBJ
	if typeSubsidiary4 == 1 then
		_typeSub4 = "Chemical tank A"
	elseif typeSubsidiary4 == 2 then
		_typeSub4 = "house1arm"
	elseif typeSubsidiary4 == 3 then
		_typeSub4 = "Boiler-house A"
	elseif typeSubsidiary4 == 4 then
		_typeSub4 = "Military staff"
	elseif typeSubsidiary4 == 5 then
		_typeSub4 = "Subsidiary structure 2"
	end
	
	local typeSubsidiary5 = math.random(1,4) --rndOBJ
	if typeSubsidiary5 == 1 then
		_typeSub5 = "Chemical tank A"
	elseif typeSubsidiary5 == 2 then
		_typeSub5 = "FARP Tent"
	elseif typeSubsidiary5 == 3 then
		_typeSub5 = "FARP Fuel Depot"
	elseif typeSubsidiary5 == 4 then
		_typeSub5 = "Container red 3"
	end
	
	local typeSubsidiary6 = math.random(1,3) --rndOBJ
	if typeSubsidiary6 == 1 then
		_typeSub6 = "Garage A"
	elseif typeSubsidiary6 == 2 then
		_typeSub6 = "Garage B"
	elseif typeSubsidiary6 == 3 then
		_typeSub6 = "Barracks 2"	
	end	
	
	local typeSubsidiary7_8 = math.random(1,2) --rndOBJ
	if typeSubsidiary7_8 == 1 then
		_typeSub7 = "Hangar A"
		_typeSub8 = "Hangar A"
	elseif typeSubsidiary7_8 == 2 then
		_typeSub7 = "Tech hangar A"	
		_typeSub8 = "Tech hangar A"
	end	
	
	--trigger.action.outText(" createHostileCampament2 ", 10)

	local heading = 0
	
	local signRnd1 = 1
	local signRnd2 = 1
	

	local factorX = 1
	local factorY = 1
	local posX = 1 
	local posY = 1	
	
	--para que cree el campamento en zona mas o menos plana (y fuera del agua)
	local minDistance = 0
	repeat		
		if factorLejos == 1 then
			factorX = math.random(-50000,50000)	
			factorY = math.random(-50000,50000)
			minDistance = 35000
		elseif factorLejos == 2 then
			factorX = math.random(-5000,5000)	
			factorY = math.random(-5000,5000)
			minDistance = 2500
		else
			factorX = math.random(-150000,150000)	
			factorY = math.random(-150000,150000)
			minDistance = 100000
		end
			
		posX = posOrigin.x - factorX  
		posY = posOrigin.y - factorY 
		
		local difHeight1 = land.getHeight({x = posX, y = posY}) - land.getHeight({x = posX + 300, y = posY + 300})
		local difHeight2 = land.getHeight({x = posX, y = posY}) - land.getHeight({x = posX - 300, y = posY - 300})
		
		--trigger.action.outText(" dif1: " .. math.abs(difHeight1) .. "; dif2: " .. math.abs(difHeight2), 10)        
		
	until math.abs(difHeight1) < 30 and math.abs(difHeight2) < 30 
			and land.getSurfaceType({x = posX + 300, y = posY + 300}) ~= land.SurfaceType.WATER and land.getSurfaceType({x = posX + 300, y = posY +300}) ~= land.SurfaceType.SHALLOW_WATER
			and land.getSurfaceType({x = posX - 300, y = posY - 300}) ~= land.SurfaceType.WATER and land.getSurfaceType({x = posX - 300, y = posY -300}) ~= land.SurfaceType.SHALLOW_WATER
			and getDistancePointPoint({x = posX, y = posY},{x = posOrigin.x, y = posOrigin.y} ) > minDistance
			
	--trigger.action.outText(" createHostileCampament3 ", 10)
		
	--objetivos principales
    local staticObj1 = {                
        ["type"] = _typeObj,
        ["unitId"] = math.random(9999,99999),        
        ["name"] = "campObjetive1",
        ["category"] = "Fortifications",
        ["y"] = posY,
        ["x"] = posX,
        ["dead"] = false,
		["shape_name"] = _shapeObj,
        ["heading"] = heading,    
    }   

	local staticObj2 = {                
        ["type"] = _typeObj,
        ["unitId"] = math.random(9999,99999),        
        ["name"] = "campObjetive2",
        ["category"] = "Fortifications",
        ["y"] = posY + 10,
        ["x"] = posX,
        ["dead"] = false,
		["shape_name"] = _shapeObj,
        ["heading"] = heading,    
    } 
	
	local staticObj3 = {                
        ["type"] = _typeObj,
        ["unitId"] = math.random(9999,99999),        
        ["name"] = "campObjetive3",
        ["category"] = "Fortifications",
        ["y"] = posY + 20,
        ["x"] = posX,
        ["dead"] = false,
		["shape_name"] = _shapeObj,
        ["heading"] = heading,    
    }   
	
	--extructuras subsidiarias
	local staticSub1 = {                
        ["type"] = _typeSub1,
        ["unitId"] = math.random(9999,99999),        
        ["name"] = "campSub1",
        ["category"] = "Fortifications",
        ["y"] = posY + 100,
        ["x"] = posX,
        ["dead"] = false,
        ["heading"] = heading,    
    } 
	
	local staticSub2 = {                
        ["type"] = _typeSub2,
        ["unitId"] = math.random(9999,99999),        
        ["name"] = "campSub2",
        ["category"] = "Fortifications",
        ["y"] = posY - 100,
        ["x"] = posX,
        ["dead"] = false,
        ["heading"] = heading,    
    }    
	
	local staticSub3 = {                
        ["type"] = _typeSub3,
        ["unitId"] = math.random(9999,99999),        
        ["name"] = "campSub3",
        ["category"] = "Fortifications",
        ["y"] = posY + 100,
        ["x"] = posX + 100,
        ["dead"] = false,
        ["heading"] = heading,    
    }    
	
	local staticSub4 = {                
        ["type"] = _typeSub4,
        ["unitId"] = math.random(9999,99999),        
        ["name"] = "campSub4",
        ["category"] = "Fortifications",
        ["y"] = posY + 100,
        ["x"] = posX - 100,
        ["dead"] = false,
        ["heading"] = heading,    
    } 


	local staticSub5_1 = {                
        ["type"] = _typeSub5,
        ["unitId"] = math.random(9999,99999),        
        ["name"] = "campSub5_1",
        ["category"] = "Fortifications",
        ["y"] = posY - 100,
        ["x"] = posX - 100,
        ["dead"] = false,
        ["heading"] = heading,    
    }
	local staticSub5_2 = {                
        ["type"] = _typeSub5,
        ["unitId"] = math.random(9999,99999),        
        ["name"] = "campSub5_2",
        ["category"] = "Fortifications",
        ["y"] = posY - 100,
        ["x"] = posX - 120,
        ["dead"] = false,
        ["heading"] = heading,    
    }   
	local staticSub5_3 = {                
        ["type"] = _typeSub5,
        ["unitId"] = math.random(9999,99999),        
        ["name"] = "campSub5_3",
        ["category"] = "Fortifications",
        ["y"] = posY - 100,
        ["x"] = posX - 140,
        ["dead"] = false,
        ["heading"] = heading,    
    }   
	local staticSub5_4 = {                
        ["type"] = _typeSub5,
        ["unitId"] = math.random(9999,99999),        
        ["name"] = "campSub5_4",
        ["category"] = "Fortifications",
        ["y"] = posY - 100,
        ["x"] = posX - 160,
        ["dead"] = false,
        ["heading"] = heading,    
    }  
	local staticSub6 = {                
        ["type"] = _typeSub6,
        ["unitId"] = math.random(9999,99999),        
        ["name"] = "campSub6",
        ["category"] = "Fortifications",
        ["y"] = posY,
        ["x"] = posX - 100,
        ["dead"] = false,
        ["heading"] = heading,    
    } 
	local staticSub7 = {                
        ["type"] = _typeSub7,
        ["unitId"] = math.random(9999,99999),        
        ["name"] = "campSub7",
        ["category"] = "Fortifications",
        ["y"] = posY,
        ["x"] = posX + 100,
        ["dead"] = false,
        ["heading"] = heading,    
    }
	local staticSub8 = {                
        ["type"] = _typeSub8,
        ["unitId"] = math.random(9999,99999),        
        ["name"] = "campSub8",
        ["category"] = "Fortifications",
        ["y"] = posY,
        ["x"] = posX + 130,
        ["dead"] = false,
        ["heading"] = heading,    
    } 	



	
	
	--torretas del campamento
	local turret1 = {                
        ["type"] = "house2arm",
        ["unitId"] = math.random(9999,99999),        
        ["name"] = "turret1",
        ["category"] = "Fortifications",
        ["y"] = posY + 180,
        ["x"] = posX - 180,
        ["dead"] = false,
        ["heading"] = heading,    
    }
	
	local turret2 = {                
        ["type"] = "house2arm",
        ["unitId"] = math.random(9999,99999),        
        ["name"] = "turret2",
        ["category"] = "Fortifications",
        ["y"] = posY - 180,
        ["x"] = posX + 180,
        ["dead"] = false,
        ["heading"] = heading,    
    }    
     
	local turret3 = {                
        ["type"] = "house2arm",
        ["unitId"] = math.random(9999,99999),        
        ["name"] = "turret3",
        ["category"] = "Fortifications",
        ["y"] = posY - 180,
        ["x"] = posX - 180,
        ["dead"] = false,
        ["heading"] = heading,    
    }
	
	local turret4 = {                
        ["type"] = "house2arm",
        ["unitId"] = math.random(9999,99999),        
        ["name"] = "turret4",
        ["category"] = "Fortifications",
        ["y"] = posY + 180,
        ["x"] = posX + 180,
        ["dead"] = false,
        ["heading"] = heading,    
    }
	 	 
	--trigger.action.outText(" createHostileCampament4 ", 10)		 
		 
    CampStaticTarget  = coalition.addStaticObject(_country, staticObj1) 
	if typeObjetive == 5 then
		local objStatic1 = coalition.addStaticObject(_country, staticObj2) 
		local objStatic2 = coalition.addStaticObject(_country, staticObj3) 
		cleanArea(objStatic1:getPoint())
		cleanArea(objStatic2:getPoint())
	end
	local objStaticSub1 = coalition.addStaticObject(_country, staticSub1)        
	local objStaticSub2 = coalition.addStaticObject(_country, staticSub2) 
	local objStaticSub3 = coalition.addStaticObject(_country, staticSub3) 
	local objStaticSub4 = coalition.addStaticObject(_country, staticSub4) 
	local objStaticSub5 = coalition.addStaticObject(_country, staticSub5_1) 
	local objStaticSub6 = coalition.addStaticObject(_country, staticSub5_2) 
	local objStaticSub7 = coalition.addStaticObject(_country, staticSub5_3) 
	local objStaticSub8 = coalition.addStaticObject(_country, staticSub5_4) 
	local objStaticSub9 = coalition.addStaticObject(_country, turret1)        
	local objStaticSub10 = coalition.addStaticObject(_country, turret2)        
	local objStaticSub11 = coalition.addStaticObject(_country, turret3)
	local objStaticSub12 = coalition.addStaticObject(_country, turret4)
	local objStaticSub13 = coalition.addStaticObject(_country, staticSub6)
	local objStaticSub14 = coalition.addStaticObject(_country, staticSub7)
	local objStaticSub15 = coalition.addStaticObject(_country, staticSub8)
	
	
	--trigger.action.outText(" createHostileCampament5 ", 10)		 
		      
	if CampStaticTarget ~= nil then cleanArea(CampStaticTarget:getPoint()) end
	if objStaticSub1 ~= nil then	cleanArea(objStaticSub1:getPoint()) end
	if objStaticSub2 ~= nil then	cleanArea(objStaticSub2:getPoint()) end
	if objStaticSub3 ~= nil then	cleanArea(objStaticSub3:getPoint()) end
	if objStaticSub4 ~= nil then	cleanArea(objStaticSub4:getPoint()) end
	if objStaticSub5 ~= nil then	cleanArea(objStaticSub5:getPoint()) end
	if objStaticSub6 ~= nil then	cleanArea(objStaticSub6:getPoint()) end
	if objStaticSub7 ~= nil then	cleanArea(objStaticSub7:getPoint()) end
	if objStaticSub8 ~= nil then	cleanArea(objStaticSub8:getPoint()) end
	if objStaticSub9 ~= nil then	cleanArea(objStaticSub9:getPoint()) end
	if objStaticSub10 ~= nil then	cleanArea(objStaticSub10:getPoint()) end
	if objStaticSub11 ~= nil then	cleanArea(objStaticSub11:getPoint()) end
	if objStaticSub12 ~= nil then	cleanArea(objStaticSub12:getPoint()) end
	if objStaticSub13 ~= nil then	cleanArea(objStaticSub13:getPoint()) end
	if objStaticSub14 ~= nil then	cleanArea(objStaticSub14:getPoint()) end
	if objStaticSub15 ~= nil then	cleanArea(objStaticSub15:getPoint()) end
	
	--trigger.action.outText(" createHostileCampament6 ", 10)		 
	
	
	
	--defensas AAA
	local _defendersdata = nil	
	
	--trigger.action.outText(" tipoCampamento " .. tipoCampamento, 10)
	
	if tipoCampamento == 1 then
		local _AAAtype = "ZU-23 Closed Insurgent" --Ural-375 ZU-23 Insurgent. -- Igla manpad INS -- SA-18 Igla comm --Kub 1S91 str --Kub 2P25 ln
		local _AAAtype2 = "Igla manpad INS"
		local _AAAtype3 = "SA-18 Igla comm"
		
			
		local unitsCamp1 = {}		
		for i = 1, 8 do
			
			local rndY = math.random(100,300)
			local rndX = math.random(100,300)
			
			local localType = _AAAtype
			if i == 1 then
				localType = _AAAtype
				rndY = -1 * math.random(100,300)
				rndX = -1 * math.random(100,300)
				repeat 				
					rndY = rndY - 1
					rndX = rndX - 1
				until isPOSBuilding({x = posX + rndX, y = land.getHeight({x = posX + rndX, y = posY + rndY}), z = posY + rndY}) == false
			elseif i == 2 then	
				localType = _AAAtype
				rndY = math.random(100,300)
				rndX = -1 * math.random(100,300)
				repeat 				
					rndY = rndY + 1
					rndX = rndX - 1
				until isPOSBuilding({x = posX + rndX, y = land.getHeight({x = posX + rndX, y = posY + rndY}), z = posY + rndY}) == false
			elseif i == 3 then	
				localType = _AAAtype
				rndY = -1 * math.random(100,300)
				rndX = math.random(100,300)
				repeat 				
					rndY = rndY - 1
					rndX = rndX + 1
				until isPOSBuilding({x = posX + rndX, y = land.getHeight({x = posX + rndX, y = posY + rndY}), z = posY + rndY}) == false
			elseif i == 4 then	
				localType = _AAAtype
				rndY = math.random(100,300)
				rndX = math.random(100,300)
				repeat 				
					rndY = rndY + 1
					rndX = rndX + 1
				until isPOSBuilding({x = posX + rndX, y = land.getHeight({x = posX + rndX, y = posY + rndY}), z = posY + rndY}) == false
			elseif i == 5 then	
				localType = _AAAtype2
				rndY = math.random(40,50)
				rndX = math.random(40,50)
				repeat 				
					rndY = rndY + 1
					rndX = rndX + 1
				until isPOSBuilding({x = posX + rndX, y = land.getHeight({x = posX + rndX, y = posY + rndY}), z = posY + rndY}) == false
			elseif i == 6 then	
				localType = _AAAtype3
				rndY = math.random(40,50)
				rndX = math.random(40,50)
				repeat 				
					rndY = rndY + 1
					rndX = rndX - 1
				until isPOSBuilding({x = posX + rndX, y = land.getHeight({x = posX + rndX, y = posY + rndY}), z = posY + rndY}) == false
			elseif i == 7 then	
				localType = _AAAtype2
				rndY = -1 * math.random(40,50)
				rndX = -1 * math.random(40,50)
				repeat 				
					rndY = rndY - 1
					rndX = rndX - 1
				until isPOSBuilding({x = posX + rndX, y = land.getHeight({x = posX + rndX, y = posY + rndY}), z = posY + rndY}) == false
			elseif i == 8 then	
				localType = _AAAtype3
				rndY = -1 * math.random(40,50)
				rndX = -1 * math.random(40,50)
				repeat 				
					rndY = rndY - 1
					rndX = rndX + 1
				until isPOSBuilding({x = posX + rndX, y = land.getHeight({x = posX + rndX, y = posY + rndY}), z = posY + rndY}) == false
			end		
		
						
			cleanArea({x = posX + rndX, y = land.getHeight({x = posX + rndX, y = posY + rndY}), z = posY + rndY})			
			unitsCamp1[i] = {
                                      ["alt"] = 0,
                                      ["heading"] = heading,                                        
                                      ["type"] = localType,
                                      ["psi"] = 0,                                        
                                      ["y"] = posY + rndY,
                                      ["x"] = posX + rndX,                                      
                                      ["name"] =  "enemyUnit" .. math.random(9999,99999),                                        
                                      ["speed"] = 0,
                                      ["unitId"] =  math.random(9999,99999),                                        
                                      ["skill"] = "High",
                                  } -- end of [i]
		end	
		--trigger.action.outText("terminadoClean2 ", 10, false)
		
		_defendersdata =     {
                              ["modulation"] = 0,
                              ["tasks"] = 
                              {
                              }, -- end of ["tasks"]
                              ["task"] = "",
                              ["uncontrolled"] = false,
                              ["groupId"] = 500 + math.random(1001, 2000),
                              ["hidden"] = false,
                              ["units"] = unitsCamp1,                              
                              ["y"] = posY,
                              ["x"] = posX,
                              ["name"] =  "U002" .. math.random(9999,99999),
                              ["communication"] = true,
                              ["start_time"] = 0,
                              ["frequency"] = 124,
                  }
	
	elseif tipoCampamento == 2 then -- tipo defensas 2 (mission heli spotter)
		local _AAAtype = "ZU-23 Closed Insurgent" --Ural-375 ZU-23 Insurgent. -- Igla manpad INS -- SA-18 Igla comm --Kub 1S91 str --Kub 2P25 ln
		local _AAAtype2 = "T-55"	


		local unitsCamp2 = {}		
		for i = 1, 8 do
			local localType = _AAAtype
			
			local rndY = math.random(100,300)
			local rndX = math.random(100,300)
			
			
			if i == 1 then
				localType = _AAAtype
				rndY = -1 * math.random(100,300)
				rndX = -1 * math.random(100,300)
				repeat 				
					rndY = rndY - 1
					rndX = rndX - 1
				until isPOSBuilding({x = posX + rndX, y = land.getHeight({x = posX + rndX, y = posY + rndY}), z = posY + rndY}) == false
			elseif i == 2 then	
				localType = _AAAtype
				rndY = math.random(100,300)
				rndX = -1 * math.random(100,300)
				repeat 				
					rndY = rndY + 1
					rndX = rndX - 1
				until isPOSBuilding({x = posX + rndX, y = land.getHeight({x = posX + rndX, y = posY + rndY}), z = posY + rndY}) == false
			elseif i == 3 then	
				localType = _AAAtype
				rndY = -1 * math.random(100,300)
				rndX = math.random(100,300)
				repeat 				
					rndY = rndY - 1
					rndX = rndX + 1
				until isPOSBuilding({x = posX + rndX, y = land.getHeight({x = posX + rndX, y = posY + rndY}), z = posY + rndY}) == false
			elseif i == 4 then	
				localType = _AAAtype
				rndY = math.random(100,300)
				rndX = math.random(100,300)
				repeat 				
					rndY = rndY + 1
					rndX = rndX + 1
				until isPOSBuilding({x = posX + rndX, y = land.getHeight({x = posX + rndX, y = posY + rndY}), z = posY + rndY}) == false
			elseif i == 5 then	
				localType = _AAAtype2
				rndY = math.random(300,350)
				rndX = math.random(300,350)
				repeat 				
					rndY = rndY + 1
					rndX = rndX + 1
				until isPOSBuilding({x = posX + rndX, y = land.getHeight({x = posX + rndX, y = posY + rndY}), z = posY + rndY}) == false
			elseif i == 6 then	
				localType = _AAAtype2
				rndY = math.random(300,350)
				rndX = -1 * math.random(300,350)
				repeat 				
					rndY = rndY + 1
					rndX = rndX - 1
				until isPOSBuilding({x = posX + rndX, y = land.getHeight({x = posX + rndX, y = posY + rndY}), z = posY + rndY}) == false
			elseif i == 7 then	
				localType = _AAAtype2
				rndY = -1 * math.random(300,350)
				rndX = math.random(300,350)
				repeat 				
					rndY = rndY - 1
					rndX = rndX + 1
				until isPOSBuilding({x = posX + rndX, y = land.getHeight({x = posX + rndX, y = posY + rndY}), z = posY + rndY}) == false
			elseif i == 8 then	
				localType = _AAAtype2
				rndY = -1 * math.random(300,350)
				rndX = -1 * math.random(300,350)
				repeat 				
					rndY = rndY - 1
					rndX = rndX - 1
				until isPOSBuilding({x = posX + rndX, y = land.getHeight({x = posX + rndX, y = posY + rndY}), z = posY + rndY}) == false
			end		
							
			cleanArea({x = posX + rndX, y = land.getHeight({x = posX + rndX, y = posY + rndY}), z = posY + rndY})
			
			unitsCamp2[i] = {
                                      ["alt"] = 0,
                                      ["heading"] = heading,                                        
                                      ["type"] = localType,
                                      ["psi"] = 0,                                        
                                      ["y"] = posY + rndY,
                                      ["x"] = posX + rndX,                                      
                                      ["name"] =  "enemyUnit" .. math.random(9999,99999),                                        
                                      ["speed"] = 0,
                                      ["unitId"] =  math.random(9999,99999),                                        
                                      ["skill"] = "High",
                                  } -- end of [i]
		end
		--trigger.action.outText("terminadoClean2 ", 10, false)
		
		_defendersdata =     {
                              ["modulation"] = 0,
                              ["tasks"] = 
                              {
                              }, -- end of ["tasks"]
                              ["task"] = "",
                              ["uncontrolled"] = false,
                              ["groupId"] = 500 + math.random(1001, 2000),
                              ["hidden"] = false,
                              ["units"] = unitsCamp2,
                              ["y"] = posY,
                              ["x"] = posX,
                              ["name"] =  "U002" .. math.random(9999,99999),
                              ["communication"] = true,
                              ["start_time"] = 0,
                              ["frequency"] = 124,
                  }
	end
		
		
	CampDefencesTarget = coalition.addGroup(_country, Group.Category.GROUND, _defendersdata)
		
	--trigger.action.outText(" createHostileCampament7 ", 10)			
		
	if haySAMs then
	--defensas SAM
	--trigger.action.outText("haySAMs ", 10, false)
		local _SAMsdata = nil
		local posXSAM = posX + math.random(-2000, 2000)
		local posYSAM = posY + math.random(-2000, 2000)
		local num = 3
		if getNumberOfPlayers() >= 2 then
			num = 6     
		end

		local SAMs = {}		
		for i = 1, num do
			
			local rndY = math.random(100,300)
			local rndX = math.random(100,300)
			
			local localType = "Kub 2P25 ln"
			if i == 1 then
				localType = "Kub 1S91 str"
				rndY = -1 * math.random(50,70)
				rndX = -1 * math.random(50,70)
				repeat 				
					rndY = rndY - 1
					rndX = rndX - 1
				until isPOSBuilding({x = posXSAM + rndX, y = land.getHeight({x = posXSAM + rndX, y = posYSAM + rndY}), z = posYSAM + rndY}) == false
			elseif i == 2 then
				localType = "Kub 2P25 ln"
				rndY = math.random(500,800)
				rndX = -1 * math.random(500,800)
				repeat 				
					rndY = rndY + 1
					rndX = rndX - 1
				until isPOSBuilding({x = posXSAM + rndX, y = land.getHeight({x = posXSAM + rndX, y = posYSAM + rndY}), z = posYSAM + rndY}) == false
			elseif i == 3 then
				localType = "Kub 2P25 ln"
				rndY = -1 * math.random(500,800)
				rndX = math.random(500,800)
				repeat 				
					rndY = rndY - 1
					rndX = rndX + 1
				until isPOSBuilding({x = posXSAM + rndX, y = land.getHeight({x = posXSAM + rndX, y = posYSAM + rndY}), z = posYSAM + rndY}) == false
			elseif i == 4 then
				localType = "Kub 1S91 str"
				rndY = math.random(500,800)
				rndX = math.random(500,800)
				repeat 				
					rndY = rndY + 1
					rndX = rndX + 1
				until isPOSBuilding({x = posXSAM + rndX, y = land.getHeight({x = posXSAM + rndX, y = posYSAM + rndY}), z = posYSAM + rndY}) == false
			elseif i == 5 then
				localType = "Kub 2P25 ln"
				rndY = -1 * math.random(500,800)
				rndX = math.random(500,800)
				repeat 				
					rndY = rndY - 1
					rndX = rndX + 1
				until isPOSBuilding({x = posXSAM + rndX, y = land.getHeight({x = posXSAM + rndX, y = posYSAM + rndY}), z = posYSAM + rndY}) == false
			elseif i == 6 then
				localType = "Kub 2P25 ln"
				rndY = math.random(500,800)
				rndX = -1 * math.random(500,800)
				repeat 				
					rndY = rndY + 1
					rndX = rndX - 1
				until isPOSBuilding({x = posXSAM + rndX, y = land.getHeight({x = posXSAM + rndX, y = posYSAM + rndY}), z = posYSAM + rndY}) == false
			end
				
			cleanArea({x = posXSAM + rndX, y = land.getHeight({x = posXSAM + rndX, y = posYSAM + rndY}), z = posYSAM + rndY})			
			
			SAMs[i] = {
										["alt"] = 0,
										["heading"] = heading,                                        
										["type"] = localType,
										["psi"] = 0,                                        
										["y"] = posYSAM + rndY,
										["x"] = posXSAM + rndX,                                      
										["name"] =  "enemyUnit" .. math.random(9999,99999),                                        
										["speed"] = 0,
										["unitId"] =  math.random(9999,99999),                                        
										["skill"] = "High",
									} -- end of [i]
		end	
		--trigger.action.outText("terminadoClean3 ", 10, false)
			
		_SAMsdata =     {
                            ["modulation"] = 0,
                            ["tasks"] =
                            {
                            }, -- end of ["tasks"]
                            ["task"] = "",
                            ["uncontrolled"] = false,
                            ["groupId"] = 500 + math.random(1001, 2000),
                            ["hidden"] = false,
                            ["units"] = SAMs,                             								                            
                            ["y"] = posYSAM,
                            ["x"] = posXSAM,
                            ["name"] =  "U002" .. math.random(9999,99999),
                            ["communication"] = true,
                            ["start_time"] = 0,
                            ["frequency"] = 124,
						}	
			--trigger.action.outText(" haySAM2 ", 10)        				  
								  
		CampSAMTarget = coalition.addGroup(_country, Group.Category.GROUND, _SAMsdata)
	end
		
	--trigger.action.outText(" createHostileCampament8 ", 10)			
	
	isEnemyCampCreated = true
		
end


function createSAMRouteCampament()
	if math.random(1,6) >= 5 then
	
		local posCamp = {x = CampStaticTarget:getPoint().x, y = CampStaticTarget:getPoint().z}
		
		local posX
		local posY
		
		repeat			
			posX = posCamp.x - ((posCamp.x - VarPosOriginal.x)/3.7) + math.random(-20000, 20000)
			posY = posCamp.y - ((posCamp.y - VarPosOriginal.z)/3.7) + math.random(-20000, 20000)		
		until land.getSurfaceType({x = posX, y = posY }) ~= land.SurfaceType.WATER 
				and land.getSurfaceType({x = posX, y = posY}) ~= land.SurfaceType.SHALLOW_WATER			
		
		createSAMinPoint(posX, posY)
				
		setMessageDelayed("[OVERLORD]: All units. Overlord. We are picking new SAM signals in route for Point Tango. Proceed with caution and avoid threat areas or call for a SEAD strike before attacking Point Tango. Over", 10, 15)					
		setMessageDelayed("TIP:(You can request SEAD mission through F10 radio menu options. ETA 2min)", 10, 15)	
		setSoundDelayed("OVERLORDSamDetectedTango.ogg", 15)
		
		if menuReqSEAD ~= nil then
			missionCommands.removeItem(menuReqSEAD)
		end		
		menuReqSEAD = missionCommands.addCommand('Request SEAD mission', menuPrinc1, requestSEAD, CampSAMRoute)
		
				
	end
end


function createSAMinPoint(posXSAM, posYSAM)
		--trigger.action.outText("createSAMinPoint ", 10, false)
		
		local _country = country.id.IRAN 	
		--trigger.action.markToAll(1, "SAM DEfenses", {x = posX, y = 0, z = posY})
	
		local _SAMsdata = nil		
		local num = 4
		if getNumberOfPlayers() >= 2 then
			num = 6     
		end

		--trigger.action.outText("createSAMinRoute1 ", 10, false)

		local SAMs = {}		
		for i = 1, num do
			
			local rndY = math.random(100,300)
			local rndX = math.random(100,300)
			
			
			local localType = "Kub 2P25 ln" 
			if i == 1 then
				localType = "SA-11 Buk CC 9S470M1" -- Kub 1S91 str   SA-11 Buk CC 9S470M1
				rndY = -1 * math.random(50,70)
				rndX = -1 * math.random(50,70)
				repeat 				
					rndY = rndY - 1
					rndX = rndX - 1
				until isPOSBuilding({x = posXSAM + rndX, y = land.getHeight({x = posXSAM + rndX, y = posYSAM + rndY}), z = posYSAM + rndY}) == false
			elseif i == 2 then
				localType = "SA-11 Buk SR 9S18M1" --Kub 2P25 ln    SA-11 Buk SR 9S18M1
				rndY = math.random(500,800)
				rndX = -1 * math.random(500,800)
				repeat 				
					rndY = rndY + 1
					rndX = rndX - 1
				until isPOSBuilding({x = posXSAM + rndX, y = land.getHeight({x = posXSAM + rndX, y = posYSAM + rndY}), z = posYSAM + rndY}) == false
			elseif i == 3 then
				localType = "SA-11 Buk LN 9A310M1" --Kub 2P25 ln
				rndY = -1 * math.random(500,800)
				rndX = math.random(500,800)
				repeat 				
					rndY = rndY - 1
					rndX = rndX + 1
				until isPOSBuilding({x = posXSAM + rndX, y = land.getHeight({x = posXSAM + rndX, y = posYSAM + rndY}), z = posYSAM + rndY}) == false
			elseif i == 4 then
				localType = "SA-11 Buk LN 9A310M1"
				rndY = math.random(500,800)
				rndX = math.random(500,800)
				repeat 				
					rndY = rndY + 1
					rndX = rndX + 1
				until isPOSBuilding({x = posXSAM + rndX, y = land.getHeight({x = posXSAM + rndX, y = posYSAM + rndY}), z = posYSAM + rndY}) == false
			elseif i == 5 then
				localType = "SA-11 Buk LN 9A310M1"
				rndY = -1 * math.random(500,800)
				rndX = math.random(500,800)
				repeat 				
					rndY = rndY - 1
					rndX = rndX + 1
				until isPOSBuilding({x = posXSAM + rndX, y = land.getHeight({x = posXSAM + rndX, y = posYSAM + rndY}), z = posYSAM + rndY}) == false
			elseif i == 6 then
				localType = "SA-11 Buk SR 9S18M1"
				rndY = math.random(500,800)
				rndX = -1 * math.random(500,800)
				repeat 				
					rndY = rndY + 1
					rndX = rndX - 1
				until isPOSBuilding({x = posXSAM + rndX, y = land.getHeight({x = posXSAM + rndX, y = posYSAM + rndY}), z = posYSAM + rndY}) == false
			end
			
			--trigger.action.outText("createSAMinRoute2 ", 10, false)
				
			cleanArea({x = posXSAM + rndX, y = land.getHeight({x = posXSAM + rndX, y = posYSAM + rndY}), z = posYSAM + rndY})			
			
			
			
			SAMs[i] = {
										["alt"] = 0,
										["heading"] = 0,                                        
										["type"] = localType,
										["psi"] = 0,                                        
										["y"] = posYSAM + rndY,
										["x"] = posXSAM + rndX,                                      
										["name"] =  "enemyUnit" .. math.random(9999,99999),                                        
										["speed"] = 0,
										["unitId"] =  math.random(9999,99999),                                        
										["skill"] = "High",
									} -- end of [i]
			--trigger.action.outText("createSAMinRoute3 ", 10, false)
		end	
		
		--trigger.action.outText("createSAMinRoute4 ", 10, false)
		
		_SAMsdata =     {
                            ["modulation"] = 0,
                            ["tasks"] =
                            {
                            }, -- end of ["tasks"]
                            ["task"] = "",
                            ["uncontrolled"] = false,
                            ["groupId"] = 500 + math.random(1001, 2000),
                            ["hidden"] = false,
                            ["units"] = SAMs,                             								                            
                            ["y"] = posYSAM,
                            ["x"] = posXSAM,
                            ["name"] =  "U002" .. math.random(9999,99999),
                            ["communication"] = true,
                            ["start_time"] = 0,
                            ["frequency"] = 124,
						}	
			--trigger.action.outText("createSAMinRoute5 ", 10, false)
								  
		CampSAMRoute = coalition.addGroup(_country, Group.Category.GROUND, _SAMsdata)
		
		--trigger.action.outText("createSAMinRoute5 ", 10, false)
		
	
end


function createComboy(PosOriginal, distancia, isOnRoad)
	--trigger.action.outText("createComboy", 3)    
		
		--local nombreJugador = world.getPlayer():getName()		
		--local PosOriginal = Unit.getByName(nombreJugador):getPoint()		 
		--trigger.action.outText("POS x: ".. PosOriginal.x .. "; y: " .. PosOriginal.z, 10) 	
		
		
		local xAliados = PosOriginal.x + math.random(-distancia, distancia)
		local yAliados = PosOriginal.z + math.random(-distancia, distancia)
		local heading = math.random(259)
		
		if (isOnRoad) then
			local offsetx, offsety = land.getClosestPointOnRoads("roads", xAliados, yAliados)
			xAliados = offsetx
			yAliados = offsety
		end	
		
		
		local _groundtype = "M1043 HMMWV Armament" --M113; M1043 HMMWV Armament; M818
		local _groundtype2 = "M818"
		local _country = country.id.USA
		
		nameComboyGroup = getCallsign()            
            
		local _allydata =     {
                                ["modulation"] = 0,
                                ["tasks"] = 
                                {
                                }, -- end of ["tasks"]
                                ["task"] = "",
                                ["uncontrolled"] = false,
                                ["groupId"] = 500 + math.random(1, 1000),
                                ["hidden"] = false,
                                ["units"] = 
                                {
                                    [1] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = heading,                                        
                                        ["type"] = _groundtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yAliados,
                                        ["x"] = xAliados,                                        
                                        ["name"] =  "allyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]
								[2] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = heading,                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = yAliados + 10,
                                        ["x"] = xAliados + 10,                                        
                                        ["name"] =  "allyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]
								[3] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = heading,                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = yAliados + 20,
                                        ["x"] = xAliados + 20,                                        
                                        ["name"] =  "allyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]  
								[4] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = heading,                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = yAliados + 30,
                                        ["x"] = xAliados + 30,                                        
                                        ["name"] =  "allyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 25,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]  
                                }, -- end of ["units"]
                                ["y"] = yAliados,
                                ["x"] = xAliados,
                                ["name"] =  nameComboyGroup,
                                ["communication"] = true,
                                ["start_time"] = 0,
                                ["frequency"] = 124,
                    }
            
                    
		return coalition.addGroup(_country, Group.Category.GROUND, _allydata)     						
end;


function requestSatellite(PositionEarth)
	missionCommands.removeItem(menuReqSatellite)
	setMessageDelayed("[AREA18 COMMAND]: Command. Copied. Satellite will be in position in 2 minutes. Over", 15, 2)
	setSoundDelayed("COMMANDSatelliteRequest.ogg", 2)
	
	timer.scheduleFunction(createSatellite, PositionEarth, timer.getTime() + 120 + math.random(-30, 30))
	
	trigger.action.outText("Satellite surveillance IBCs cost: ".. 15000, 10)
	SaveInFile("financings.lua", "\n AccountingBalance = AccountingBalance - 15000 -- request satellite ", false)									
	AccountingBalance = AccountingBalance - 15000
	
end

function createSatellite(Position)
	--trigger.action.outText("createSatellite", 3)	
	
	local _groundtype = "TACAN_beacon"	
	local _country = country.id.USA	
	local nameAllySateliteGroup = "Satelite " .. math.random(9999,99999)

	local _tacandata =     {
                                ["modulation"] = 0,
                                ["tasks"] = 
                                {
                                }, -- end of ["tasks"]
                                ["task"] = "",
                                ["uncontrolled"] = false,
                                ["groupId"] = 500 + math.random(1, 1000),
                                ["hidden"] = false,
                                ["units"] = 
                                {
                                    [1] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = 0,                                        
                                        ["type"] = _groundtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = Position.y,
                                        ["x"] = Position.x,                                        
                                        ["name"] =  "Satelite" .. math.random(9999,99999),                                        
                                        ["speed"] = 0,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]
                                }, -- end of ["units"]
                                ["y"] = Position.y,
                                ["x"] = Position.x,
                                ["name"] = nameAllySateliteGroup,                                         
                                ["communication"] = true,
                                ["start_time"] = 0,
                                ["frequency"] = 124,
                    }
					
					
		local SetInvisible = { 
			  id = 'SetInvisible', 
			  params = { 
				value = true 
			  } 
			}
			
		local SetImmortal = { 
		  id = 'SetImmortal', 
		  params = { 
			value = true 
		  } 
		}	
        
		coalition.addGroup(_country, Group.Category.GROUND, _tacandata)
		
		local allySateliteController = Group.getByName(nameAllySateliteGroup):getController()
		allySateliteController:setCommand(SetInvisible)
		allySateliteController:setCommand(SetImmortal)
		
		
		return Group.getByName(nameAllySateliteGroup)	

end


function createAllyTroops(PosOriginal, distancia, minDistance)
		--trigger.action.outText("createAllyTroops", 3)    
				
		local xAliados
		local yAliados		
		
		repeat 			
			xAliados = PosOriginal.x + math.random(-distancia, distancia)
			yAliados = PosOriginal.z + math.random(-distancia, distancia)			
			--trigger.action.outText("x: " .. xAliados .. "y: " .. yAliados, 10) 
			--trigger.action.outText("dist: " ..getDistancePointPoint({x = xAliados, y = yAliados}, {x = PosOriginal.x, y = PosOriginal.z} ), 10) 			
		until getDistancePointPoint({x = xAliados, y = yAliados}, {x = PosOriginal.x, y = PosOriginal.z} ) >= minDistance		
						
		local _groundtype = "Soldier M249" 
		local _groundtype2 = "Soldier M4"
		local _country = country.id.USA
		nameAllyTroopsGroup = "allyTroops" .. math.random(9999,99999)
		    
		local _allydata =     {
                                ["modulation"] = 0,
                                ["tasks"] = 
                                {
                                }, -- end of ["tasks"]
                                ["task"] = "",
                                ["uncontrolled"] = false,
                                ["groupId"] = 500 + math.random(1, 1000),
                                ["hidden"] = false,
                                ["units"] = 
                                {
                                    [1] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = math.random(259),                                        
                                        ["type"] = _groundtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yAliados,
                                        ["x"] = xAliados,                                        
                                        ["name"] =  "allyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 0,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]
								[2] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = math.random(259),                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = yAliados + 5,
                                        ["x"] = xAliados + 5,                                        
                                        ["name"] =  "allyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 0,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]
								[3] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = math.random(259),                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = yAliados - 5,
                                        ["x"] = xAliados + 5,                                        
                                        ["name"] =  "allyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 0,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]  
								[4] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = math.random(259),                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = yAliados + 5,
                                        ["x"] = xAliados - 5,                                        
                                        ["name"] =  "allyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 0,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
									}, -- end of [1] 
								[5] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = math.random(259),                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = yAliados - 5,
                                        ["x"] = xAliados - 5,                                        
                                        ["name"] =  "allyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 0,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
									}, -- end of [1]
								[6] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = math.random(259),                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = yAliados - 5,
                                        ["x"] = xAliados - 10,                                        
                                        ["name"] =  "allyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 0,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]
								[7] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = math.random(259),                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = yAliados + 5,
                                        ["x"] = xAliados - 10,                                        
                                        ["name"] =  "allyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 0,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]
								[8] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = math.random(259),                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = yAliados + 5,
                                        ["x"] = xAliados + 10,                                        
                                        ["name"] =  "allyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 0,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]								
								[9] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = math.random(259),                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = yAliados + 10,
                                        ["x"] = xAliados + 10,                                        
                                        ["name"] =  "allyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 0,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]
								[10] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = math.random(259),                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = yAliados - 10,
                                        ["x"] = xAliados + 15,                                        
                                        ["name"] =  "allyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 0,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]								
								[11] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = math.random(259),                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = yAliados + 10,
                                        ["x"] = xAliados - 15,                                        
                                        ["name"] =  "allyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 0,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]
								[12] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = math.random(259),                                        
                                        ["type"] = _groundtype2,
                                        ["psi"] = 0,                                        
                                        ["y"] = yAliados - 10,
                                        ["x"] = xAliados - 15,                                        
                                        ["name"] =  "allyUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 0,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]
                                }, -- end of ["units"]
                                ["y"] = yAliados,
                                ["x"] = xAliados,
                                ["name"] =  nameAllyTroopsGroup,                                         
                                ["communication"] = true,
                                ["start_time"] = 0,
                                ["frequency"] = 124,
                    }
        
			coalition.addGroup(_country, Group.Category.GROUND, _allydata)
		return Group.getByName(nameAllyTroopsGroup)						
end;


function createAllyBombingGroup(posInitialAir, distance, typeGroup)
		--trigger.action.outText("createAllyBombingGroup", 3)    
		
		--local nombreJugador = world.getPlayer():getName()		
		--local PosOriginal = Unit.getByName(nombreJugador):getPoint()		 
		--trigger.action.outText("POS x: ".. PosOriginal.x .. "; y: " .. PosOriginal.z, 10) 	
		
		if nameAllyBombersGroup == nil  or nameAllyBombersGroup == "" then
			nameAllyBombersGroup = getAirCallsign()
		end
		
		local xAlly = posInitialAir.x - distance
		local yAlly = posInitialAir.y
				
		local heading = 0
		
		--trigger.action.outText("x: " .. xAlly .. "y: " .. yAlly, 10)    
		
		local _airtype = ""
		if typeGroup == 1 then
			_airtype = "A-10C"	
		end
			
		
		local _country = country.id.USA
		local _payload = nil
		

		_payload = {
				["pylons"] =
				{	[1] =
					{	
					["CLSID"] = "{DB769D48-67D7-42ED-A2BE-108D566C8B1E}",
					}, -- end of [1]			
					[2] =
					{	
					["CLSID"] = "{DB769D48-67D7-42ED-A2BE-108D566C8B1E}",
					}, -- end of [2]			
					[3] =
					{
					["CLSID"] = "{DB769D48-67D7-42ED-A2BE-108D566C8B1E}",
					}, -- end of [3]			
					[4] =
					{
					["CLSID"] = "{DB769D48-67D7-42ED-A2BE-108D566C8B1E}",
					}, -- end of [4]
					[5] =
					{
					["CLSID"] = "{DB769D48-67D7-42ED-A2BE-108D566C8B1E}",
					}, -- end of [5]
					[6] =
					{
					["CLSID"] = "{DB769D48-67D7-42ED-A2BE-108D566C8B1E}",
					}, -- end of [6]
					[7] =
					{
					["CLSID"] = "{DB769D48-67D7-42ED-A2BE-108D566C8B1E}",
					}, -- end of [7]
					[8] =
					{
					["CLSID"] = "{DB769D48-67D7-42ED-A2BE-108D566C8B1E}",
					}, -- end of [8]	
					[9] =
					{	
					["CLSID"] = "{DB769D48-67D7-42ED-A2BE-108D566C8B1E}",
					}, -- end of [9]							
					[10] =
					{
					["CLSID"] = "{A111396E-D3E8-4b9c-8AC9-2432489304D5}",
					}, -- end of [10]
					[11] =
					{					
					}, -- end of [3]		
					
				}, -- end of ["pylons"]
				["fuel"] = "6103",
				["flare"] = 120,
				["chaff"] = 240,
				["gun"] = 100,
			}
        
            
		local _allydata =     {
                                ["modulation"] = 0,
                                ["tasks"] = 
                                {
                                }, -- end of ["tasks"]
                                ["uncontrolled"] = false,
                                ["groupId"] = math.random(9999,99999),
                                ["hidden"] = false,
                                ["units"] = 
                                {
                                    [1] = 
                                    {
                                        ["alt"] = 8000,
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yAlly,
                                        ["x"] = xAlly,
										["payload"] = _payload,                                        
                                        ["name"] =  "allyAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 350,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]
								[2] = 
                                    {
                                        ["alt"] = 8000,
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yAlly,
                                        ["x"] = xAlly - 50,                                        
										["payload"] = _payload,
                                        ["name"] =  "allyAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 350,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]								
                                }, -- end of ["units"]
                                ["y"] = yAlly,
                                ["x"] = xAlly,
                                ["name"] =  nameAllyBombersGroup,
                                ["communication"] = true,
                                ["start_time"] = 0,
                                ["frequency"] = 117.5,
								["task"] = "CAS"
                    }
            
                    
			coalition.addGroup(_country, Group.Category.AIRPLANE, _allydata) 
			
			trigger.action.outText("nameAllyBombersGroup: " .. nameAllyBombersGroup, 10)    
			
			return Group.getByName(nameAllyBombersGroup) -- por alguna estupida razon el coalition.addgroup no devuelve el objeto grupo creado. Toca buscarlo a posteriori.
end


function requestSEAD(SAMGroup)
	
	missionCommands.removeItem(menuReqSEAD)	
	
	local posSAM = {x = coalition.getPlayers(coalition.side.BLUE)[1]:getPoint().x, y = coalition.getPlayers(coalition.side.BLUE)[1]:getPoint().z}
	
	local Players = coalition.getPlayers(coalition.side.BLUE)	
	if SAMGroup ~= nil then
		posSAM = {x = SAMGroup:getUnit(1):getPoint().x, y = SAMGroup:getUnit(1):getPoint().z}
	end
	
	local posX = posSAM.x - ((posSAM.x - VarPosOriginal.x)/2) + math.random(-5000, 5000)
	local posY = posSAM.y - ((posSAM.y - VarPosOriginal.z)/2) + math.random(-5000, 5000)
	
	timer.scheduleFunction(createAllySEADGroup, {x = posX, y = posY, pSAMGroup = SAMGroup}, timer.getTime() + 120 + math.random(-30, 30))
	
	--local SEADGroup = createAllySEADGroup({x = posX, y = posY}) 
	setMessageDelayed("[AREA18 COMMAND]: Command. Copied. Reinforcements will arrive in 2 minutes. Over", 15, 2)
	setSoundDelayed("DELCOMMANDReinforcementsETAR.ogg", 2)
end


function createAllySEADGroup(parameters)
		--trigger.action.outText("createAllySEADGroup", 10) 		
		nameAllySEADGroup = getAirCallsign()
		
		local xAlly = parameters.x 
		local yAlly = parameters.y
				
		local heading = 0
		
		local _airtype = "FA-18C_hornet"
		
					
		local _country = country.id.USA
		local _payload = nil
		
		_payload = {
				["pylons"] = {
								[1] = {
										["CLSID"] = "{6CEB49FC-DED8-4DED-B053-E1F033FF72D3}",
										["num"] = 9,
									},
									[2] = {
										["CLSID"] = "{6CEB49FC-DED8-4DED-B053-E1F033FF72D3}",
										["num"] = 1,
									},
									[3] = {
										["CLSID"] = "{B06DD79A-F21E-4EB9-BD9D-AB3844618C93}",
										["num"] = 3,
									},
									[4] = {
										["CLSID"] = "{B06DD79A-F21E-4EB9-BD9D-AB3844618C93}",
										["num"] = 8,
									},
									[5] = {
										["CLSID"] = "{B06DD79A-F21E-4EB9-BD9D-AB3844618C93}",
										["num"] = 7,
									},
									[6] = {
										["CLSID"] = "{B06DD79A-F21E-4EB9-BD9D-AB3844618C93}",
										["num"] = 2,
									},
									[7] = {
										["CLSID"] = "{B06DD79A-F21E-4EB9-BD9D-AB3844618C93}",
										["num"] = 5,
									},
							},
				["fuel"] = "6103",
				["flare"] = 120,
				["chaff"] = 240,
				["gun"] = 100,
			}
        
            
		local _allydata =     {								
                                ["modulation"] = 0,                                
                                ["uncontrolled"] = false,
                                ["groupId"] = math.random(9999,99999),
                                ["hidden"] = false,
                                ["units"] = 
                                {
                                    [1] = 
                                    {
                                        ["alt"] = 8000,
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yAlly,
                                        ["x"] = xAlly,
										["payload"] = _payload,                                        
                                        ["name"] =  "allyAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 350,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]
								[2] = 
                                    {
                                        ["alt"] = 8000,
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yAlly,
                                        ["x"] = xAlly - 50,                                        
										["payload"] = _payload,
                                        ["name"] =  "allyAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 350,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
									}, -- end of [2]
								[3] = 
                                    {
                                        ["alt"] = 8000,
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yAlly,
                                        ["x"] = xAlly + 50,                                        
										["payload"] = _payload,
                                        ["name"] =  "allyAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = 350,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [3]								
                                }, -- end of ["units"]
                                ["y"] = yAlly,
                                ["x"] = xAlly,
                                ["name"] =  nameAllySEADGroup,
                                ["communication"] = true,
                                ["start_time"] = 0,
                                ["frequency"] = 117.5,
								["task"] = "SEAD",
								["taskSelected"] = true,
                    }
            
                    
			coalition.addGroup(_country, Group.Category.AIRPLANE, _allydata) 
					
			doSEAD(Group.getByName(nameAllySEADGroup), parameters.pSAMGroup)
						
			if parameters.pSAMGroup ~= nil then
				
				if math.random(1,2) == 1 then
					setMessageDelayed("[AREA18 COMMAND]: Command. Reinforcements has arrived to the operations area. Over", 15, 2)
					setSoundDelayed("DELCOMMANDReinforcementsArriveR.ogg", 2)
				else
					setMessageDelayed("[SIERRA]: This is Sierra 1-1. We have arrive to the AO. Engaging targets. Over", 15, 2)
					setSoundDelayed("SIERRAengagingTarget.ogg", 2)
				end
			else
				setMessageDelayed("[SIERRA]: This is Sierra 1-1. We are not picking radar threats in the AO. Aborting mission. Over", 15, 10)
				setSoundDelayed("SIERRANoRadar.ogg", 10)
			end	
				
			
			trigger.action.outText("Ally reinforcements IBCs cost: ".. 15000, 10)
			SaveInFile("financings.lua", "\n AccountingBalance = AccountingBalance - 15000 -- request reinforcements F-18 ", false)									
			AccountingBalance = AccountingBalance - 15000
			
			return Group.getByName(nameAllySEADGroup)
end


function createAllyAirGroup()
		--trigger.action.outText("createAllyAirGroup", 3)   
		missionCommands.removeItem(menuReqHelp)			
						
		local heading = math.random(256)
		
		local _airtype = ""
		local _velocity = 10
		
		local _country = country.id.USA
		local _allyData = nil
		local _payload = nil
		
		-- los putos grupos aereos, cuando mueren, la variable que los contiene no es nil pero cualquier intento de acceso a lo que tenia dentro (el grupo) hace que de error.
		-- la unica manera de saber si un grupo aereo ha sido eliminado es hacer un getByName y ver si devuelve nil. Por eso debo conservar el nombre.
		nameAllyAirGroup = "AllyAirGroup" .. math.random(1,9999) 		
		
				
			_airtype = "F-5E"
			_velocity = 0	
			
			_payload = {
				["pylons"] =
				{	[1] =
					{		
					["CLSID"] = "{9BFD8C90-F7AE-4e90-833B-BFD0CED0E536}", --AIM-9
					}, -- end of [1]			
					[2] =
					{
					
					}, -- end of [2]
					[3] =
					{
					["CLSID"] = "{0395076D-2F77-4420-9D33-087A4398130B}", --fuel tank
					}, -- end of [3]					
					[4] =
					{
					["CLSID"] = "{0395076D-2F77-4420-9D33-087A4398130B}", --fuel tank
					}, -- end of [4]
					[5] =
					{
					["CLSID"] = "{0395076D-2F77-4420-9D33-087A4398130B}", --fuel tank
					}, -- end of [5]
					[6] =
					{
					
					}, -- end of [6]
					[7] =
					{
					["CLSID"] = "{9BFD8C90-F7AE-4e90-833B-BFD0CED0E536}", --AIM-9
					}, -- end of [7]
					
					
				}, -- end of ["pylons"]
				["fuel"] = "6103",
				["flare"] = 120,
				["chaff"] = 240,
				["gun"] = 100,
			}
				            
		_allyData =     {
                                ["modulation"] = 0,
                                ["tasks"] = 
                                {
                                }, -- end of ["tasks"]
                                ["uncontrolled"] = false,
                                ["groupId"] = math.random(9999,99999),
                                ["hidden"] = false,
								["route"] = 
												{
													["points"] = 
													{
														[1] = 
														{
															["alt"] = 0,
															["type"] = "TakeOffParkingHot",
															["action"] = "From Parking Area",															
															["alt_type"] = "RADIO",
															["formation_template"] = "",
															["ETA"] = 0,
															["airdromeId"] = 19,
															["y"] = VarPosOriginal.z,
															["x"] = VarPosOriginal.x,
															["speed"] = 0,
															["ETA_locked"] = true,															
															["speed_locked"] = true,
														}, -- end of [1]
													[2] = 
														{
															["alt"] = 5000,
															["type"] = "Turning Point",
															["action"] = "Fly Over Point",															
															["alt_type"] = "RADIO",
															["formation_template"] = "",
															["ETA"] = 0,															
															["y"] = VarPosOriginal.z + 5000,
															["x"] = VarPosOriginal.x + 5000,
															["speed"] = 500,
															["ETA_locked"] = true,															
															["speed_locked"] = true,
														}, -- end of [1]	
													}, -- end of ["points"]
												}, -- end of ["route"]
                                ["units"] = 
                                {
                                    [1] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = VarPosOriginal.z,
                                        ["x"] = VarPosOriginal.x,
										["parking"] = 51,
										["payload"] = _payload,                                        
                                        ["name"] =  "allyAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = _velocity,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "Excellent",
										
                                    }, -- end of [1]
								[2] = 
                                    {
                                        ["alt"] = 0,
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = VarPosOriginal.z,
                                        ["x"] = VarPosOriginal.x - 50,
										["parking"] = 50,
										["payload"] = _payload,
                                        ["name"] =  "allyAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = _velocity,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",										
									}, -- end of [2]																
                                }, -- end of ["units"]
                                ["y"] = VarPosOriginal.z,
                                ["x"] = VarPosOriginal.x,
                                ["name"] =  nameAllyAirGroup,
                                ["communication"] = true,
                                ["start_time"] = 0,
                                ["frequency"] = 131.5,
								["task"] = "Intercept",
                    }
					
					
				
		   
                    
		coalition.addGroup(_country, Group.Category.AIRPLANE, _allyData) 
		Group.getByName(nameAllyAirGroup):getController():setOption(AI.Option.Air.id.ROE, AI.Option.Air.val.ROE.WEAPON_FREE)
		--trigger.action.outText("createAllyAirGroup", 3)    
		setMessageDelayed("[AREA18 COMMAND]: India. Command. Reinforcements ready to take off from Shiraz. Over", 15, 2)
		setSoundDelayed("DELINDIAReinforcementsreadytakeoffshirazR.ogg", 2)
		
		trigger.action.outText("Ally reinforcements IBCs cost: ".. 10000, 10)
		SaveInFile("financings.lua", "\n AccountingBalance = AccountingBalance - 10000 -- request reinforcements F-5 ", false)									
		AccountingBalance = AccountingBalance - 10000
		
		airAllyAir = Group.getByName(nameAllyAirGroup)
		return airAllyAir  -- por alguna estupida razon el coalition.addgroup no devuelve el objeto grupo creado. Toca buscarlo a posteriori.
end


function createAllyAirGroupInAir()
		--trigger.action.outText("createAllyAirGroupInAir", 3)   
		missionCommands.removeItem(menuReqHelp)			
		
		local posPlayer = coalition.getPlayers(coalition.side.BLUE)[1]:getPoint()
						
		local heading = getHeading(coalition.getPlayers(coalition.side.BLUE)[1])	
		
		local _airtype = ""
		local _velocity = 400
		
		local _country = country.id.USA
		local _allyData = nil
		local _payload = nil
		
		-- los putos grupos aereos, cuando mueren, la variable que los contiene no es nil pero cualquier intento de acceso a lo que tenia dentro (el grupo) hace que de error.
		-- la unica manera de saber si un grupo aereo ha sido eliminado es hacer un getByName y ver si devuelve nil. Por eso debo conservar el nombre.
		nameAllyAirGroup = "AllyAirGroup" .. math.random(1,9999) 		
		
				
			_airtype = "M-2000C" -- "F-5E"
			_velocity = 300	
			
			_payload = {
				["pylons"] =
				{	[1] =
					{		
					["CLSID"] = "{MMagicII}", --Magic 
					}, -- end of [1]			
					[2] =
					{
					["CLSID"] = "{Matra_S530D}", --Matra
					}, -- end of [2]
					[3] =
					{
					
					}, -- end of [3]					
					[4] =
					{
					
					}, -- end of [4]
					[5] =
					{
					["CLSID"] = "{M2KC_RPL_522}", --fuel tank
					}, -- end of [5]
					[6] =
					{
					
					}, -- end of [6]
					[7] =
					{
					
					}, -- end of [7]
					[8] =
					{
					["CLSID"] = "{Matra_S530D}", --Matra
					}, -- end of [7]
					[9] =
					{
					["CLSID"] = "{MMagicII}", --Magic
					}, -- end of [7]
					
					
				}, -- end of ["pylons"]
				["fuel"] = "6103",
				["flare"] = 120,
				["chaff"] = 240,
				["gun"] = 100,
			}
				            
		_allyData =     {
                                ["modulation"] = 0,
                                ["tasks"] = 
                                {
                                }, -- end of ["tasks"]
                                ["uncontrolled"] = false,
                                ["groupId"] = math.random(9999,99999),
                                ["hidden"] = false,								
                                ["units"] = 
                                {
                                    [1] = 
                                    {
                                        ["alt"] = 15000,
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = posPlayer.z + 5000,
                                        ["x"] = posPlayer.x + 5000,										
										["payload"] = _payload,                                        
                                        ["name"] =  "allyAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = _velocity,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "Excellent",
										
                                    }, -- end of [1]
								[2] = 
                                    {
                                        ["alt"] = 15000,
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = posPlayer.z + 5000,
                                        ["x"] = posPlayer.x + 5050,										
										["payload"] = _payload,
                                        ["name"] =  "allyAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = _velocity,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",										
									}, -- end of [2]																
                                }, -- end of ["units"]
                                ["y"] = VarPosOriginal.z,
                                ["x"] = VarPosOriginal.x,
                                ["name"] =  nameAllyAirGroup,
                                ["communication"] = true,
                                ["start_time"] = 0,
                                ["frequency"] = 131.5,
								["task"] = "Intercept",
                    }
					
					                    
		coalition.addGroup(_country, Group.Category.AIRPLANE, _allyData) 
		Group.getByName(nameAllyAirGroup):getController():setOption(AI.Option.Air.id.ROE, AI.Option.Air.val.ROE.WEAPON_FREE)
		--trigger.action.outText("createAllyAirGroup", 3)    
		if math.random(1,2) == 1 then
			setMessageDelayed("[AREA18 COMMAND]: Command. Reinforcements has arrived to the operations area. Over", 15, 2)
			setSoundDelayed("DELCOMMANDReinforcementsArriveR.ogg", 2)
		else
			setMessageDelayed("[SIERRA]: This is Sierra 1-1. We have arrive to the AO. Engaging targets. Over", 15, 2)
			setSoundDelayed("SIERRAengagingTarget.ogg", 2)
		end
		
		trigger.action.outText("Ally reinforcements IBCs cost: ".. 15000, 10)
		SaveInFile("financings.lua", "\n AccountingBalance = AccountingBalance - 15000 -- request reinforcements F-5 ", false)									
		AccountingBalance = AccountingBalance - 15000
		--trigger.action.outText("creado escolta", 10)
		airAllyAir = Group.getByName(nameAllyAirGroup)
		return allyAirGroup -- por alguna estupida razon el coalition.addgroup no devuelve el objeto grupo creado. Toca buscarlo a posteriori.
end


function setEscortAttackHostiles()
	--trigger.action.outText("setEscortAttackHostiles", 10)
	local hostileAirGroup = Group.getByName(nameHostileAirGroup)
	local allyAirGroup = Group.getByName(nameAllyAirGroup)
	
	--trigger.action.outText("hostiles: " .. hostileAirGroup:getName(), 10)
	--trigger.action.outText("aliados: " .. allyAirGroup:getName(), 10)

	--trigger.action.outText("pointZhostiles: " .. hostileAirGroup:getUnit(1):getPoint().z, 10)
	--trigger.action.outText("pointZaliados: " .. allyAirGroup:getUnit(1):getPoint().z, 10)

	
	if (Group.getByName(nameHostileAirGroup) ~= nil and Group.getByName(nameAllyAirGroup) ~= nil) then			
		setAirRoute(allyAirGroup, {x = hostileAirGroup:getUnit(1):getPoint().x, y = hostileAirGroup:getUnit(1):getPoint().z, z = hostileAirGroup:getUnit(1):getPoint().y + 100}, {x = hostileAirGroup:getUnit(1):getPoint().x, y = hostileAirGroup:getUnit(1):getPoint().z, z = hostileAirGroup:getUnit(1):getPoint().y}, 250)	
	end
end


function requestEscort()
	--trigger.action.outText("requestEscort: ", 10)
	local delaySec = 120 + math.random(-30, 30)
	timer.scheduleFunction(createAllyAirGroupInAir, nil, timer.getTime() + delaySec)
	
	timer.scheduleFunction(setEscortAttackHostiles, nil, timer.getTime() + delaySec + 3)
	
	setMessageDelayed("[AREA18 COMMAND]: Command. Copied. Reinforcements will arrive in 2 minutes. Over", 15, 2)
	setSoundDelayed("DELCOMMANDReinforcementsETAR.ogg", 2)
	
end


function createHostilesBomberGroup(posInitialAir, minDistance, distancia)
		--trigger.action.outText("createHostilesBomberGroup", 3)    
		
		local xHostiles = 0
		local yHostiles = 0		
		repeat 			
			xHostiles = posInitialAir.x - math.random(-distancia, distancia)
			yHostiles = posInitialAir.y - math.random(-distancia, distancia)			
			--trigger.action.outText("x: " .. xHostiles .. "y: " .. yHostiles, 10)    
		until getDistancePointPoint({x = xHostiles, y = yHostiles}, {x = VarPosOriginal.x, y = VarPosOriginal.z} ) >= minDistance
				
		local heading = math.random(256)		
		local typeEscortGroup = math.random(1, 2) --rndOBJ
		local typeBomberGroup = math.random(1, 2) --rndOBJ
		   
		
		local _airtype = ""
		local _velocity = 0
		
		local _country = country.id.IRAN
		local _Hostiledata = nil
		
		
		-- los putos grupos aereos, cuando mueren, la variable que los contiene no es nil pero cualquier intento de acceso a lo que tenia dentro (el grupo) hace que de error.
		-- la unica manera de saber si un grupo aereo ha sido eliminado es hacer un getByName y ver si devuelve nil. Por eso debo conservar el nombre.
		nameHostileAirGroup = "hostile" .. math.random(1,9999) 
		nameHostileBomberGroup = "hostileBomber" .. math.random(1,9999)
		
		if typeEscortGroup == 1 then
			_airtype = "MiG-29A"
			_velocity = 600	
			
			_payload = {
				["pylons"] =
				{	[1] =
					{		
					["CLSID"] = "{FBC29BFE-3D24-4C64-B81D-941239D12249}", --R-73
					}, -- end of [1]			
					[2] =
					{
					["CLSID"] = "{FBC29BFE-3D24-4C64-B81D-941239D12249}", --R-73
					}, -- end of [2]			
					[3] =
					{	
					["CLSID"] = "{E8069896-8435-4B90-95C0-01A03AE6E400}", --R-27ER
					}, -- end of [3]			
					[4] =
					{
					["CLSID"] = "{2BEC576B-CDF5-4B7F-961F-B0FA4312B841}", --fuel tank
					}, -- end of [4]
					[5] =
					{
					["CLSID"] = "{E8069896-8435-4B90-95C0-01A03AE6E400}", --R-27ER
					}, -- end of [5]
					[6] =
					{
					["CLSID"] = "{FBC29BFE-3D24-4C64-B81D-941239D12249}", --R-27ER
					}, -- end of [6]
					[7] =
					{
					["CLSID"] = "{FBC29BFE-3D24-4C64-B81D-941239D12249}", --R-27ER
					}, -- end of [7]
					
				}, -- end of ["pylons"]
				["fuel"] = "6103",
				["flare"] = 120,
				["chaff"] = 240,
				["gun"] = 100,
			}
				            
		_Hostiledata =     {
                                ["modulation"] = 0,
                                ["tasks"] = 
                                {
                                }, -- end of ["tasks"]
                                ["uncontrolled"] = false,
                                ["groupId"] = math.random(9999,99999),
                                ["hidden"] = false,
                                ["units"] = 
                                {
                                    [1] = 
                                    {
                                        ["alt"] = 2000,
										["alt_type"] = "RADIO",
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yHostiles,
                                        ["x"] = xHostiles,
										["payload"] = _payload,                                        
                                        ["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = _velocity,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]
								[2] = 
                                    {
                                        ["alt"] = 2000,
										["alt_type"] = "RADIO",
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yHostiles,
                                        ["x"] = xHostiles - 50,                                        
										["payload"] = _payload,
                                        ["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = _velocity,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
									}, -- end of [2]															
                                }, -- end of ["units"]
                                ["y"] = yHostiles,
                                ["x"] = xHostiles,
                                ["name"] =  nameHostileAirGroup,
                                ["communication"] = true,
                                ["start_time"] = 0,
                                ["frequency"] = 127.5,
								["task"] = "Intercept",
                    }
					
					
		--si hay mas de un jugador
		local numberPlayers = getNumberOfPlayers()
		if numberPlayers >= 2 then			
					_Hostiledata["units"][3] = 
							{
								["alt"] = 2000,
								["alt_type"] = "RADIO",
								["heading"] = heading,                                        
								["type"] = _airtype,
								["psi"] = 0,                                        
								["y"] = yHostiles - 200,
								["x"] = xHostiles + 200,                                       
								["payload"] = _payload,
								["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
								["speed"] = _velocity,
								["unitId"] =  math.random(9999,99999),                                        
								["skill"] = "High",
							}
					_Hostiledata["units"][4] = 
							{
								["alt"] = 2000,
								["alt_type"] = "RADIO",
								["heading"] = heading,                                        
								["type"] = _airtype,
								["psi"] = 0,                                        
								["y"] = yHostiles - 300,
								["x"] = xHostiles + 300,                                       
								["payload"] = _payload,
								["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
								["speed"] = _velocity,
								["unitId"] =  math.random(9999,99999),                                        
								["skill"] = "High",
							}		
		end				
					
					
		elseif typeEscortGroup == 2 then
			_airtype = "F-16C bl.50"
			_velocity = 600	
			
			_payload = {
				["pylons"] =
				{	[1] =
					{		
					["CLSID"] = "{AIM-9L}", --R-73
					}, -- end of [1]			
					[2] =
					{
					["CLSID"] = "{C8E06185-7CD6-4C90-959F-044679E90751}", --AIM-120
					}, -- end of [2]			
					[3] =
					{	
					["CLSID"] = "{C8E06185-7CD6-4C90-959F-044679E90751}", --AIM-120
					}, -- end of [3]			
					[4] =
					{
					["CLSID"] = "{F376DBEE-4CAE-41BA-ADD9-B2910AC95DEC}", --fuel tank
					}, -- end of [4]
					[5] =
					{					
					}, -- end of [5]
					[6] =
					{
					
					}, -- end of [6]
					[7] =
					{
					["CLSID"] = "{F376DBEE-4CAE-41BA-ADD9-B2910AC95DEC}", --fuel tank
					}, -- end of [7]
					[8] =
					{
					["CLSID"] = "{C8E06185-7CD6-4C90-959F-044679E90751}", --AIM-120
					}, -- end of [8]
					[9] =
					{
					["CLSID"] = "{C8E06185-7CD6-4C90-959F-044679E90751}", --AIM-120
					}, -- end of [9]
					[10] =
					{
					["CLSID"] = "{AIM-9L}", --R-73
					}, -- end of [10]
					
					
				}, -- end of ["pylons"]
				["fuel"] = "6103",
				["flare"] = 120,
				["chaff"] = 240,
				["gun"] = 100,
			}
				            
		_Hostiledata =     {
                                ["modulation"] = 0,
                                ["tasks"] = 
                                {
                                }, -- end of ["tasks"]
                                ["uncontrolled"] = false,
                                ["groupId"] = math.random(9999,99999),
                                ["hidden"] = false,
                                ["units"] = 
                                {
                                    [1] = 
                                    {
                                        ["alt"] = 2000,
										["alt_type"] = "RADIO",
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yHostiles,
                                        ["x"] = xHostiles,
										["payload"] = _payload,                                        
                                        ["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = _velocity,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]
								[2] = 
                                    {
                                        ["alt"] = 2000,
										["alt_type"] = "RADIO",
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yHostiles,
                                        ["x"] = xHostiles - 50,                                        
										["payload"] = _payload,
                                        ["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = _velocity,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
									}, -- end of [2]															
                                }, -- end of ["units"]
                                ["y"] = yHostiles,
                                ["x"] = xHostiles,
                                ["name"] =  nameHostileAirGroup,
                                ["communication"] = true,
                                ["start_time"] = 0,
                                ["frequency"] = 127.5,
								["task"] = "Intercept",
                    }					
		
		end
		
		--si hay mas de un jugador
		local numberPlayers = getNumberOfPlayers()
		if numberPlayers >= 2 then			
					_Hostiledata["units"][3] = 
							{
								["alt"] = 2000,
								["alt_type"] = "RADIO",
								["heading"] = heading,                                        
								["type"] = _airtype,
								["psi"] = 0,                                        
								["y"] = yHostiles - 200,
								["x"] = xHostiles + 200,                                       
								["payload"] = _payload,
								["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
								["speed"] = _velocity,
								["unitId"] =  math.random(9999,99999),                                        
								["skill"] = "Excellent",
							}
					_Hostiledata["units"][4] = 
							{
								["alt"] = 2000,
								["alt_type"] = "RADIO",
								["heading"] = heading,                                        
								["type"] = _airtype,
								["psi"] = 0,                                        
								["y"] = yHostiles - 300,
								["x"] = xHostiles + 300,                                       
								["payload"] = _payload,
								["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
								["speed"] = _velocity,
								["unitId"] =  math.random(9999,99999),                                        
								["skill"] = "High",
							}		
		end	
				
		
		--Bombarderos
		local _Hostilebomberdata = nil

		
		if typeBomberGroup == 1 then
			_airtype = "A-10C"
			_velocity = 600	
		
			_payload = {
				["pylons"] =
				{	[1] =
					{	
					["CLSID"] = "{DB769D48-67D7-42ED-A2BE-108D566C8B1E}",
					}, -- end of [1]			
					[2] =
					{	
					["CLSID"] = "{DB769D48-67D7-42ED-A2BE-108D566C8B1E}",
					}, -- end of [2]			
					[3] =
					{
					["CLSID"] = "{DB769D48-67D7-42ED-A2BE-108D566C8B1E}",
					}, -- end of [3]			
					[4] =
					{
					["CLSID"] = "{DB769D48-67D7-42ED-A2BE-108D566C8B1E}",
					}, -- end of [4]
					[5] =
					{
					["CLSID"] = "{DB769D48-67D7-42ED-A2BE-108D566C8B1E}",
					}, -- end of [5]
					[6] =
					{
					["CLSID"] = "{DB769D48-67D7-42ED-A2BE-108D566C8B1E}",
					}, -- end of [6]
					[7] =
					{
					["CLSID"] = "{DB769D48-67D7-42ED-A2BE-108D566C8B1E}",
					}, -- end of [7]
					[8] =
					{
					["CLSID"] = "{DB769D48-67D7-42ED-A2BE-108D566C8B1E}",
					}, -- end of [8]	
					[9] =
					{	
					["CLSID"] = "{DB769D48-67D7-42ED-A2BE-108D566C8B1E}",
					}, -- end of [9]							
					[10] =
					{
					["CLSID"] = "{A111396E-D3E8-4b9c-8AC9-2432489304D5}",
					}, -- end of [10]
					[11] =
					{					
					}, -- end of [3]		
					
				}, -- end of ["pylons"]
				["fuel"] = "6103",
				["flare"] = 120,
				["chaff"] = 240,
				["gun"] = 100,
			}
        
			            
			_HostileBomberdata =     {
                            ["modulation"] = 0,
                            ["tasks"] = 
                            {
                            }, -- end of ["tasks"]
                            ["uncontrolled"] = false,
                            ["groupId"] = math.random(9999,99999),
                            ["hidden"] = false,
                            ["units"] = 
                            {
                                [1] = 
                                {
                                    ["alt"] = 2000,
									["alt_type"] = "RADIO",
                                    ["heading"] = heading,                                        
                                    ["type"] = _airtype,
                                    ["psi"] = 0,                                        
                                    ["y"] = yHostiles,
                                    ["x"] = xHostiles - 200,
									["payload"] = _payload,                                        
                                    ["name"] =  "hostileBomberUnit" .. math.random(9999,99999),                                        
                                    ["speed"] = 350,
                                    ["unitId"] =  math.random(9999,99999),                                        
                                    ["skill"] = "High",
                                }, -- end of [1]
								[2] = 
                                {
                                    ["alt"] = 2000,
									["alt_type"] = "RADIO",
                                    ["heading"] = heading,                                        
                                    ["type"] = _airtype,
                                    ["psi"] = 0,                                        
                                    ["y"] = yHostiles,
                                    ["x"] = xHostiles - 250,                                        
									["payload"] = _payload,
                                    ["name"] =  "hostileBomberUnit" .. math.random(9999,99999),                                        
                                    ["speed"] = 350,
                                    ["unitId"] =  math.random(9999,99999),                                        
                                    ["skill"] = "High",
                                }, -- end of [1]									
                            }, -- end of ["units"]
                            ["y"] = yHostiles,
                            ["x"] = xHostiles - 200,
                            ["name"] =  nameHostileBomberGroup,
                            ["communication"] = true,
                            ["start_time"] = 0,
                            ["frequency"] = 117.5,
						["task"] = "CAS",
                }
			
		elseif typeBomberGroup == 2 then
			_airtype = "Su-25"
			_velocity = 600	
		
			_payload = {
				["pylons"] =
				{	[1] =
					{	
					["CLSID"] = "{37DCC01E-9E02-432F-B61D-10C166CA2798}",
					}, -- end of [1]			
					[2] =
					{	
					["CLSID"] = "{37DCC01E-9E02-432F-B61D-10C166CA2798}",
					}, -- end of [2]			
					[3] =
					{
					["CLSID"] = "{37DCC01E-9E02-432F-B61D-10C166CA2798}",
					}, -- end of [3]			
					[4] =
					{
					["CLSID"] = "{37DCC01E-9E02-432F-B61D-10C166CA2798}",
					}, -- end of [4]
					[5] =
					{
					["CLSID"] = "{37DCC01E-9E02-432F-B61D-10C166CA2798}",
					}, -- end of [5]
					[6] =
					{
					["CLSID"] = "{37DCC01E-9E02-432F-B61D-10C166CA2798}",
					}, -- end of [6]
					[7] =
					{
					["CLSID"] = "{37DCC01E-9E02-432F-B61D-10C166CA2798}",
					}, -- end of [7]
					[8] =
					{
					["CLSID"] = "{37DCC01E-9E02-432F-B61D-10C166CA2798}",
					}, -- end of [8]	
					[9] =
					{	
					["CLSID"] = "{37DCC01E-9E02-432F-B61D-10C166CA2798}",
					}, -- end of [9]							
					[10] =
					{
					["CLSID"] = "{37DCC01E-9E02-432F-B61D-10C166CA2798}",
					}, -- end of [10]						
					
				}, -- end of ["pylons"]
				["fuel"] = "6103",
				["flare"] = 120,
				["chaff"] = 240,
				["gun"] = 100,
			}
        
			            
			_HostileBomberdata =     {
                            ["modulation"] = 0,
                            ["tasks"] = 
                            {
                            }, -- end of ["tasks"]
                            ["uncontrolled"] = false,
                            ["groupId"] = math.random(9999,99999),
                            ["hidden"] = false,
                            ["units"] = 
                            {
                                [1] = 
                                {
                                    ["alt"] = 2000,
									["alt_type"] = "RADIO",
                                    ["heading"] = heading,                                        
                                    ["type"] = _airtype,
                                    ["psi"] = 0,                                        
                                    ["y"] = yHostiles,
                                    ["x"] = xHostiles - 200,
									["payload"] = _payload,                                        
                                    ["name"] =  "hostileBomberUnit" .. math.random(9999,99999),                                        
                                    ["speed"] = 350,
                                    ["unitId"] =  math.random(9999,99999),                                        
                                    ["skill"] = "High",
                                }, -- end of [1]
								[2] = 
                                {
                                    ["alt"] = 2000,
									["alt_type"] = "RADIO",
                                    ["heading"] = heading,                                        
                                    ["type"] = _airtype,
                                    ["psi"] = 0,                                        
                                    ["y"] = yHostiles,
                                    ["x"] = xHostiles - 250,                                        
									["payload"] = _payload,
                                    ["name"] =  "hostileBomberUnit" .. math.random(9999,99999),                                        
                                    ["speed"] = 350,
                                    ["unitId"] =  math.random(9999,99999),                                        
                                    ["skill"] = "High",
                                }, -- end of [1]									
                            }, -- end of ["units"]
                            ["y"] = yHostiles,
                            ["x"] = xHostiles - 200,
                            ["name"] =  nameHostileBomberGroup,
                            ["communication"] = true,
                            ["start_time"] = 0,
                            ["frequency"] = 117.5,
						["task"] = "CAS",
                }
			end
            
                    
			coalition.addGroup(_country, Group.Category.AIRPLANE, _Hostiledata) 
			coalition.addGroup(_country, Group.Category.AIRPLANE, _HostileBomberdata) 
			Group.getByName(nameHostileAirGroup):getController():setOption(AI.Option.Air.id.ROE, AI.Option.Air.val.ROE.WEAPON_FREE)
			Group.getByName(nameHostileBomberGroup):getController():setOption(AI.Option.Air.id.ROE, AI.Option.Air.val.ROE.WEAPON_FREE)
			local returnObj = {HostileEscortGroup = Group.getByName(nameHostileAirGroup), HostileBomberGroup = Group.getByName(nameHostileBomberGroup)}
			return returnObj -- por alguna estupida razon el coalition.addgroup no devuelve el objeto grupo creado. Toca buscarlo a posteriori.
end


function createHostilesAirGroup(posInitialAir, minDistance, distancia, heading)
		--trigger.action.outText("createHostilesAirGroup", 10)    
		
		local xHostiles = 0
		local yHostiles = 0	
				
		repeat 			
			xHostiles = posInitialAir.x - math.random(-distancia, distancia)
			yHostiles = posInitialAir.y - math.random(-distancia, distancia)			
			--trigger.action.outText("x: " .. xHostiles .. "y: " .. yHostiles, 10)    
		until getDistancePointPoint({x = xHostiles, y = yHostiles}, {x = VarPosOriginal.x, y = VarPosOriginal.z} ) >= minDistance
		
		if heading == nil then
			heading = math.random(256)
		end
		
		local _airtype = ""
		local _velocity = 0
		
		local _country = country.id.IRAN
		local _Hostiledata = nil
		local _payload = nil
		
		-- los putos grupos aereos, cuando mueren, la variable que los contiene no es nil pero cualquier intento de acceso a lo que tenia dentro (el grupo) hace que de error.
		-- la unica manera de saber si un grupo aereo ha sido eliminado es hacer un getByName y ver si devuelve nil. Por eso debo conservar el nombre.
		nameHostileAirGroup = "hostile" .. math.random(1,9999) 		
		
		local typeGroup = math.random(1, 2) --rndOBJ
		
		if typeGroup == 1 then
			_airtype = "MiG-29A"
			_velocity = 600	
			
			_payload = {
				["pylons"] =
				{	[1] =
					{		
					["CLSID"] = "{FBC29BFE-3D24-4C64-B81D-941239D12249}", --R-73
					}, -- end of [1]			
					[2] =
					{
					["CLSID"] = "{FBC29BFE-3D24-4C64-B81D-941239D12249}", --R-73
					}, -- end of [2]			
					[3] =
					{	
					["CLSID"] = "{E8069896-8435-4B90-95C0-01A03AE6E400}", --R-27ER
					}, -- end of [3]			
					[4] =
					{
					["CLSID"] = "{2BEC576B-CDF5-4B7F-961F-B0FA4312B841}", --fuel tank
					}, -- end of [4]
					[5] =
					{
					["CLSID"] = "{E8069896-8435-4B90-95C0-01A03AE6E400}", --R-27ER
					}, -- end of [5]
					[6] =
					{
					["CLSID"] = "{FBC29BFE-3D24-4C64-B81D-941239D12249}", --R-73
					}, -- end of [6]
					[7] =
					{
					["CLSID"] = "{FBC29BFE-3D24-4C64-B81D-941239D12249}", --R-73
					}, -- end of [7]
					
				}, -- end of ["pylons"]
				["fuel"] = "6103",
				["flare"] = 120,
				["chaff"] = 240,
				["gun"] = 100,
			}
				            
		_Hostiledata =     {
                                ["modulation"] = 0,
                                ["tasks"] = 
                                {
                                }, -- end of ["tasks"]
                                ["uncontrolled"] = false,
                                ["groupId"] = math.random(9999,99999),
                                ["hidden"] = false,
                                ["units"] = 
                                {
                                    [1] = 
                                    {
                                        ["alt"] = 2000,
										["alt_type"] = "RADIO",
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yHostiles,
                                        ["x"] = xHostiles,
										["payload"] = _payload,                                        
                                        ["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = _velocity,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]
								[2] = 
                                    {
                                        ["alt"] = 2000,
										["alt_type"] = "RADIO",
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yHostiles,
                                        ["x"] = xHostiles - 50,                                        
										["payload"] = _payload,
                                        ["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = _velocity,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
									}, -- end of [2]															
                                }, -- end of ["units"]
                                ["y"] = yHostiles,
                                ["x"] = xHostiles,
                                ["name"] =  nameHostileAirGroup,
                                ["communication"] = true,
                                ["start_time"] = 0,
                                ["frequency"] = 127.5,
								["task"] = "Intercept",
                    }
					
									
				--si hay mas de un jugador
				local numberPlayers = getNumberOfPlayers()
				if numberPlayers >= 2 then					
						_Hostiledata["units"][3] =  
                             {
                                ["alt"] = 2000,
								["alt_type"] = "RADIO",
                                ["heading"] = heading,                                        
                                ["type"] = _airtype,
                                ["psi"] = 0,                                        
                                ["y"] = yHostiles,
                                ["x"] = xHostiles - 100,                                        
								["payload"] = _payload,
                                ["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
                                ["speed"] = _velocity,
                                ["unitId"] =  math.random(9999,99999),                                        
                                ["skill"] = "High",
							}
							
						_Hostiledata["units"][4] = 
							{
								["alt"] = 2000,
								["alt_type"] = "RADIO",
								["heading"] = heading,                                        
								["type"] = _airtype,
								["psi"] = 0,                                        
								["y"] = yHostiles - 200,
								["x"] = xHostiles + 200,                                       
								["payload"] = _payload,
								["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
								["speed"] = _velocity,
								["unitId"] =  math.random(9999,99999),                                        
								["skill"] = "High",
							}							
				end
					
					
		elseif typeGroup == 2 then
			_airtype = "F-16C bl.50"
			_velocity = 600	
			
			_payload = {
				["pylons"] =
				{	[1] =
					{		
					["CLSID"] = "{AIM-9L}", --AIM-9
					}, -- end of [1]			
					[2] =
					{
					["CLSID"] = "{C8E06185-7CD6-4C90-959F-044679E90751}", --AIM-120
					}, -- end of [2]			
					[3] =
					{	
					["CLSID"] = "{8D399DDA-FF81-4F14-904D-099B34FE7918}", --AIM-7
					}, -- end of [3]			
					[4] =
					{
					["CLSID"] = "{F376DBEE-4CAE-41BA-ADD9-B2910AC95DEC}", --fuel tank
					}, -- end of [4]
					[5] =
					{					
					}, -- end of [5]
					[6] =
					{
					
					}, -- end of [6]
					[7] =
					{
					["CLSID"] = "{F376DBEE-4CAE-41BA-ADD9-B2910AC95DEC}", --fuel tank
					}, -- end of [7]
					[8] =
					{
					["CLSID"] = "{8D399DDA-FF81-4F14-904D-099B34FE7918}", --AIM-7
					}, -- end of [8]
					[9] =
					{
					["CLSID"] = "{C8E06185-7CD6-4C90-959F-044679E90751}", --AIM-120
					}, -- end of [9]
					[10] =
					{
					["CLSID"] = "{AIM-9L}", --AIM-9
					}, -- end of [10]
					
					
				}, -- end of ["pylons"]
				["fuel"] = "6103",
				["flare"] = 120,
				["chaff"] = 240,
				["gun"] = 100,
			}
				            
		_Hostiledata =     {
                                ["modulation"] = 0,
                                ["tasks"] = 
                                {
                                }, -- end of ["tasks"]
                                ["uncontrolled"] = false,
                                ["groupId"] = math.random(9999,99999),
                                ["hidden"] = false,
                                ["units"] = 
                                {
                                    [1] = 
                                    {
                                        ["alt"] = 2000,
										["alt_type"] = "RADIO",
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yHostiles,
                                        ["x"] = xHostiles,
										["payload"] = _payload,                                        
                                        ["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = _velocity,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "Excellent",
                                    }, -- end of [1]
								[2] = 
                                    {
                                        ["alt"] = 2000,
										["alt_type"] = "RADIO",
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yHostiles,
                                        ["x"] = xHostiles - 50,                                        
										["payload"] = _payload,
                                        ["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = _velocity,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "Excellent",
									}, -- end of [2]																
                                }, -- end of ["units"]
                                ["y"] = yHostiles,
                                ["x"] = xHostiles,
                                ["name"] =  nameHostileAirGroup,
                                ["communication"] = true,
                                ["start_time"] = 0,
                                ["frequency"] = 127.5,
								["task"] = "Intercept",
                    }	
					
				--si hay mas de un jugador
				local numberPlayers = getNumberOfPlayers()
				if numberPlayers >= 2 then					
						_Hostiledata["units"][3] = 
                                    {
                                        ["alt"] = 2000,
										["alt_type"] = "RADIO",
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yHostiles,
                                        ["x"] = xHostiles - 100,                                        
										["payload"] = _payload,
                                        ["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = _velocity,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "Excellent",
                                    } -- end of [3]
							
						_Hostiledata["units"][4] = 
                                    {
                                        ["alt"] = 2000,
										["alt_type"] = "RADIO",
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yHostiles - 200,
                                        ["x"] = xHostiles + 200,                                       
										["payload"] = _payload,
                                        ["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = _velocity,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "Excellent",
                                    }									
				end			
		end
		   
                    
		coalition.addGroup(_country, Group.Category.AIRPLANE, _Hostiledata) 
		Group.getByName(nameHostileAirGroup):getController():setOption(AI.Option.Air.id.ROE, AI.Option.Air.val.ROE.WEAPON_FREE)
		--trigger.action.outText(Group.getByName(nameHostileAirGroup):getName(), 10)  
		return Group.getByName(nameHostileAirGroup) -- por alguna estupida razon el coalition.addgroup no devuelve el objeto grupo creado. Toca buscarlo a posteriori.
end


function createHostilesDefenderAirGroup()
		--trigger.action.outText("createHostilesAirGroup", 10)    
		
		local xHostiles = 0
		local yHostiles = 0	
		
		local posCamp = {x = CampStaticTarget:getPoint().x, y = CampStaticTarget:getPoint().z}
					
		xHostiles = posCamp.x + ((posCamp.x - VarPosOriginal.x)/2) + math.random(-35000, 35000)
		yHostiles = posCamp.y + ((posCamp.y - VarPosOriginal.z)/2) + math.random(-35000, 35000)	
		
		
		heading = math.random(256)		
		
		local _airtype = ""
		local _velocity = 0
		
		local _country = country.id.IRAN
		local _Hostiledata = nil
		local _payload = nil
		
		-- los putos grupos aereos, cuando mueren, la variable que los contiene no es nil pero cualquier intento de acceso a lo que tenia dentro (el grupo) hace que de error.
		-- la unica manera de saber si un grupo aereo ha sido eliminado es hacer un getByName y ver si devuelve nil. Por eso debo conservar el nombre.
		nameHostileDefenderAirGroup = "hostileDefender" .. math.random(1,9999) 		
				
		local typeGroup = math.random(1, 2) --rndOBJ
		
		if typeGroup == 1 then
			_airtype = "MiG-19P"
			_velocity = 600	
			
			_payload = {
				["pylons"] = {
								[1] = {
									["CLSID"] = "{K-13A}"
								},
								[2] = {
									["CLSID"] = "PTB760_MIG19"
								},
								[5] = {
									["CLSID"] = "PTB760_MIG19"
								},
								[6] = {
									["CLSID"] = "{K-13A}"
								},	
							},
				["fuel"] = "6103",
				["flare"] = 120,
				["chaff"] = 240,
				["gun"] = 100,
			}
				            
		_Hostiledata =     {
                                ["modulation"] = 0,
                                ["tasks"] = 
                                {
                                }, -- end of ["tasks"]
                                ["uncontrolled"] = false,
                                ["groupId"] = math.random(9999,99999),
                                ["hidden"] = false,
                                ["units"] = 
                                {
                                    [1] = 
                                    {
                                        ["alt"] = 2000,
										["alt_type"] = "RADIO",
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yHostiles,
                                        ["x"] = xHostiles,
										["payload"] = _payload,                                        
                                        ["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = _velocity,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [1]
								[2] = 
                                    {
                                        ["alt"] = 2000,
										["alt_type"] = "RADIO",
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yHostiles,
                                        ["x"] = xHostiles - 50,                                        
										["payload"] = _payload,
                                        ["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = _velocity,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
									}, -- end of [2]															
                                }, -- end of ["units"]
                                ["y"] = yHostiles,
                                ["x"] = xHostiles,
                                ["name"] =  nameHostileDefenderAirGroup,
                                ["communication"] = true,
                                ["start_time"] = 0,
                                ["frequency"] = 127.5,
								["task"] = "Intercept",
                    }
					
									
				--si hay mas de un jugador
				local numberPlayers = getNumberOfPlayers()
				if numberPlayers >= 2 then					
						_Hostiledata["units"][3] =  
                             {
                                ["alt"] = 2000,
								["alt_type"] = "RADIO",
                                ["heading"] = heading,                                        
                                ["type"] = _airtype,
                                ["psi"] = 0,                                        
                                ["y"] = yHostiles,
                                ["x"] = xHostiles - 100,                                        
								["payload"] = _payload,
                                ["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
                                ["speed"] = _velocity,
                                ["unitId"] =  math.random(9999,99999),                                        
                                ["skill"] = "High",
							}
							
						_Hostiledata["units"][4] = 
							{
								["alt"] = 2000,
								["alt_type"] = "RADIO",
								["heading"] = heading,                                        
								["type"] = _airtype,
								["psi"] = 0,                                        
								["y"] = yHostiles - 200,
								["x"] = xHostiles + 200,                                       
								["payload"] = _payload,
								["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
								["speed"] = _velocity,
								["unitId"] =  math.random(9999,99999),                                        
								["skill"] = "High",
							}							
				end
					
					
		elseif typeGroup == 2 then
			_airtype = "MiG-21Bis"
			_velocity = 600	
			
			_payload = {
				["pylons"] = {
								[1] = {
									["CLSID"] = "{R-60}"
								},
								[3] = {
									["CLSID"] = "{PTB_800_MIG21}"
								},
								[5] = {
									["CLSID"] = "{R-60}"
								},								
							},
				["fuel"] = "6103",
				["flare"] = 120,
				["chaff"] = 240,
				["gun"] = 100,
			}
				            
		_Hostiledata =     {
                                ["modulation"] = 0,
                                ["tasks"] = 
                                {
                                }, -- end of ["tasks"]
                                ["uncontrolled"] = false,
                                ["groupId"] = math.random(9999,99999),
                                ["hidden"] = false,
                                ["units"] = 
                                {
                                    [1] = 
                                    {
                                        ["alt"] = 2000,
										["alt_type"] = "RADIO",
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yHostiles,
                                        ["x"] = xHostiles,
										["payload"] = _payload,                                        
                                        ["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = _velocity,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "Excellent",
                                    }, -- end of [1]
								[2] = 
                                    {
                                        ["alt"] = 2000,
										["alt_type"] = "RADIO",
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yHostiles,
                                        ["x"] = xHostiles - 50,                                        
										["payload"] = _payload,
                                        ["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = _velocity,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "Excellent",
									}, -- end of [2]																
                                }, -- end of ["units"]
                                ["y"] = yHostiles,
                                ["x"] = xHostiles,
                                ["name"] =  nameHostileDefenderAirGroup,
                                ["communication"] = true,
                                ["start_time"] = 0,
                                ["frequency"] = 127.5,
								["task"] = "Intercept",
                    }	
					
				--si hay mas de un jugador
				local numberPlayers = getNumberOfPlayers()
				if numberPlayers >= 2 then					
						_Hostiledata["units"][3] = 
                                    {
                                        ["alt"] = 2000,
										["alt_type"] = "RADIO",
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yHostiles,
                                        ["x"] = xHostiles - 100,                                        
										["payload"] = _payload,
                                        ["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = _velocity,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "Excellent",
                                    } -- end of [3]
							
						_Hostiledata["units"][4] = 
                                    {
                                        ["alt"] = 2000,
										["alt_type"] = "RADIO",
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yHostiles - 200,
                                        ["x"] = xHostiles + 200,                                       
										["payload"] = _payload,
                                        ["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = _velocity,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "Excellent",
                                    }									
				end			
		end
		   
                    
		coalition.addGroup(_country, Group.Category.AIRPLANE, _Hostiledata) 
		
		-- mandamos a defender el campamento enemigo
		local Orbit = { 
			 id = 'Orbit', 
			 params = { 
			   pattern = "Race-Track",
			   point = {posCamp.x,  posCamp.y},
			   point2 = nil,
			   speed = 300,
			   altitude = 20000
			 } 
			}
		
		local routePoints = {}		
							
			routePoints[1] = {
								["alt"] = 20000,
                                ["type"] = "Turning Point",
								["action"] = "Turning Point",
								["alt_type"] = "BARO",
                                ["formation_template"] = "",
                                ["ETA"] = 0,
                                ["y"] = yHostiles,
                                ["x"] = xHostiles,
								["speed"] = 300,
                                ["ETA_locked"] = false,                                
                                ["speed_locked"] = true,			
								}	
		
			routePoints[2] = {
								["alt"] = 20000,
								["task"] = Orbit,
                                ["type"] = "Turning Point",
								["action"] = "Turning Point",
								["alt_type"] = "BARO",
                                ["formation_template"] = "",
                                ["ETA"] = 0,
                                ["y"] = posCamp.y,
                                ["x"] = posCamp.x,
								["speed"] = speed,
                                ["ETA_locked"] = false,                                
                                ["speed_locked"] = true,			
								}
							
					
		local _mission = { 
            id = 'Mission', 
            params = { 
				airborne = true,
                route = { 
                    points = routePoints
                }, 
            } 
        }
	
		isHostilesDefenderAirGroupCreated = true;
		local hostilesController = Group.getByName(nameHostileDefenderAirGroup):getController()
	    --hostilesController:setOption(AI.Option.Air.id.ROE, AI.Option.Air.val.ROE.WEAPON_FREE)
		hostilesController:setTask(_mission)
		
		--trigger.action.outText(Group.getByName(nameHostileDefenderAirGroup):getName(), 10)  
		return Group.getByName(nameHostileDefenderAirGroup) -- por alguna estupida razon el coalition.addgroup no devuelve el objeto grupo creado. Toca buscarlo a posteriori.
end


function createCivilAirGroup(posInitialAir, minDistance, distancia)
		--trigger.action.outText("createCivilAirGroup", 10)    
		
		local xNeutral = 0
		local yNeutral = 0		
		repeat 			
			xNeutral = posInitialAir.x - math.random(-distancia, distancia)
			yNeutral = posInitialAir.y - math.random(0, distancia)			
			--trigger.action.outText("x: " .. xNeutral .. "y: " .. yNeutral, 10)    
		until getDistancePointPoint({x = xNeutral, y = yNeutral}, {x = VarPosOriginal.x, y = VarPosOriginal.z} ) >= minDistance
				
		local heading = math.random(256)
		
		local _airtype = ""		
		
		local _country = country.id.JAPAN
		local _Neutraldata = nil
		local _payload = nil
		
		-- los putos grupos aereos, cuando mueren, la variable que los contiene no es nil pero cualquier intento de acceso a lo que tenia dentro (el grupo) hace que de error.
		-- la unica manera de saber si un grupo aereo ha sido eliminado es hacer un getByName y ver si devuelve nil. Por eso debo conservar el nombre.
		nameCivilAirGroup = "neutral" .. math.random(1,9999) 		
		
		local typeGroup = math.random(1, 3) --rndOBJ
		
		if typeGroup == 1 then
			_airtype = "B_747"			
		elseif typeGroup == 2 then
			_airtype = "B_757"	
		elseif typeGroup == 3 then
			_airtype = "A_320"			
		end	

		_payload = {			
				["fuel"] = "250000",				
			}		
		
		_Neutraldata =     {
                                ["modulation"] = 0,
                                ["tasks"] = 
                                {
                                }, -- end of ["tasks"]
                                ["uncontrolled"] = false,
                                ["groupId"] = math.random(9999,99999),
                                ["hidden"] = false,
                                ["units"] = 
                                {
                                    [1] = 
                                    {
                                        ["alt"] = 6000,
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yNeutral,
                                        ["x"] = xNeutral,
										["payload"] = _payload,                                        
                                        ["name"] =  nameCivilAirGroup,                                       
                                        ["speed"] = 300,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "Excellent",
                                    }, -- end of [1]															
                                }, -- end of ["units"]
                                ["y"] = yNeutral,
                                ["x"] = xNeutral,
                                ["name"] =  nameCivilAirGroup,
                                ["communication"] = true,
                                ["start_time"] = 0,
                                ["frequency"] = 127.5,
								["task"] = nil,
                    }
							   
                    
		coalition.addGroup(_country, Group.Category.AIRPLANE, _Neutraldata) 		
		--trigger.action.outText(Group.getByName(nameCivilAirGroup):getName(), 10)  
		return Group.getByName(nameCivilAirGroup) -- por alguna estupida razon el coalition.addgroup no devuelve el objeto grupo creado. Toca buscarlo a posteriori.
end


function createNotHostileAirGroup(posInitialAir, minDistance, distancia)
		--trigger.action.outText("createCivilAirGroup", 10)    
		
		local xNeutral = 0
		local yNeutral = 0		
		repeat 			
			xNeutral = posInitialAir.x - math.random(-distancia, distancia)
			yNeutral = posInitialAir.y - math.random(0, distancia)			
			--trigger.action.outText("x: " .. xNeutral .. "y: " .. yNeutral, 10)    
		until getDistancePointPoint({x = xNeutral, y = yNeutral}, {x = VarPosOriginal.x, y = VarPosOriginal.z} ) >= minDistance
				
		local heading = 326
		
		local _airtype = ""		
		
		local _country = country.id.IRAQ
		local _notHostiledata = nil
		local _payload = nil
		
		-- los putos grupos aereos, cuando mueren, la variable que los contiene no es nil pero cualquier intento de acceso a lo que tenia dentro (el grupo) hace que de error.
		-- la unica manera de saber si un grupo aereo ha sido eliminado es hacer un getByName y ver si devuelve nil. Por eso debo conservar el nombre.
		nameNotHostileAirGroup = "Bogie" .. math.random(1,9999) 		
		
		local typeGroup = math.random(1, 4) --rndOBJ
		
		if typeGroup <= 2 then
			_airtype = "B-1B"			
		else
			_airtype = "B-52H"					
		end	

		_payload = {			
				["fuel"] = "250000",				
			}		
		
		_notHostiledata =     {
                                ["modulation"] = 0,
                                ["tasks"] = 
                                {
                                }, -- end of ["tasks"]
                                ["uncontrolled"] = false,
                                ["groupId"] = math.random(9999,99999),
                                ["hidden"] = false,
                                ["units"] = 
                                {
                                    [1] = 
                                    {
                                        ["alt"] = 6000,
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yNeutral,
                                        ["x"] = xNeutral,
										["payload"] = _payload,                                        
                                        ["name"] =  nameNotHostileAirGroup,                                        
                                        ["speed"] = 100,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "Excellent",
                                    }, -- end of [1]															
                                }, -- end of ["units"]
                                ["y"] = yNeutral,
                                ["x"] = xNeutral,
                                ["name"] =  nameNotHostileAirGroup,
                                ["communication"] = true,
                                ["start_time"] = 0,
                                ["frequency"] = 127.5,
								["task"] = nil,
                    }
							   
                    
		local _controler = coalition.addGroup(_country, Group.Category.AIRPLANE, _notHostiledata) 		
		
		Controller.setOption(_controler, AI.Option.Ground.id.ALARM_STATE, AI.Option.Ground.val.ALARM_STATE.GREEN)
		Controller.setOption(_controler, AI.Option.Air.id.REACTION_ON_THREAT, AI.Option.Air.val.REACTION_ON_THREAT.NO_REACTION)
		
		typeNotHostileInDestiny = 0
		
		return Group.getByName(nameNotHostileAirGroup) -- por alguna estupida razon el coalition.addgroup no devuelve el objeto grupo creado. Toca buscarlo a posteriori.
end


function createHostilesSwarm(posInitialAir, minDistance, distancia)
		--trigger.action.outText("createHostilesSwarm", 3)    
		
		local xHostiles = 0
		local yHostiles = 0		
		repeat 			
			xHostiles = posInitialAir.x - math.random(-distancia, distancia)
			yHostiles = posInitialAir.y - math.random(-distancia, distancia)			
			--trigger.action.outText("x: " .. xHostiles .. "y: " .. yHostiles, 10)    
		until getDistancePointPoint({x = xHostiles, y = yHostiles}, {x = VarPosOriginal.x, y = VarPosOriginal.z} ) >= minDistance
				
		local heading = math.random(256)
		
		local _airtype = ""
		local _velocity = 0
		
		local _country = country.id.IRAN
		local _Hostiledata1 = nil
		local _payload = nil
		
		-- los putos grupos aereos, cuando mueren, la variable que los contiene no es nil pero cualquier intento de acceso a lo que tenia dentro (el grupo) hace que de error.
		-- la unica manera de saber si un grupo aereo ha sido eliminado es hacer un getByName y ver si devuelve nil. Por eso debo conservar el nombre.
		nameHostileSwarm1 = "hostile" .. math.random(1,9999) 		
		nameHostileSwarm2 = "hostile2" .. math.random(1,9999) 		
		nameHostileSwarm3 = "hostile3" .. math.random(1,9999) 		
		nameHostileSwarm4 = "hostile4" .. math.random(1,9999) 		
		
		local typeGroup = math.random(1, 2) --rndOBJ
		
		if typeGroup == 1 then
			_airtype = "MiG-19P"
		else
			_airtype = "F-4E"
		end
			_velocity = 400	
			
			_payload = {				
				["fuel"] = "6103",
				["flare"] = 120,
				["chaff"] = 240,
				["gun"] = 100,
			}
				            
			_Hostiledata1 =     {
                                ["modulation"] = 0,
                                ["tasks"] = 
                                {
                                }, -- end of ["tasks"]
                                ["uncontrolled"] = false,
                                ["groupId"] = math.random(9999,99999),
                                ["hidden"] = false,
                                ["units"] = 
                                {
                                    [1] = 
                                    {
                                        ["alt"] = 8000,
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yHostiles,
                                        ["x"] = xHostiles,
										["payload"] = _payload,                                        
                                        ["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = _velocity,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "Excellent",
                                    }, -- end of [1]
								[2] = 
                                    {
                                        ["alt"] = 8000,
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yHostiles,
                                        ["x"] = xHostiles - 50,                                        
										["payload"] = _payload,
                                        ["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = _velocity,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
									}, -- end of [2]															
                                }, -- end of ["units"]
                                ["y"] = yHostiles,
                                ["x"] = xHostiles,
                                ["name"] =  nameHostileSwarm1,
                                ["communication"] = true,
                                ["start_time"] = 0,
                                ["frequency"] = 127.5,
								["task"] = "Intercept",
                    }
					
			_Hostiledata2 =     {
                                ["modulation"] = 0,
                                ["tasks"] = 
                                {
                                }, -- end of ["tasks"]
                                ["uncontrolled"] = false,
                                ["groupId"] = math.random(9999,99999),
                                ["hidden"] = false,
                                ["units"] = 
                                {
                                    [1] = 
                                    {
                                        ["alt"] = 8000,
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yHostiles - 200,
                                        ["x"] = xHostiles,
										["payload"] = _payload,                                        
                                        ["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = _velocity,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "Excellent",
                                    }, -- end of [1]
								[2] = 
                                    {
                                        ["alt"] = 8000,
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yHostiles - 300,
                                        ["x"] = xHostiles - 50,                                        
										["payload"] = _payload,
                                        ["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = _velocity,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
									}, -- end of [2]															
                                }, -- end of ["units"]
                                ["y"] = yHostiles - 100,
                                ["x"] = xHostiles - 100,
                                ["name"] =  nameHostileSwarm2,
                                ["communication"] = true,
                                ["start_time"] = 0,
                                ["frequency"] = 127.5,
								["task"] = "Intercept",
                    }
					
			_Hostiledata3 =     {
                                ["modulation"] = 0,
                                ["tasks"] = 
                                {
                                }, -- end of ["tasks"]
                                ["uncontrolled"] = false,
                                ["groupId"] = math.random(9999,99999),
                                ["hidden"] = false,
                                ["units"] = 
                                {
                                    [1] = 
                                    {
                                        ["alt"] = 8000,
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yHostiles - 200,
                                        ["x"] = xHostiles - 100,
										["payload"] = _payload,                                        
                                        ["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = _velocity,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "Excellent",
                                    }, -- end of [1]																									
                                }, -- end of ["units"]
                                ["y"] = yHostiles - 500,
                                ["x"] = xHostiles - 500,
                                ["name"] =  nameHostileSwarm3,
                                ["communication"] = true,
                                ["start_time"] = 0,
                                ["frequency"] = 127.5,
								["task"] = "Intercept",
                    }	
					
			_Hostiledata4 =     {
                                ["modulation"] = 0,
                                ["tasks"] = 
                                {
                                }, -- end of ["tasks"]
                                ["uncontrolled"] = false,
                                ["groupId"] = math.random(9999,99999),
                                ["hidden"] = false,
                                ["units"] = 
                                {
                                    [1] = 
                                    {
                                        ["alt"] = 8000,
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yHostiles - 200,
                                        ["x"] = xHostiles + 100,
										["payload"] = _payload,                                        
                                        ["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = _velocity,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "Excellent",
                                    }, -- end of [1]																								
                                }, -- end of ["units"]
                                ["y"] = yHostiles - 400,
                                ["x"] = xHostiles - 400,
                                ["name"] =  nameHostileSwarm4,
                                ["communication"] = true,
                                ["start_time"] = 0,
                                ["frequency"] = 127.5,
								["task"] = "Intercept",
                    }		
					
				--si hay mas de un jugador
				local numberPlayers = getNumberOfPlayers()
				if numberPlayers >= 2 then	
					_Hostiledata1["units"][3] = 
							{
								["alt"] = 8000,
								["heading"] = heading,                                        
								["type"] = _airtype,
								["psi"] = 0,                                        
								["y"] = yHostiles - 400,
								["x"] = xHostiles + 400,                                       
								["payload"] = _payload,
								["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
								["speed"] = _velocity,
								["unitId"] =  math.random(9999,99999),                                        
								["skill"] = "Excellent",
							}					
					_Hostiledata1["units"][4] = 
							{
								["alt"] = 8000,
								["heading"] = heading,                                        
								["type"] = _airtype,
								["psi"] = 0,                                        
								["y"] = yHostiles - 400,
								["x"] = xHostiles + 500,                                       
								["payload"] = _payload,
								["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
								["speed"] = _velocity,
								["unitId"] =  math.random(9999,99999),                                        
								["skill"] = "Excellent",
							}
							
					_Hostiledata2["units"][3] = 
							{
								["alt"] = 8000,
								["heading"] = heading,                                        
								["type"] = _airtype,
								["psi"] = 0,                                        
								["y"] = yHostiles - 600,
								["x"] = xHostiles + 600,                                       
								["payload"] = _payload,
								["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
								["speed"] = _velocity,
								["unitId"] =  math.random(9999,99999),                                        
								["skill"] = "Excellent",
							}							
                    _Hostiledata2["units"][4] = 
							{
								["alt"] = 8000,
								["heading"] = heading,                                        
								["type"] = _airtype,
								["psi"] = 0,                                        
								["y"] = yHostiles - 600,
								["x"] = xHostiles + 700,                                       
								["payload"] = _payload,
								["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
								["speed"] = _velocity,
								["unitId"] =  math.random(9999,99999),                                        
								["skill"] = "Excellent",
							}
					_Hostiledata3["units"][2] = 
							{
								["alt"] = 8000,
								["heading"] = heading,                                        
								["type"] = _airtype,
								["psi"] = 0,                                        
								["y"] = yHostiles - 400,
								["x"] = xHostiles + 600,                                       
								["payload"] = _payload,
								["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
								["speed"] = _velocity,
								["unitId"] =  math.random(9999,99999),                                        
								["skill"] = "Excellent",
							}							
                    _Hostiledata3["units"][3] = 
							{
								["alt"] = 8000,
								["heading"] = heading,                                        
								["type"] = _airtype,
								["psi"] = 0,                                        
								["y"] = yHostiles - 500,
								["x"] = xHostiles + 700,                                       
								["payload"] = _payload,
								["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
								["speed"] = _velocity,
								["unitId"] =  math.random(9999,99999),                                        
								["skill"] = "Excellent",
							}
					_Hostiledata4["units"][2] = 
							{
								["alt"] = 8000,
								["heading"] = heading,                                        
								["type"] = _airtype,
								["psi"] = 0,                                        
								["y"] = yHostiles - 300,
								["x"] = xHostiles + 600,                                       
								["payload"] = _payload,
								["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
								["speed"] = _velocity,
								["unitId"] =  math.random(9999,99999),                                        
								["skill"] = "Excellent",
							}							
                    _Hostiledata4["units"][3] = 
							{
								["alt"] = 8000,
								["heading"] = heading,                                        
								["type"] = _airtype,
								["psi"] = 0,                                        
								["y"] = yHostiles - 200,
								["x"] = xHostiles + 700,                                       
								["payload"] = _payload,
								["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
								["speed"] = _velocity,
								["unitId"] =  math.random(9999,99999),                                        
								["skill"] = "Excellent",
							}			
				end
				   
                    
		coalition.addGroup(_country, Group.Category.AIRPLANE, _Hostiledata1) 
		coalition.addGroup(_country, Group.Category.AIRPLANE, _Hostiledata2) 
		coalition.addGroup(_country, Group.Category.AIRPLANE, _Hostiledata3) 
		coalition.addGroup(_country, Group.Category.AIRPLANE, _Hostiledata4) 
		
		Group.getByName(nameHostileSwarm1):getController():setOption(AI.Option.Air.id.ROE, AI.Option.Air.val.ROE.WEAPON_FREE)
		Group.getByName(nameHostileSwarm2):getController():setOption(AI.Option.Air.id.ROE, AI.Option.Air.val.ROE.WEAPON_FREE)
		Group.getByName(nameHostileSwarm3):getController():setOption(AI.Option.Air.id.ROE, AI.Option.Air.val.ROE.WEAPON_FREE)
		Group.getByName(nameHostileSwarm4):getController():setOption(AI.Option.Air.id.ROE, AI.Option.Air.val.ROE.WEAPON_FREE)
			
		
		local returnGroups = {Group1 = Group.getByName(nameHostileSwarm1), Group2 = Group.getByName(nameHostileSwarm2), Group3 = Group.getByName(nameHostileSwarm3), Group4 = Group.getByName(nameHostileSwarm4)}		
		return returnGroups -- por alguna estupida razon el coalition.addgroup no devuelve el objeto grupo creado. Toca buscarlo a posteriori.
end


function createHostilesAirGroupExtra(posInitialAir, minDistance, distancia)
		--trigger.action.outText("createHostilesAirGroupExtra", 3)    
		
		local xHostiles = 0
		local yHostiles = 0		
		repeat 			
			xHostiles = posInitialAir.x + distancia
			yHostiles = posInitialAir.y + distancia 
			--trigger.action.outText("x: " .. xHostiles .. "y: " .. yHostiles, 10)    
		until getDistancePointPoint({x = xHostiles, y = yHostiles}, {x = VarPosOriginal.x, y = VarPosOriginal.z} ) >= minDistance
		  		
		local heading = math.random(256)
		
		local _airtype = ""
		local _velocity = 0
		
		local _country = country.id.IRAN
		local _Hostiledata = nil
		local _payload = nil
		
		-- los putos grupos aereos, cuando mueren, la variable que los contiene no es nil pero cualquier intento de acceso a lo que tenia dentro (el grupo) hace que de error.
		-- la unica manera de saber si un grupo aereo ha sido eliminado es hacer un getByName y ver si devuelve nil. Por eso debo conservar el nombre.
		nameHostileAirGroupExtra = "hostile" .. math.random(1,9999) 		
		
		local typeGroup = math.random(1, 2) --rndOBJ
		
		if typeGroup == 1 then
			_airtype = "MiG-29A"
			_velocity = 600	
			
			_payload = {
				["pylons"] =
				{	[1] =
					{		
					["CLSID"] = "{FBC29BFE-3D24-4C64-B81D-941239D12249}", --R-73
					}, -- end of [1]			
					[2] =
					{
					["CLSID"] = "{FBC29BFE-3D24-4C64-B81D-941239D12249}", --R-73
					}, -- end of [2]			
					[3] =
					{	
					["CLSID"] = "{E8069896-8435-4B90-95C0-01A03AE6E400}", --R-27ER
					}, -- end of [3]			
					[4] =
					{
					["CLSID"] = "{2BEC576B-CDF5-4B7F-961F-B0FA4312B841}", --fuel tank
					}, -- end of [4]
					[5] =
					{
					["CLSID"] = "{E8069896-8435-4B90-95C0-01A03AE6E400}", --R-27ER
					}, -- end of [5]
					[6] =
					{
					["CLSID"] = "{FBC29BFE-3D24-4C64-B81D-941239D12249}", --R-73
					}, -- end of [6]
					[7] =
					{
					["CLSID"] = "{FBC29BFE-3D24-4C64-B81D-941239D12249}", --R-73
					}, -- end of [7]
					
				}, -- end of ["pylons"]
				["fuel"] = "6103",
				["flare"] = 120,
				["chaff"] = 240,
				["gun"] = 100,
			}
				            
		_Hostiledata =     {
                                ["modulation"] = 0,
                                ["tasks"] = 
                                {
                                }, -- end of ["tasks"]
                                ["uncontrolled"] = false,
                                ["groupId"] = math.random(9999,99999),
                                ["hidden"] = false,
                                ["units"] = 
                                {
                                    [1] = 
                                    {
                                        ["alt"] = 2000,
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yHostiles,
                                        ["x"] = xHostiles,
										["payload"] = _payload,                                        
                                        ["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = _velocity,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "Excellent",
                                    }, -- end of [1]
								[2] = 
                                    {
                                        ["alt"] = 2000,
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yHostiles,
                                        ["x"] = xHostiles - 50,                                        
										["payload"] = _payload,
                                        ["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = _velocity,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
									}, -- end of [2]
								[3] = 
                                    {
                                        ["alt"] = 2000,
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yHostiles,
                                        ["x"] = xHostiles - 100,                                        
										["payload"] = _payload,
                                        ["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = _velocity,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "High",
                                    }, -- end of [3]								
                                }, -- end of ["units"]
                                ["y"] = yHostiles,
                                ["x"] = xHostiles,
                                ["name"] =  nameHostileAirGroupExtra,
                                ["communication"] = true,
                                ["start_time"] = 0,
                                ["frequency"] = 127.5,
								["task"] = "Intercept",
                    }
				
			elseif typeGroup == 2 then
			_airtype = "F-16C bl.50"
			_velocity = 600	
			
			_payload = {
				["pylons"] =
				{	[1] =
					{		
					["CLSID"] = "{AIM-9L}", --R-73
					}, -- end of [1]			
					[2] =
					{
					["CLSID"] = "{C8E06185-7CD6-4C90-959F-044679E90751}", --AIM-120
					}, -- end of [2]			
					[3] =
					{	
					["CLSID"] = "{8D399DDA-FF81-4F14-904D-099B34FE7918}", --AIM-7
					}, -- end of [3]			
					[4] =
					{
					["CLSID"] = "{F376DBEE-4CAE-41BA-ADD9-B2910AC95DEC}", --fuel tank
					}, -- end of [4]
					[5] =
					{					
					}, -- end of [5]
					[6] =
					{
					
					}, -- end of [6]
					[7] =
					{
					["CLSID"] = "{F376DBEE-4CAE-41BA-ADD9-B2910AC95DEC}", --fuel tank
					}, -- end of [7]
					[8] =
					{
					["CLSID"] = "{8D399DDA-FF81-4F14-904D-099B34FE7918}", --AIM-7
					}, -- end of [8]
					[9] =
					{
					["CLSID"] = "{C8E06185-7CD6-4C90-959F-044679E90751}", --AIM-120
					}, -- end of [9]
					[10] =
					{
					["CLSID"] = "{AIM-9L}", --R-73
					}, -- end of [10]
					
					
				}, -- end of ["pylons"]
				["fuel"] = "6103",
				["flare"] = 120,
				["chaff"] = 240,
				["gun"] = 100,
			}
				            
		_Hostiledata =     {
                                ["modulation"] = 0,
                                ["tasks"] = 
                                {
                                }, -- end of ["tasks"]
                                ["uncontrolled"] = false,
                                ["groupId"] = math.random(9999,99999),
                                ["hidden"] = false,
                                ["units"] = 
                                {
                                    [1] = 
                                    {
                                        ["alt"] = 2000,
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yHostiles,
                                        ["x"] = xHostiles,
										["payload"] = _payload,                                        
                                        ["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = _velocity,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "Excellent",
                                    }, -- end of [1]
								[2] = 
                                    {
                                        ["alt"] = 2000,
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yHostiles,
                                        ["x"] = xHostiles - 50,                                        
										["payload"] = _payload,
                                        ["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = _velocity,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "Excellent",
									}, -- end of [2]
								[3] = 
                                    {
                                        ["alt"] = 2000,
                                        ["heading"] = heading,                                        
                                        ["type"] = _airtype,
                                        ["psi"] = 0,                                        
                                        ["y"] = yHostiles,
                                        ["x"] = xHostiles - 100,                                        
										["payload"] = _payload,
                                        ["name"] =  "hostileAirUnit" .. math.random(9999,99999),                                        
                                        ["speed"] = _velocity,
                                        ["unitId"] =  math.random(9999,99999),                                        
                                        ["skill"] = "Excellent",
                                    }, -- end of [3]								
                                }, -- end of ["units"]
                                ["y"] = yHostiles,
                                ["x"] = xHostiles,
                                ["name"] =  nameHostileAirGroupExtra,
                                ["communication"] = true,
                                ["start_time"] = 0,
                                ["frequency"] = 127.5,
								["task"] = "Intercept",
                    }			
		end
		   
                    
		coalition.addGroup(_country, Group.Category.AIRPLANE, _Hostiledata) 
		Group.getByName(nameHostileAirGroupExtra):getController():setOption(AI.Option.Air.id.ROE, AI.Option.Air.val.ROE.WEAPON_FREE)
		return Group.getByName(nameHostileAirGroupExtra) -- por alguna estupida razon el coalition.addgroup no devuelve el objeto grupo creado. Toca buscarlo a posteriori.
end


function reconCampament()	

	local posCamp = {x = CampStaticTarget:getPoint().x, y = CampStaticTarget:getPoint().z}
	
	local Players = coalition.getPlayers(coalition.side.BLUE)	 
	local isPlayerInRange = false
	for i = 1, #Players do		
		if getDistancePoint(Players[i]:getGroup(), posCamp)  <= 15000 and Players[i]:getPoint().y >= 3000 then
			isPlayerInRange = true
		end
	end	
	
	--isPlayerInRange = true
		
	if isPlayerInRange	
	then		
		missionCommands.removeItem(menuReconCamp)	
		isCampRecon = true;		
		
		if string.match(getPlayersTypes():gsub("%-", "_"), "MB_339PAN" .. ";" ) or
			string.match(getPlayersTypes():gsub("%-", "_"), "T_45" .. ";" )then	
			setMessageDelayed("[HIPSTER]: Wilco. Recon started. Let's stay in the area for a couple of minutes to allow the camera to take good images from the target, but do not get too close to it.", 15, 2)					
			setSoundDelayed("HIPSTERReconInit.ogg", 2)
		else
			trigger.action.outText("(INFO: Recon initiated. Stay in the area until the recon has been completed.)", 10, true)        	
		end
		
	else
		if string.match(getPlayersTypes():gsub("%-", "_"), "MB_339PAN" .. ";" ) or
			string.match(getPlayersTypes():gsub("%-", "_"), "T_45" .. ";" )then	
			setMessageDelayed("[HIPSTER]: Can't comply. We are too far away from the target yet. Let's get closer, man.", 15, 2)					
			setSoundDelayed("HIPSTERReconKO.ogg", 2)
		else
			trigger.action.outText("INFO: (All players are to far away from the campament to recon it. You need to get closer.) ", 10, true)        	
		end
		
		
	end
end;


function isGroupDestroyed(pGroup)	
	if (pGroup == nil or pGroup:getUnit(1) == nil) then		
		return true;
	else		
		return false;
	end
	
end


function allyGroupSave(allyGroup, destiny)
	if allyGroup ~= nil and destiny ~= nil and isGroupDestroyed(allyGroup) == false then		
		local PosAlly = allyGroup:getUnit(1):getPoint()    
		if (math.abs(PosAlly.x - destiny.x) < 100 and math.abs(PosAlly.z - destiny.y) < 100) then 
			--trigger.action.outText("llegaroooooon", 60)         
			return true
		else
			--trigger.action.outText("xoffset: ".. (PosAlly.x - destino.x) .. "; yoffset: " .. (PosAlly.z - destino.y), 1)    
			return false
		end		
	else
		return false
	end
end;


function embarkGroup(group, coordx, coordy)
	EmbarkToTransport = {
	 id = "EmbarkToTransport",
	 params = {
	   x = coordx,
	   y = coordy,
	   zoneRadius = 600
	 }
	}	 
	 
	group:getController():setTask(EmbarkToTransport)

end;


function setRouteAllyComboy(isOnRoad)
--	local factorHelo = 1
--	if missionType == 3 then--si es helicoptero, hacemos la ruta del comboy mas pequena
--		factorHelo = 0.5
--	end
--	
--	destinationComboy = setDestiny(comboyAllyGroup, 4000, true, factorHelo)
--	local PosGroup = comboyAllyGroup:getUnit(1):getPoint()		
--	originComboy = {x = PosGroup.x, y = PosGroup.z}
--	
--	
--	setGroundRoute(comboyAllyGroup, originComboy, destinationComboy, 40, true)	
	
	missionCommands.removeItem(menuProcRoute)		
	isComboyMoving = true;
	menuReqStop = missionCommands.addCommand('Stop comboy', menuPrinc2, requestStopComboy, nil)
	menuReqCont = missionCommands.addCommand('Continue route', menuPrinc2, requestContinueComboy, nil)
	resetRouteAllyComboy()
	setMessageDelayed("[".. string.upper(nameComboyGroup) .. "]:Eco group. " .. nameComboyGroup .. ". Oscar-Mike, proceeding with route. Over", 20, 2)	
	setSoundDelayed("DELECOOscarMikeproceedingrouteR.ogg", 2)
end;


function setRouteComboyAttackers(isOnroad)
	--trigger.action.outText("setRouteComboyAttackers", 10)
	local PosGroupAlly = comboyAllyGroup:getUnit(1):getPoint();
	local tableDestiny = {x = PosGroupAlly.x + 50, y = PosGroupAlly.z + 50};
	
	local PosGroupAttack = comboyAttackerGroup:getUnit(1):getPoint();
	local tableOrigin = {x = PosGroupAttack.x, y = PosGroupAttack.z};
		
	setGroundRoute(comboyAttackerGroup, tableOrigin, tableDestiny, 65, isOnroad);
end;


function loadComboyCoordinates()
	--Añadimos ruta a los aviones flaming cliff 3
			local PosAlly = comboyAllyGroup:getUnit(1):getPoint();
			local DestinationPlayer = {x = PosAlly.x, y = PosAlly.z, z= PosAlly.y + 1500}	

			local Players = coalition.getPlayers(coalition.side.BLUE)	 
			local isPlayerInRange = false
						
			local OriginPlayer = {x = VarPosInicialPlayer.x , y = VarPosInicialPlayer.z , z = land.getHeight({x = VarPosInicialPlayer.x, y = VarPosInicialPlayer.z}) + 500}
			
			for i = 1, #Players do						
				setAirRoute(Players[i]:getGroup(), OriginPlayer, DestinationPlayer, 250)
			end	
			
	--Para todos los aviones mostramos latitud y longitud, para que el jugador lo programe en su navegador	
	local lat, long, alt = coord.LOtoLL(PosAlly)
	local coordSTR = getCoordinatesSTR(lat, long)

	trigger.action.outText("Eco group. " .. nameComboyGroup .. ". Copy following coordinates. Out", 30, true)
	trigger.action.outSoundForCoalition(coalition.side.BLUE, "ECOCopyFollowCoordinatesR.ogg")
	trigger.action.outText(coordSTR.lat .. "     " .. coordSTR.long, 120)	
	trigger.action.outText("Fly heading " .. getBearing(coalition.getPlayers(coalition.side.BLUE)[1]:getPoint(), comboyAllyGroup:getUnit(1):getPoint()) .. "º for " .. math.floor((getDistanceGroups(coalition.getPlayers(coalition.side.BLUE)[1]:getGroup(), comboyAllyGroup)* 0.000539957) + 0.5), 120)	
	trigger.action.outText("INFO: (If you are using a FC3 aircraft, press 1 (Navigation modes key) two times to load " .. nameComboyGroup .. " coordinates into a WP)", 30)	
end;


function loadHostileComboyCoordinates()		
	--Anadimos ruta a los aviones flaming cliff 3
			local PosEnemy = comboyAttackerGroup:getUnit(1):getPoint();
			local DestinationPlayer = {x = PosEnemy.x, y = PosEnemy.z, z= PosEnemy.y}			
			local OriginPlayer = {x = VarPosInicialPlayer.x , y = VarPosInicialPlayer.z , z = land.getHeight({x = VarPosInicialPlayer.x, y = VarPosInicialPlayer.z}) + 500}
			
			local Players = coalition.getPlayers(coalition.side.BLUE)	 
			local isPlayerInRange = false
			for i = 1, #Players do		
				setAirRoute(Players[i]:getGroup(), OriginPlayer, DestinationPlayer, 250)
			end					
			
	--Para todos los aviones mostramos latitud y longitud, para que el jugador lo programe en su navegador	
	local lat, long, alt = coord.LOtoLL(PosEnemy)
	local coordSTR = getCoordinatesSTR(lat, long)
		
	trigger.action.outText("[AREA18 COMMAND]: Alpha group. Command. Copy following coordinates for targets. Out", 30, true)
	trigger.action.outSoundForCoalition(coalition.side.BLUE, "ALPHACommandCopyCoordenatesR.ogg")
	trigger.action.outText(coordSTR.lat .. "     " .. coordSTR.long, 120)	
	trigger.action.outText("Fly heading " .. getBearing(coalition.getPlayers(coalition.side.BLUE)[1]:getPoint(), comboyAttackerGroup:getUnit(1):getPoint()) .. "º for " .. math.floor((getDistanceGroups(coalition.getPlayers(coalition.side.BLUE)[1]:getGroup(), comboyAttackerGroup)* 0.000539957) + 0.5), 120)	
	trigger.action.outText("INFO: (If you are using a FC3 aircraft, press 1 (Navigation modes key) two times to load target coordinates into a WP)", 30)	
end;


function loadCampCoordinates()
	--Añadimos ruta a los aviones flaming cliff 3			
			local PosCamp = CampStaticTarget:getPoint();			
			local DestinationPlayer = {x = PosCamp.x, y = PosCamp.z, z= PosCamp.y}						
			local OriginPlayer = {x = VarPosInicialPlayer.x , y = VarPosInicialPlayer.z , z = land.getHeight({x = VarPosInicialPlayer.x, y = VarPosInicialPlayer.z}) + 500}
			
			local Players = coalition.getPlayers(coalition.side.BLUE)	 
			local isPlayerInRange = false
			for i = 1, #Players do
				--trigger.action.outText("player ".. i, 30, true)			
				setAirRoute(Players[i]:getGroup(), OriginPlayer, DestinationPlayer, 250)
			end				
	
			
	--Para todos los aviones mostramos latitud y longitud, para que el jugador lo programe en su navegador	
	local lat, long, alt = coord.LOtoLL(PosCamp)
	local coordSTR = getCoordinatesSTR(lat, long)

	trigger.action.outText("[AREA18 COMMAND]: Romeo group. Mission Command. Copy following coordinates for Point Tango: ", 30, true)
	trigger.action.outSoundForCoalition(coalition.side.BLUE, "ROMEOCopyFollowingCoordinatesTANGOR.ogg")
	trigger.action.outText(coordSTR.lat .. "     " .. coordSTR.long .. "", 120)
	trigger.action.outText("Fly heading " .. getBearing(coalition.getPlayers(coalition.side.BLUE)[1]:getPoint(), CampStaticTarget:getPoint()) .. "º for " .. math.floor((getDistancePoint(coalition.getPlayers(coalition.side.BLUE)[1]:getGroup(), {x = CampStaticTarget:getPoint().x, y = CampStaticTarget:getPoint().z})* 0.000539957) + 0.5), 120)	
	trigger.action.outText("INFO: (If you are using a FC3 aircraft, press 1 (Navigation modes key) two times to load these coordinates into a WP)", 30)	
end;


function loadPlayerCAP()
	--Añadimos ruta a los aviones flaming cliff 3. Solo se pueden añadir 2 WP por lo que sea.. mas de 2 hace que se cuelgue			
			--trigger.action.outText("loadPlayerCAP ", 120)
			
			PlayerWP1 = {x = 370307.34375, y = 8000 , z = -486100.9375}
			PlayerWP2 = {x = 00321131, y = 8000 , z = -465174}
			
			local Players = coalition.getPlayers(coalition.side.BLUE)	 
			--local isPlayerInRange = false
			for i = 1, #Players do		
				setPlayerCAP(Players[i]:getGroup(), PlayerWP1, PlayerWP2)
			end					
			
--			setPlayerCAP(Group.getByName("A10a_1"), PlayerWP1, PlayerWP2)
--			setPlayerCAP(Group.getByName("A10a_2"), PlayerWP1, PlayerWP2)
--			setPlayerCAP(Group.getByName("SU25T_1"), PlayerWP1, PlayerWP2)
--			setPlayerCAP(Group.getByName("SU25T_2"), PlayerWP1, PlayerWP2)
--			setPlayerCAP(Group.getByName("SU33_1"), PlayerWP1, PlayerWP2)
--			setPlayerCAP(Group.getByName("SU33_2"), PlayerWP1, PlayerWP2)
--			setPlayerCAP(Group.getByName("F15c_1"), PlayerWP1, PlayerWP2)
--			setPlayerCAP(Group.getByName("F15c_2"), PlayerWP1, PlayerWP2)					
			
	--Para todos los aviones mostramos latitud y longitud de cada waypoint, para que el jugador lo programe en su navegador. Ademas mostramos un par de marcas en el mapa.
	
	if isMarkCapAdded == false then
			--trigger.action.outText("Marcas en mapa", 3)
			trigger.action.markToCoalition(1, "Origin CAP point", {x = PlayerWP1.x, y = 0, z = PlayerWP1.z}, coalition.side.BLUE, true, "no message")
			trigger.action.markToCoalition(2, "Destination CAP point", {x = PlayerWP2.x, y = 0, z = PlayerWP2.z}, coalition.side.BLUE, true, "no message")		
			isMarkCapAdded = true
	end		
	
	trigger.action.outText("CAP ROUTE: ", 120, true)
	
	local lat, long, alt = coord.LOtoLL(PlayerWP1)
	local coordSTR1 = getCoordinatesSTR(lat, long)
		trigger.action.outText("   WP1: " .. coordSTR1.lat .. "     " .. coordSTR1.long .. "", 120)
	lat, long, alt = coord.LOtoLL(PlayerWP2)
	local coordSTR2 = getCoordinatesSTR(lat, long)	
		trigger.action.outText("   WP2: " .. coordSTR2.lat .. "     " .. coordSTR2.long .. "", 120)

	trigger.action.outText("INFO: (If you are using a FC3 aircraft, press 1 (Navigation modes key) two times to load CAP route into Waypoints)", 120)	
	trigger.action.outText("TIP: (Marks for CAP Waypoints have been added to the F10 MAP)", 120)	
end;


function setOriginLocalizated(tipoPosicion)
	if tipoPosicion == 1 then
		--ciudades varias
		local rndPos = math.random(1,5) --rndPOS
		if rndPos == 1 then
			VarPosOriginal = {x = 428718.5, z = -326683.6525};
		elseif rndPos == 2 then
			VarPosOriginal = {x = 311702.84375, z = -251513.96875};
		elseif rndPos == 3 then
			VarPosOriginal = {x = 392935.3125, z = -441801.40625};
		elseif rndPos == 4 then
			VarPosOriginal = {x = 303304.96875, z = -355332.71875};
		elseif rndPos == 5 then
			VarPosOriginal = {x = 419999.65625, z = -280631.875};
		end
	elseif tipoPosicion == 2 then
		--FARPs
		local rndPos = math.random(1,3) --rndPOS
		if rndPos == 1 then
			VarPosOriginal = {x = 347915.84375, z = -340735.78125};
		elseif rndPos == 2 then
			VarPosOriginal = {x = 404776.75, z = -395960.75};
		elseif rndPos == 3 then
			VarPosOriginal = {x = 383308.875, z = -310975.125};			
		end
	else
		VarPosOriginal= {x = 323946.71875, z = -333863.96875};
	end
end;


function secureRandomizer(pMax)
	local randomVal = 0
	
	while true do
		randomVal = math.random(1,pMax)
		if not string.match(strRandoms, "_" .. randomVal .. "_") then
			 strRandoms = strRandoms .."_" .. randomVal .. "_"
			 break
		end
	end	
	--trigger.action.outText("random: " .. strRandoms, 20)		
	return randomVal
end


function sayHipsterInitMission()
		
	local message = ""
	
		local rndHipsterMssg1 = math.random(1,4)	
		
			
		if rndHipsterMssg1 == 1 then
			message = message .. "Hi man."
			setSoundDelayed("HIPSTERhi1.ogg", 4)
		elseif rndHipsterMssg1 == 2 then
			message = message .. "Hello there."
			setSoundDelayed("HIPSTERhi2.ogg", 4)
		elseif rndHipsterMssg1 >= 3 then		
			message = message .. "Checking."
			setSoundDelayed("HIPSTERhi3.ogg", 4)		
		end
		
		rndHipsterMssg1 = math.random(1,2)	
		
		if rndHipsterMssg1 == 1 then
			message = message .. " This is Hipster from seat two,"
			setSoundDelayed("HIPSTERthisIs1.ogg", 6)
		elseif rndHipsterMssg1 == 2 then
			message = message .. " Hipster here on seat two,"
			setSoundDelayed("HIPSTERthisIs2.ogg", 6)		
		end
		
		rndHipsterMssg1 = math.random(1,4)	
		
		if rndHipsterMssg1 == 1 then
			message = message .. " I will be with you in this mission."
			setSoundDelayed("HIPSTERthisMission1.ogg", 8)
		elseif rndHipsterMssg1 == 2 then
			message = message .. " We'll fly together today."
			setSoundDelayed("HIPSTERthisMission2.ogg", 8)		
		elseif rndHipsterMssg1 >= 3 then		
			message = message .. " Today I'll be your WSO."
			setSoundDelayed("HIPSTERthisMission3.ogg", 8)
		end
		
		rndHipsterMssg1 = math.random(1,4)	
		
		if rndHipsterMssg1 == 1 then
			message = message .. " Take us to the target and I will do my job. Let's take some nice pictures!"
			setSoundDelayed("HIPSTERPictures1.ogg", 10)
		elseif rndHipsterMssg1 == 2 then
			message = message .. " Ready to go when you are. Hope you have brought the snacks for the picnic, because I have a new camera with a completely unused reel "
			setSoundDelayed("HIPSTERPictures2.ogg", 10)		
		elseif rndHipsterMssg1 >= 3 then		
			message = message .. " Request target coordinates to Command when you are ready, and put this thing in the air. It's time to make good movie of the baddies."
			setSoundDelayed("HIPSTERPictures3.ogg", 10)
		end
		
		setMessageDelayed("[HIPSTER]: " .. message, 20, 4)					

			
end	


function randomGroundChat(nombreUnidad)
	local randomChat = math.random(1, 10)
	if randomChat == 1 then
		trigger.action.outText("[AREA18 COMMAND]: " .. nombreUnidad .. ". Command. We have reports of suspicious activity in the north. Stay alert. Out", 10)
		trigger.action.outSoundForCoalition(coalition.side.BLUE, "COMMANDsuspiciousactivitynorthR.ogg")
	elseif randomChat == 2 then
		trigger.action.outText("[".. string.upper(nombreUnidad) .. "]: Command. " .. nombreUnidad .. ". Nothing to report. Over", 10)
		trigger.action.outSoundForCoalition(coalition.side.BLUE, "COMMANDNothingreportR.ogg")
		setMessageDelayed("[AREA18 COMMAND]: ".. nameComboyGroup .. ". Command. Copy that. Out", 10, 7)
		setSoundDelayed("DELCOMMANDCopythatR.ogg", 7)
	elseif randomChat == 3 then
		trigger.action.outText("[".. string.upper(nombreUnidad) .. "]: Eco. " .. nombreUnidad .. ". AFAWK, this operation can be FUBAR at any moment. Thanks for the assistant. Over", 10)
		trigger.action.outSoundForCoalition(coalition.side.BLUE, "ECOFubarR.ogg")
	elseif randomChat == 4 then
		trigger.action.outText("[".. string.upper(nombreUnidad) .. "]: Command. " .. nombreUnidad .. ". Situation seems quiet, so far so good. Over", 10)
		trigger.action.outSoundForCoalition(coalition.side.BLUE, "COMMANDSituationseemsquiet_R.ogg")
		setMessageDelayed("[AREA18 COMMAND]: " .. nameComboyGroup .. ". Command. Copy that. Out", 10, 7)
		setSoundDelayed("DELCOMMANDCopythatR.ogg", 7)
	elseif randomChat == 5 then
		trigger.action.outText("[".. string.upper(nombreUnidad) .. "]: Command. " .. nombreUnidad .. ". Maintaining radio silent for a couple of minutes. Out", 10)
		trigger.action.outSoundForCoalition(coalition.side.BLUE, "COMMANDMaintainingradiosilentR.ogg")
	elseif randomChat == 6 then
		trigger.action.outText("[".. string.upper(nombreUnidad) .. "]: Command. " .. nombreUnidad .. ". Request SITREP. Over", 10)
		trigger.action.outSoundForCoalition(coalition.side.BLUE, "COMMANDRequestSITREPR.ogg")
		setMessageDelayed("[AREA18 COMMAND]: " .. nameComboyGroup .. ". Command. All clear. Out", 10, 7)
		setSoundDelayed("DELCOMMANDAllclearR.ogg", 7)
	elseif randomChat == 7 then
		trigger.action.outText("[".. string.upper(nombreUnidad) .. "]: Eco. " .. nombreUnidad .. ". We have to slow down for a minute. Out ", 10)
		trigger.action.outSoundForCoalition(coalition.side.BLUE, "ECOslowdownR.ogg")
	elseif randomChat == 8 then
		trigger.action.outText("[".. string.upper(nombreUnidad) .. "]: Command. " .. nombreUnidad .. ". Passing next waypoint. Out", 10)
		trigger.action.outSoundForCoalition(coalition.side.BLUE, "COMMANDPassingnextwaypointR.ogg")
	elseif randomChat == 9 then
		trigger.action.outText("[".. string.upper(nombreUnidad) .. "]: Command. " .. nombreUnidad .. ". Request confirmation of destination coordinates through datalink. Out", 10)
		trigger.action.outSoundForCoalition(coalition.side.BLUE, "COMMANDRequestconfirmationdestinationR.ogg")
	elseif randomChat == 10 then
		trigger.action.outText("[".. string.upper(nombreUnidad) .. "]: Eco " .. nombreUnidad .. " is speeding up now. Out", 10)
		trigger.action.outSoundForCoalition(coalition.side.BLUE, "ECOWespeedingupR.ogg")
	end
end


function setTaxiRadioMessages1()
	
	local rndTaxiMssg1 = math.random(1,5)
	
	if rndTaxiMssg1 == 1 then
		setMessageDelayed("[GROUND CREW]: Standard payload loaded. Fuel 100%. The aircraft is ready to go. Over ", 10, 19, false)
		setSoundDelayed("TAXIgroundteam1.ogg", 19)
	elseif rndTaxiMssg1 == 2 then
		setMessageDelayed("[GROUND CREW]: Captain. Standard payload have been loaded. If you need to change the payload before takeoff, contact us. Over ", 10, 17, false)
		setSoundDelayed("TAXIgroundteam2.ogg", 17)
	elseif rndTaxiMssg1 == 3 then
		setMessageDelayed("[GROUND CREW]: Start sequence has been complete. Armament is ready to go. Over ", 10, 15, false)
		setSoundDelayed("TAXIgroundteam3.ogg", 15)
	elseif rndTaxiMssg1 == 4 then
		setMessageDelayed("[AREA18 ATC]: You are cleared to start your mission. Contact Shiraz ATC before taxi. Over ", 10, 17, false)
		setSoundDelayed("TAXIatc1.ogg", 17)
	elseif rndTaxiMssg1 == 5 then
		setMessageDelayed("[AREA18 ATC]: This is AREA18 ATC. You are cleared. Godspeed. Over", 10, 15, false)
		setSoundDelayed("TAXIatc2.ogg", 15)		
	end
end	


function setTaxiRadioMessages2()	
	-- la segunda comunicacion depende de la mission
	local rndTaxiMssg2 = math.random(1,4)
	--trigger.action.outText("rndTaxiMssg2: ".. rndTaxiMssg2, 10)	
	--trigger.action.outText("missionType: ".. missionType, 10)	
	--trigger.action.outText("missionSubType: ".. missionSubType, 10)	
	
	if missionType == 1 and (missionSubType == 1 or missionSubType == 2) then	
		if rndTaxiMssg2 == 1 then
			setMessageDelayed("[AREA18 ATC]: India Group. AREA18 ATC. We have a large group of hostiles in our screens heading for Shiraz. Take off ASAP, climb to max altitude and intercept them. Over", 15, 60, false)
			setSoundDelayed("TAXIRUNatc_1.ogg", 60)
		elseif rndTaxiMssg2 == 2 then
			setMessageDelayed("[AREA18 ATC]: India Group. AREA18 ATC. Intercept the hostile group from high altitude. Request support once you are in the engagement area if you need it. Over ", 15, 60, false)
			setSoundDelayed("TAXIRUNatc_2.ogg", 60)
		elseif rndTaxiMssg2 == 3 then
			setMessageDelayed("[BRAVO]: India group. Bravo 2-1. We are in route to Shiraz. Call us once you are near the hostiles and we will support you. Over", 15, 60, false)
			setSoundDelayed("TAXIRUNbravo1.ogg", 60)
		end
	elseif missionType == 1 and missionSubType == 5 then
		if rndTaxiMssg2 == 1 then
			setMessageDelayed("[AREA18 COMMAND]: India Group. AREA18 Command. The bogie seems to be some king of large aircraft. Weapons cold until furher orders, but trust nothing and engage with caution. Over ", 15, 60, false)
			setSoundDelayed("TAXIRUNatc_3.ogg", 60)
		elseif rndTaxiMssg2 == 2 then
			setMessageDelayed("[AREA18 COMMAND]: India Group. AREA18 Command. ROE are weapons cold until the bogie has been identified as hostile. Contact overlord for heading to target. Over ", 15, 60, false)
			setSoundDelayed("TAXIRUNatc_4.ogg", 60)
		elseif rndTaxiMssg2 == 3 then
			setMessageDelayed("[AREA18 COMMAND]: India Group. AREA18 Command. Climb to high altitude and stay in contact with Overlord. Remember: weapons cold. Over ", 15, 60, false)
			setSoundDelayed("TAXIRUNatc_5.ogg", 60)
		end		
	elseif (missionType == 2 and (missionSubType == 2 or missionSubType == 3 or missionSubType == 4)) 
			or (missionType == 3 and (missionSubType == 2 or missionSubType == 3)) then	
		if rndTaxiMssg2 == 1 then
			setMessageDelayed("[AREA18 COMMAND]: This is AREA18 Command. You are ordered to take off and head for the target campament area. Take into account that SAM threats could be present in the AO. Over", 15, 60, false)
			setSoundDelayed("TAXIRUNatc_6.ogg", 60)
		elseif rndTaxiMssg2 == 2 then
			setMessageDelayed("[AREA18 COMMAND]: This is AREA18 Command. Proceed with your mission and try to return in one piece. If you find hostiles protecting the AO, request SWEEP mission or engage by yourself. Over ", 15, 60, false)
			setSoundDelayed("TAXIRUNatc_7.ogg", 60)
		elseif rndTaxiMssg2 == 3 then
			setMessageDelayed("[AREA18 COMMAND]: This is AREA18 Command. Beware of possible SAM defences or CAPs in the area. Do not engage defences by yourself is is not necessary, we need all our pilots. Over", 15, 60, false)
			setSoundDelayed("TAXIRUNatc_8.ogg", 60)
		end
	elseif (missionType == 2 or missionType == 3) and missionSubType == 1 then
		if rndTaxiMssg2 == 1 then
			setMessageDelayed("[AREA18 COMMAND]: Eco group. AREA18 Command. You are ordered to take off and head for the rendevouz point. Provide CAS during their route. Over", 15, 60, false)
			setSoundDelayed("TAXIRUNatc_9.ogg", 60)
		elseif rndTaxiMssg2 == 2 then
			setMessageDelayed("[AREA18 COMMAND]: Eco group. AREA18 Command. Proceed to rendevouz with the comboy and escort them through enemy territory. Over ", 15, 60, false)
			setSoundDelayed("TAXIRUNatc_10.ogg", 60)
		elseif rndTaxiMssg2 == 3 then
			setMessageDelayed("[AREA18 COMMAND]: Eco group. AREA18 Command. The comboy is waiting for you at the given coordinates. It is an important asset, protect them at all cost. Over.", 15, 60, false)
			setSoundDelayed("TAXIRUNatc_11.ogg", 60)
		end
	elseif missionType == 3 and missionSubType == 4 then
		if rndTaxiMssg2 == 1 then
			setMessageDelayed("[AREA18 COMMAND]: Alpha group. AREA18 Command. You are ordered to take off and intercept an enemy comboy near the given coordinates. Over", 15, 60, false)
			setSoundDelayed("TAXIRUNatc_12.ogg", 60)
		elseif rndTaxiMssg2 == 2 then
			setMessageDelayed("[AREA18 COMMAND]: Alpha group. AREA18 Command. You are cleared to engage at sight. Destroy all enemy units and return to base. Over ", 15, 60, false)
			setSoundDelayed("TAXIRUNatc_13.ogg", 60)
		elseif rndTaxiMssg2 == 3 then
			setMessageDelayed("[AREA18 COMMAND]: Alpha group. AREA18 Command. Take into account that other threats could be present in the AO. Proceed with caution. Over ", 15, 60, false)
			setSoundDelayed("TAXIRUNatc_14.ogg", 60)
		end
		
	end
	
	
	
	
end


function setTaxiMusic(allPlayersHaveRadio)
	--trigger.action.outText("setTaxiMusic", 10)
	local relSong = math.random(1,6)
	if	allPlayersHaveRadio then
		if relSong == 1 then			
			setMusic({pfile = 'l10n/DEFAULT/MusicRel1.ogg', pdelayNextSec = 145, pallPlayersHaveRadio = allPlayersHaveRadio})
		elseif relSong == 2 then
			setMusic({pfile = 'l10n/DEFAULT/MusicRel2.ogg', pdelayNextSec = 210, pallPlayersHaveRadio = allPlayersHaveRadio})			
		elseif relSong == 3 then	 
			setMusic({pfile = 'l10n/DEFAULT/MusicRel3.ogg', pdelayNextSec = 165, pallPlayersHaveRadio = allPlayersHaveRadio})			
		elseif relSong == 4 then	 
			setMusic({pfile = 'l10n/DEFAULT/MusicRel4.ogg', pdelayNextSec = 115, pallPlayersHaveRadio = allPlayersHaveRadio})			
		elseif relSong == 5 then	 
			setMusic({pfile = 'l10n/DEFAULT/MusicRel5.ogg', pdelayNextSec = 225, pallPlayersHaveRadio = allPlayersHaveRadio})			
		elseif relSong == 6 then	 
			setMusic({pfile = 'l10n/DEFAULT/MusicRel6.ogg', pdelayNextSec = 215, pallPlayersHaveRadio = allPlayersHaveRadio})			
		end 
	else
		if relSong == 1 then
			setMusic({pfile = 'MusicRel1.ogg', pdelayNextSec = 145, pallPlayersHaveRadio = allPlayersHaveRadio})
		elseif relSong == 2 then
			setMusic({pfile = 'MusicRel2.ogg', pdelayNextSec = 210, pallPlayersHaveRadio = allPlayersHaveRadio})		
		elseif relSong == 3 then	 
			setMusic({pfile = 'MusicRel3.ogg', pdelayNextSec = 165, pallPlayersHaveRadio = allPlayersHaveRadio})		
		elseif relSong == 4 then	 
			setMusic({pfile = 'MusicRel4.ogg', pdelayNextSec = 115, pallPlayersHaveRadio = allPlayersHaveRadio})		
		elseif relSong == 5 then	 
			setMusic({pfile = 'MusicRel5.ogg', pdelayNextSec = 225, pallPlayersHaveRadio = allPlayersHaveRadio})		
		elseif relSong == 6 then	 
			setMusic({pfile = 'MusicRel6.ogg', pdelayNextSec = 215, pallPlayersHaveRadio = allPlayersHaveRadio})		
		end 
	end
	 
end 


function setTaxiMusicDark(allPlayersHaveRadio)
	--trigger.action.outText("setTaxiMusicDark", 10)
	local darkSong = math.random(1,3)
	if	allPlayersHaveRadio then
		if darkSong == 1 then
			setMusic({pfile = 'l10n/DEFAULT/MusicDark1.ogg', pdelayNextSec = 170, pallPlayersHaveRadio = allPlayersHaveRadio})			
		elseif darkSong == 2 then
			setMusic({pfile = 'l10n/DEFAULT/MusicDark2.ogg', pdelayNextSec = 110, pallPlayersHaveRadio = allPlayersHaveRadio})			
		elseif darkSong == 3 then
			setMusic({pfile = 'l10n/DEFAULT/MusicDark3.ogg', pdelayNextSec = 130, pallPlayersHaveRadio = allPlayersHaveRadio})
			
		end 
	else
		if darkSong == 1 then
			setMusic({pfile = 'MusicDark1.ogg', pdelayNextSec = 170, pallPlayersHaveRadio = allPlayersHaveRadio})
		elseif darkSong == 2 then
			setMusic({pfile = 'MusicDark2.ogg', pdelayNextSec = 110, pallPlayersHaveRadio = allPlayersHaveRadio})			
		elseif darkSong == 3 then	
			setMusic({pfile = 'MusicDark3.ogg', pdelayNextSec = 130, pallPlayersHaveRadio = allPlayersHaveRadio})						
		end 
	end	 
end 


function setMusic(parameters)
	--trigger.action.outText("setMusic", 10)
	--local p = coalition.getPlayers(coalition.side.BLUE)[1]:getPoint() --Por alguna razon no funciona con los FC3, asiq eu tengo que transmitir desde shiraz
	
	local p = trigger.misc.getZone('Shiraz Airport').point		
			
	if continueMusic then
		if parameters.pallPlayersHaveRadio then
			trigger.action.radioTransmission(parameters.pfile, p, 0, false, 127500000, 5, "taxi2")
			trigger.action.radioTransmission(parameters.pfile, p, 0, false, 250350000, 5, "taxi")
			--trigger.action.radioTransmission(parameters.pfile, p, 0, parameters.ploop, 121900000, 5, "taxi")	
		else
			trigger.action.outSoundForCoalition(coalition.side.BLUE, parameters.pfile)		
		end
		
		timer.scheduleFunction(setMusic, {pfile = parameters.pfile, pdelayNextSec = parameters.pdelayNextSec, pallPlayersHaveRadio = parameters.pallPlayersHaveRadio}, timer.getTime() + parameters.pdelayNextSec)
	else
		isPlayingMusic = false
	end
	
end


function stopTaxiMusic()
	--trigger.action.outText("para la musica la proxima vez", 10)					
	continueMusic = false
end


function setFlagDelayed(parameters)
	trigger.action.setUserFlag(parameters.pflag, parameters.pvalue)
end


function setRandomTakeof()

	if math.random(1,3) == 1 then
		Group.getByName("randomtakeof1"):activate()
		setRemoveGroupDelayed("randomtakeof1", 600)
	end
		
	if math.random(1,3) == 1 then
		Group.getByName("randomtakeof2"):activate()
		setRemoveGroupDelayed("randomtakeof2", 600)
	end
		
	if math.random(1,3) == 1 then
		Group.getByName("randomtakeof3"):activate()
		setRemoveGroupDelayed("randomtakeof3", 600)
	end
		
	if math.random(1,3) == 1 then
		Group.getByName("randomtakeof4"):activate()
		setDelayedStartGroup("randomtakeof4", 90)
		setRemoveGroupDelayed("randomtakeof4", 600)
	end
		
	if math.random(1,3) == 1 then
		Group.getByName("randomtakeof5"):activate()
		setRemoveGroupDelayed("randomtakeof5", 600)
	end
		
	if math.random(1,3) == 1 then
		Group.getByName("randomtakeof6"):activate()
		setRemoveGroupDelayed("randomtakeof6", 600)
	end
		
	if math.random(1,3) == 1 then
		Group.getByName("randomtakeof7"):activate()
		setRemoveGroupDelayed("randomtakeof7", 600)
	end
		
	if math.random(1,3) == 1 then
		Group.getByName("randomtakeof8"):activate()
		setRemoveGroupDelayed("randomtakeof8", 600)
	end
		
	if math.random(1,3) == 1 then
		Group.getByName("randomtakeof9"):activate()
		setRemoveGroupDelayed("randomtakeof9", 600)
	end
		
	if math.random(1,3) == 1 then
		Group.getByName("randomtakeof10"):activate()
		setRemoveGroupDelayed("randomtakeof10", 600)
	end
		
	if math.random(1,3) == 1 then
		Group.getByName("randomtakeof11"):activate()
		setRemoveGroupDelayed("randomtakeof11", 600)
	end
		
	if math.random(1,3) == 1 then
		Group.getByName("randomtakeof12"):activate()
		setRemoveGroupDelayed("randomtakeof12", 600)
	end
		
	if math.random(1,3) == 1 then
		Group.getByName("randomtakeof13"):activate()
		setRemoveGroupDelayed("randomtakeof13", 600)
	end
		
	if math.random(1,3) == 1 then
		Group.getByName("randomtakeof14"):activate()
		setRemoveGroupDelayed("randomtakeof14", 600)
	end
	
	if math.random(1,3) == 1 then
		Group.getByName("randomtakeof15"):activate()
		setDelayedStartGroup("randomtakeof15", 60)
		setRemoveGroupDelayed("randomtakeof15", 600)
	end
	
	if math.random(1,3) == 1 then
		Group.getByName("randomtakeof16"):activate()
		setDelayedStartGroup("randomtakeof16", 120)
		setRemoveGroupDelayed("randomtakeof16", 600)
	end
	  
end


function setDelayedStartGroup(groupName, delaySec)
	timer.scheduleFunction(startGroup, {pgroupName = groupName}, timer.getTime() + delaySec)	
end


function startGroup(parameters)
	Start = { 
				  id = 'Start', 
				  params = { 
				  } 
				}
				
	Group.getByName(parameters.pgroupName):getController():setCommand(Start)
end


function setMessageDelayed(text, duration, delaySec, clear)
	if clear == nil or clear == false then
        clear = false
	else
		clear = true
    end
	timer.scheduleFunction(showMessage, {ptext = text, pduration = duration, pclear = clear}, timer.getTime() + delaySec)
end


function setSoundDelayed(sound, delaySec)
	timer.scheduleFunction(playSound, {psound = sound}, timer.getTime() + delaySec)
end


function showMessage(parameters)	
	trigger.action.outText(parameters.ptext, parameters.pduration, parameters.pclear)		
end


function playSound(parameters)
	trigger.action.outSoundForCoalition(coalition.side.BLUE, parameters.psound)		
end


function setRemoveGroupDelayed(pGroupName, delaySec)
	timer.scheduleFunction(RemoveGroup, {pGroupRemove = pGroupName}, timer.getTime() + delaySec)
end


function RemoveGroup(parameters)
	if parameters.pGroupRemove ~= nil and Group.getByName(parameters.pGroupRemove) ~= nil then
		Group.getByName(parameters.pGroupRemove):destroy()
	end
end


function setRemoveNeutralDelayed(pGroup, delaySec)
	timer.scheduleFunction(RemoveNeutral, pGroup, timer.getTime() + delaySec)
end


function RemoveNeutral(pGroup)		
	isEnemyComboyCreated = false
	isRandomInProgress = false		
	strRandoms = ""	
	pGroup:destroy()
end
 

function RequestBackUp()
	setMessageDelayed("[".. string.upper(nameComboyGroup) .. "]: Eco group. " .. nameComboyGroup .. ". Backup escort is on the way, you can RTB. Thanks for your assistance!", 20, 5)
	setSoundDelayed("DELECOBackupescortonwayR.ogg", 5)
	isMissionEnded = true	
	setRemoveGroupDelayed(comboyAllyGroup:getName(), 60)
end;


function identifyUnknown()	

	local Players = coalition.getPlayers(coalition.side.BLUE)	 
	local isPlayerInRange = false
	for i = 1, #Players do		
		if getDistanceGroups(Players[i]:getGroup(), comboyAttackerGroup) <= 3000  then
			isPlayerInRange = true
		end
	end	
		
	if isPlayerInRange	
	then	
		local randomVal = math.random(1,2) --rndEVENT
		if randomVal == 1 then
			local PosNeutral = comboyAttackerGroup:getUnit(1):getPoint();		
			setMessageDelayed("[".. string.upper(nameComboyGroup) .. "]: Eco group. " .. nameComboyGroup .. ". Unknown vehicles identified as hostile. Cleared to engage. Repeat... Targets are hostile, you are cleared to engage. Over", 20, 5)	
			setSoundDelayed("DELECOUnknownvehiclesidentifiedhostileR.ogg", 5)
			if missionType == 3 then -- si es mission de helicoptero lo creamos mas flojo
				comboyAttackerGroup = createComboyAttackers({x = PosNeutral.x, y = PosNeutral.z}, true, 7)
			else
				comboyAttackerGroup = createComboyAttackers({x = PosNeutral.x, y = PosNeutral.z}, true, 3)
			end
			
			setRouteComboyAttackers(true)
			
		else		
			setMessageDelayed("[".. string.upper(nameComboyGroup) .. "]: Eco group. " .. nameComboyGroup .. ". Unknown vehicles identified as NOT hostile. Repeat... vehicles are civilian transports, you are ordered to withdraw. Proceedeng with route. Out.", 20, 5)
			setSoundDelayed("DELECOUnknownvehiclesidentifiedNOThostileR.ogg", 5)
			resetRouteAllyComboy()
			menuReqStop = missionCommands.addCommand('Stop comboy', menuPrinc2, requestStopComboy, nil)
			menuReqCont = missionCommands.addCommand('Continue route', menuPrinc2, requestContinueComboy, nil)
			setRemoveNeutralDelayed(comboyAttackerGroup, 10)
		end
		
		missionCommands.removeItem(menuIdentifyUnknown)	
	else
		trigger.action.outText("INFO: (You are to far away from the unknown comboy to identify them) ", 10)        	
		trigger.action.outSoundForCoalition(coalition.side.BLUE, "Beep.wav")
	end
end;


function interceptCivilAircraft()	
	--trigger.action.outText("interceptCivilAircraft", 10)        	
	local Players = coalition.getPlayers(coalition.side.BLUE)	 
	local isPlayerInRange = false
	for i = 1, #Players do		
		if getDistanceGroups(Players[i]:getGroup(), civilAirGroup) <= 150  then
			isPlayerInRange = true
		end
		--trigger.action.outText("distance: " .. getDistanceGroups(Players[i]:getGroup(), civilAirGroup), 10) 
	end	
		
	if isPlayerInRange	then	
		isCivilIntercepted = true
		setMessageDelayed("[JA0891 FLIGHT]: Interceptor aircraft, do not fire. We are not hostile. This is civil aircraft JA0891 carrying passengers with destination Kerman airport. We have problems with the communication and navigation systems and we need help to get to our destination. Could you assist us?. Out", 20, 5, true)		
		setSoundDelayed("CIVILdonotfireR.ogg", 5)
		
		missionCommands.removeItem(menuOtherInterceptCiv)	
		menuOtherTransmitCommand = missionCommands.addCommand('Transmit aircraft ID and situation to command', menuPrinc3, transmitCivilAirStatus, nil)					
	else
		trigger.action.outText("INFO: (You are to far away from the civil aircraft to intercept them) ", 10)        	
		trigger.action.outSoundForCoalition(coalition.side.BLUE, "Beep.wav")
	end
end;


function transmitCivilAirStatus()
	missionCommands.removeItem(menuOtherTransmitCommand)
	trigger.action.outText("INFO: (wait until command check flight ID) ", 10, true)        	
	trigger.action.outSoundForCoalition(coalition.side.BLUE, "Beep.wav")
	setMessageDelayed("[AREA18 COMMAND]: India-25, Command. The flight ID, origin and destination have been confirmed. Escort them out of our airspace, but do not approach Kerman Airport more than 80 miles to avoid entering enemy airspace. Over.", 20, 20, true)
	setMessageDelayed("TIP: (use F10 radio menu to give new orders to JA0891)", 20, 20, false)
	setSoundDelayed("COMMANDCivilIDR.ogg", 20)
	
	menuOtherTransmitCivilFollow = missionCommands.addCommand('Order Civil aircraft follow you', menuPrinc3, transmitCivilFollow, nil)					
	
end;


function transmitCivilFollow()
	missionCommands.removeItem(menuOtherTransmitCivilFollow)	
	timer.scheduleFunction(setNewRouteCivilAircraft, nil, timer.getTime() + 5)	
end


function destroyCivilAircraft()
	Group.getByName(nameCivilAirGroup):destroy()	
	-- si los interceptores persas no son hostiles, desaparecen tambien.
	if Group.getByName(nameHostileAirGroup) ~= nil and ROECivilEscortInterceptors == "NOTHOSTILE" then
		Group.getByName(nameHostileAirGroupExtra):destroy()
	end	
	
	if Group.getByName(nameHostileAirGroupExtra) ~= nil and ROECivilEscortInterceptors == "NOTHOSTILE" then
		Group.getByName(nameHostileAirGroupExtra):destroy()
	end	
end


function setNewRouteCivilAircraft()
	trigger.action.outText("[JA0891 FLIGHT]: JA0891. Understood, we will follow you. Thanks for your help. Out.", 15, true)
	trigger.action.outSoundForCoalition(coalition.side.BLUE, "CIVILfollowyouR.ogg")
	
	local airCivil = Group.getByName(nameCivilAirGroup)	
	setAirRoute(airCivil, {x = airCivil:getUnit(1):getPoint().x, y = airCivil:getUnit(1):getPoint().z, z = airCivil:getUnit(1):getPoint().y}, {x = 456191 , z = 6000, y = -42463}, 250)	
end;


function createCivilEscortInterceptors()

	hostileAirGroup = createHostilesAirGroup({x = 456191, y = -60463}, 1000, 7000, nil)
	isCivilEscortInterceptorsCreated = true;
	
	hostileAttackPlayer(hostileAirGroup)
	hostileAirGroup:getController():setOption(AI.Option.Air.id.ROE, AI.Option.Air.val.ROE.WEAPON_FREE)		
	
	if getNumberOfPlayers() >= 4 then
		local mainGroupPos = hostileAirGroup:getUnit(1):getPoint()
		hostileAirGroupExtra = createHostilesAirGroupExtra({x = mainGroupPos.x, y = mainGroupPos.z}, 1000, 8000)
		isCivilEscortInterceptorsExtraCreated = true;
		hostileAttackPlayer(hostileAirGroupExtra)
		hostileAirGroupExtra:getController():setOption(AI.Option.Air.id.ROE, AI.Option.Air.val.ROE.WEAPON_FREE)		
	end

end;


function setROECivilEscortInterceptors()
	local rand = math.random(1,5)
	--trigger.action.outText("rand: " .. rand, 15, true)
	if rand == 1 or rand == 3 or rand == 4  then
		hostileAirGroup:getController():setOption(AI.Option.Air.id.ROE, AI.Option.Air.val.ROE.WEAPON_HOLD)		
		if isHostilesAirGroupExtraCreated then
			hostileAirGroupExtra:getController():setOption(AI.Option.Air.id.ROE, AI.Option.Air.val.ROE.WEAPON_HOLD)		
		end
		
		setMessageDelayed("[UNKNOWN]: Trespasser  aircraft. Hunter 1-5. You must leave the Persian Empire airspace at once. We will escort JA0891 from now on. Out", 15, 5, true)					
		setSoundDelayed("TRESPASSLeavePersianAirspaceR.ogg", 5)
		
		ROECivilEscortInterceptors =  "NOTHOSTILE"
		
	else
		setMessageDelayed("[UNKNOWN]: Trespasser aircraft. Hunter 1-5. Persian Empire doesn't care about your pathetic excuses. You have invaded our sovereign airspace and we will take your live for it. Out", 15, 5, true)			
		setSoundDelayed("TRESPASSPersianDoesntCareR.ogg", 5)	
		
		ROECivilEscortInterceptors =  "HOSTILE"
		
		setMessageDelayed("[AREA18 COMMAND]: India-25. Command. Seems that the 'Glorious Empire' wants some action. Leave your mission and RTB or destroy attackers. It is up to you. Over", 15, 20, true)		
		setMessageDelayed("INFO:(Return to base or destroy the enemy)", 15, 20, false)		
		
		setSoundDelayed("COMMANDGloriousEmpireActionR.ogg", 20)	
	end
	
	missionCommands.removeItem(menuExplainMission)	
end;


function loadCombatDropCoordinates()
	--Añadimos ruta a los aviones flaming cliff 3
	--trigger.action.outText("loadCombatDropCoordinates " .. nameAllyTroopsGroup, 30, true)	
	local PosAlly = Group.getByName(nameAllyTroopsGroup):getUnit(1):getPoint();
		
	local DestinationPlayer = {x = PosAlly.x, y = PosAlly.z, z= PosAlly.y + 1500}	

	local Players = coalition.getPlayers(coalition.side.BLUE)	 	
				
	local OriginPlayer = {x = VarPosInicialPlayer.x , y = VarPosInicialPlayer.z , z = land.getHeight({x = VarPosInicialPlayer.x, y = VarPosInicialPlayer.z}) + 500}
	
	for i = 1, #Players do						
		setAirRoute(Players[i]:getGroup(), OriginPlayer, DestinationPlayer, 250)
	end	
			
	--Para todos los aviones mostramos latitud y longitud, para que el jugador lo programe en su navegador	
	local lat, long, alt = coord.LOtoLL(PosAlly)
	local coordSTR = getCoordinatesSTR(lat, long)

	trigger.action.outText("[GROUND TROOPS]: Eco group. Copy following coordinates. Out", 30, true)
	trigger.action.outSoundForCoalition(coalition.side.BLUE, "ECOCopyFollowCoordinatesR.ogg")
	trigger.action.outText(coordSTR.lat .. "     " .. coordSTR.long, 120)
	trigger.action.outText("Fly heading " .. getBearing(coalition.getPlayers(coalition.side.BLUE)[1]:getPoint(), Group.getByName(nameAllyTroopsGroup):getUnit(1):getPoint()) .. "º for " .. math.floor((getDistanceGroups(coalition.getPlayers(coalition.side.BLUE)[1]:getGroup(), Group.getByName(nameAllyTroopsGroup))* 0.000539957) + 0.5), 120)	

end;


function markDropZoneSmoke()
	--trigger.action.outText("markDropZoneSmoke " .. nameAllyTroopsGroup, 30, true)	
	trigger.action.smoke(Group.getByName(nameAllyTroopsGroup):getUnit(1):getPoint(), trigger.smokeColor.Green)	
	setMessageDelayed("[GROUND TROOPS]: Eco Group. Our position is marked with green smoke. Deliver your cargo near us, please. Over", 10, 5, true) 
	setSoundDelayed("ECODropZoneMarkedR.ogg", 5)
end;


function getNumberOfPlayers()
	local numero = #coalition.getPlayers(coalition.side.BLUE)	
	return numero		
end;


function activateTankers()
	Group.getByName("tanker1"):activate()
	Group.getByName("tanker2"):activate()
	setMessageDelayed("[AREA18 COMMAND]: Command. Tankers are now in the operation area. Contact them through assigned radio frequencies. Out", 10, 2)					
	setSoundDelayed("DELCOMMANDTankersInOperationAreaR.ogg", 8)
	
	setMessageDelayed("Ally tankers IBCs cost: 5000" , 10, 4)
	SaveInFile("financings.lua", "\n AccountingBalance = AccountingBalance - 5000 -- Request tankers", false)									
	AccountingBalance = AccountingBalance - 5000					
end


function requestTankers()
	timer.scheduleFunction(activateTankers, nil, timer.getTime() + 120 + math.random(-30, 30))	
	setMessageDelayed("[AREA18 COMMAND]: Roger that. Tankers are heading to operation area. ETA 2 minutes. Out", 10, 2)					
	setSoundDelayed("DELCOMMANDTankersHeadingR.ogg", 2)
	missionCommands.removeItem(menuReqTanker)
end


function requestCAPbackUp()
	setMessageDelayed("[AREA18 COMMAND]: Command. Roger. Bravo will relieve you during AAR. Proceed to WP1 and transmit reasuming CAP once you finish with the tanker. Out", 30, 2)					
	setMessageDelayed("[TIP]: Use F10 radio menu to reasume your CAP when ready", 30, 2)					
	setSoundDelayed("COMMANDBravoRelieveCAP.ogg", 2)
	missionCommands.removeItem(menuReqAAR)
	menuReqResumeCAP = missionCommands.addCommand('Reasuming CAP', menuPrinc1, requestReasumingCAP, nil)
	isPlayerRefueling = true
end


function requestReasumingCAP()
	setMessageDelayed("[AREA18 COMMAND]: Command. Copy. Out", 10, 2)					
	setSoundDelayed("COMMANDCopy.ogg", 2)
	missionCommands.removeItem(menuReqResumeCAP)
	menuReqAAR = missionCommands.addCommand('Request backup for AAR', menuPrinc1, requestCAPbackUp, nil)
	isPlayerRefueling = false
end


function reconComplete()

	if string.match(getPlayersTypes():gsub("%-", "_"), "MB_339PAN" .. ";" ) or
		string.match(getPlayersTypes():gsub("%-", "_"), "T_45" .. ";" )then	
		setMessageDelayed("[HIPSTER]: Ok, I believe it is enough. I've got the images from the target. Let's return home and get some beers, pal. ", 15, 2)					
		setSoundDelayed("HIPSTERReconComplete.ogg", 2)	
	end


	setMessageDelayed("Mission accomplished. The area has been recorded. You can RTB.", 60, 15, true)				
	setSoundDelayed("MAareahasbeenrecordedR.ogg", 15)		
	isMissionEnded = true
	isMissionWin = true;
	SaveInFile("financings.lua", "\n AccountingBalance = AccountingBalance + 10000 -- Mission Acomplished ", false)	

end


function setChecker1(pWait)
	
	if timer1 == pWait then   
		timer1 = 0;
		return true;
	else
		timer1 = timer1 + 1;   
		return false;
	end;
end;


function doChecker1()
	--Missions accomplished
		--escolta comboy  (Helo1 or aircraft1)
	if ((missionType == 2 and missionSubType == 1) or (missionType == 3 and missionSubType == 1)) and isMissionEnded == false and comboyAllyGroup ~= nil and allyGroupSave(comboyAllyGroup, destinationComboy) then			
		trigger.action.outText("Mission accomplished. The comboy has reached its destiny. You can RTB.", 60)				
		trigger.action.outSoundForCoalition(coalition.side.BLUE, "MAcomboyReachedDestinyR.ogg")		
		isMissionEnded = true
		isMissionWin = true;
		SaveInFile("financings.lua", "\n AccountingBalance = AccountingBalance + 25000 -- Mission Acomplished ", false)		
	end
		
		
		--trigger.action.outText("missionType: " .. missionType .. "; missionSubType: " .. missionSubType .. "; isMissionEnded: " .. tostring(isMissionEnded) .. "; isEnemyCampCreated: " .. tostring(isEnemyCampCreated) , 20)		
		--if CampStaticTarget == nil then
		--	trigger.action.outText("CampStaticTarget: nulo " .. CampStaticTarget:getLife(), 10)
		--else
		--	trigger.action.outText("CampStaticTarget: no nulo" .. CampStaticTarget:getLife(), 10)
		--end
	--attack enemy campament (aircraft2)
	if missionType == 2 and missionSubType == 2 and isMissionEnded == false and isEnemyCampCreated and (CampStaticTarget == nil or CampStaticTarget:getLife() == 0)then			
		trigger.action.outText("Mission accomplished. The target has been destroyed. You can RTB.", 60)
		trigger.action.outSoundForCoalition(coalition.side.BLUE, "MAtargethasbeendestroyedR.ogg")		
		isMissionEnded = true
		isMissionWin = true;
		SaveInFile("financings.lua", "\n AccountingBalance = AccountingBalance + 25000 -- Mission Acomplished ", false)		
	end
	
	--attack enemy campament SAMs (Helo2 or aircraft3)
	if ((missionType == 2 and missionSubType == 3) or (missionType == 3 and missionSubType == 2)) and isMissionEnded == false and isEnemyCampCreated and (CampSAMTarget == nil or isGroupDestroyed(CampSAMTarget))then			
		trigger.action.outText("Mission accomplished. The target has been destroyed. You can RTB.", 60)				
		trigger.action.outSoundForCoalition(coalition.side.BLUE, "MAtargethasbeendestroyedR.ogg")		
		isMissionEnded = true
		isMissionWin = true;
		SaveInFile("financings.lua", "\n AccountingBalance = AccountingBalance + 25000 -- Mission Acomplished ", false)		
	end
	
	-- recon enemy campament. aircraft4
	if missionType == 2 and missionSubType == 4 and isMissionEnded == false and isEnemyCampCreated and isCampRecon and isNotReconInit then		
		-- 1 minuto mas de reconocimiento, para completarlo
		timer.scheduleFunction(reconComplete, nil, timer.getTime() + 60 + math.random(-30, 30))		
		isNotReconInit = false;
	end
	
	-- spooter enemy campament. Helo3
	if missionType == 3 and missionSubType == 3 and isMissionEnded == false and isEnemyCampCreated and (CampDefencesTarget == nil or isGroupDestroyed(CampDefencesTarget)) then			
		trigger.action.outText("Mission accomplished. All targets has been destroyed. You can RTB.", 60)				
		trigger.action.outSoundForCoalition(coalition.side.BLUE, "MAAlltargetshasbeendestroyedR.ogg")		
		isMissionEnded = true
		isMissionWin = true;
		SaveInFile("financings.lua", "\n AccountingBalance = AccountingBalance + 25000 -- Mission Acomplished ", false)		
	end
	
	-- Interception hostiles attacking AWACs / bombers atancado pista / CAP (Hostiles destruidos)
	if missionType == 1 and (missionSubType == 1 or missionSubType == 2 or missionSubType == 3 or missionSubType == 5) and isMissionEnded == false 
		and isHostilesAirGroupCreated and Group.getByName(nameHostileAirGroup) == nil 
		and (isHostilesBomberGroupCreated == false or (isHostilesBomberGroupCreated == true and Group.getByName(nameHostileBomberGroup)) == nil)	
		and (isHostilesAirGroupExtraCreated == false or (isHostilesAirGroupExtraCreated == true and Group.getByName(nameHostileAirGroupExtra)) == nil) then		
		trigger.action.outText("Mission accomplished. Hostile aircrafts have been destroyed. You can RTB.", 60)				
		trigger.action.outSoundForCoalition(coalition.side.BLUE, "MAHostileaircraftshavebeendestroyedR.ogg")		
		isMissionEnded = true
		isMissionWin = true;
		SaveInFile("financings.lua", "\n AccountingBalance = AccountingBalance + 25000 -- Mission Acomplished ", false)		
	end
	
	-- Interception hostiles swarm
	if missionType == 1 and missionSubType == 4 and isMissionEnded == false 
		and isHostilesAirSwarmCreated and Group.getByName(nameHostileSwarm1) == nil and Group.getByName(nameHostileSwarm2) == nil and Group.getByName(nameHostileSwarm3) == nil  and Group.getByName(nameHostileSwarm4) == nil then 		 
		trigger.action.outText("Mission accomplished. Rebel fighters have been destroyed. You can RTB.", 60)				
		trigger.action.outSoundForCoalition(coalition.side.BLUE, "MARebelfightershavebeendestroyedR.ogg")		
		isMissionEnded = true
		isMissionWin = true;
		SaveInFile("financings.lua", "\n AccountingBalance = AccountingBalance + 25000 -- Mission Acomplished ", false)		
	end
	
	-- comboy enemigo destruido
	if ((missionType == 3 and missionSubType == 4)) and isMissionEnded == false
			and isEnemyComboyCreated and isGroupDestroyed(comboyAttackerGroup) then			
		trigger.action.outText("Mission accomplished. All targets has been destroyed. You can RTB.", 60)
		trigger.action.outSoundForCoalition(coalition.side.BLUE, "MAAlltargetshasbeendestroyedR.ogg")		
		isMissionEnded = true
		isMissionWin = true;
		SaveInFile("financings.lua", "\n AccountingBalance = AccountingBalance + 25000 -- Mission Acomplished ", false)		
	end
	
	-- escolta a avion civil (CAP o intercepcion). Civil llega de destino
	if ((missionType == 1 and missionSubType == 5) or (missionType == 1 and missionSubType == 3)) and isCivilAirGroupCreated == true and isMissionEnded == false then 
			local civilGroup = Group.getByName(nameCivilAirGroup)
			if civilGroup ~= nil then
				if getDistancePoint(civilGroup, {x = 456191, y = -42463})  <= 85000 then
					trigger.action.outText("[AREA18 COMMAND]: India-25, Command. JA0891 is approaching hostile territory. End your escort and RTB. Over.", 60)
					trigger.action.outSoundForCoalition(coalition.side.BLUE, "COMMANDCivilNearHostileTerrR.ogg")
					
					setMessageDelayed("[JA0891 FLIGHT]: Escort aircraft. JA0891. Thanks for your assistance. Godspeed. Over.", 10, 15, true)
					setSoundDelayed("CIVILThanksEscR.ogg", 15)
					isMissionEnded = true
					isMissionWin = true;
					SaveInFile("financings.lua", "\n AccountingBalance = AccountingBalance + 25000 -- Mission Acomplished ", false)
						
					timer.scheduleFunction(destroyCivilAircraft, nil, timer.getTime() + 90)	
				end
			end
	end
	
	
	if (missionType == 1 and missionSubType == 3) and counterCAP >= (15 + math.random(0,10))
					and isMissionEnded == false and isRandomInProgress == false then
		-- finalizar CAP por tiempo								
		isMissionEnded = true;
		
		setMessageDelayed("[AREA18 COMMAND]: Command. Your on-station time is over. Bravo will relieve you during the next hour on the CAP. Return to base to get some rest before your next shift. Over.", 30, 3)					
		setSoundDelayed("COMMANDCAPEnds.ogg", 3)		
	end	
	
	--Aircraft transport. Entrega BMD-1 X 3
	if ((missionType == 4 and missionSubType == 1)) and isMissionEnded == false then
		
			local distDropZoneC1 = 50000
			local distDropZoneC2 = 50000
			local distDropZoneC3 = 50000
			
			
			if cargo1 ~= nil then
				distDropZoneC1 = getDistanceGroups(cargo1, Group.getByName(nameAllyTroopsGroup))
				--trigger.action.outText("Cargo 1 delivered at " .. math.floor(distDropZoneC1) .. "; Type: " .. Group.getByName("Cargo Group 1"):getUnit(1):getTypeName(), 60)
			end
			
			if cargo2 ~= nil then
				distDropZoneC2 = getDistanceGroups(cargo2, Group.getByName(nameAllyTroopsGroup))
				--trigger.action.outText("Cargo 2 delivered at " .. math.floor(distDropZoneC2) .. "; Type: " .. Group.getByName("Cargo Group 2"):getUnit(1):getTypeName(), 60)
			end
			
			if cargo3 ~= nil then
				distDropZoneC3 = getDistanceGroups(cargo3, Group.getByName(nameAllyTroopsGroup))
				--trigger.action.outText("Cargo 3 delivered at " .. math.floor(distDropZoneC3) .. "; Type: " .. Group.getByName("Cargo Group 3"):getUnit(1):getTypeName(), 60)
			end
			
			if  (cargo1 ~= nil and cargo1:getUnit(1):getTypeName() == "BMD-1" and distDropZoneC1 <= 4000) or
				(cargo2 ~= nil and cargo2:getUnit(1):getTypeName() == "BMD-1" and distDropZoneC2 <= 4000) or
				(cargo3 ~= nil and cargo3:getUnit(1):getTypeName() == "BMD-1" and distDropZoneC3 <= 4000)				 
			then
				trigger.action.outText("[GROUND TROOPS]: Eco group. We can see the package from here. Thanks for the delivery. Over.", 10)
				trigger.action.outSoundForCoalition(coalition.side.BLUE, "ECOseePackageR.ogg")
				
				setMessageDelayed("Mission accomplished. The cargo has been delivered at Point Delta. You can RTB.", 10, 15, true)
				setSoundDelayed("Beep.wav", 15)
				
				isMissionEnded = true
				isMissionWin = true;
				SaveInFile("financings.lua", "\n AccountingBalance = AccountingBalance + 25000 -- Mission Acomplished ", false)
			else
			
				if (cargo1 ~= nil and not isCargo1FarAwayWarned and (cargo1:getUnit(1):getTypeName() ~= "BMD-1" or distDropZoneC1 > 4000)) then
					trigger.action.outText("INFO: (You have delivered cargo 1 too far away from the Drop Zone, or launched a wrong type of cargo)", 60)
					setSoundDelayed("Beep.wav", 15)
					isCargo1FarAwayWarned = true
				end
				if (cargo2 ~= nil and not isCargo2FarAwayWarned and (cargo2:getUnit(1):getTypeName() ~= "BMD-1" or distDropZoneC2 > 4000)) then
					trigger.action.outText("INFO: (You have delivered cargo 2 too far away from the Drop Zone, or launched a wrong type of cargo)", 60)
					setSoundDelayed("Beep.wav", 15)
					isCargo2FarAwayWarned = true
				end
				if (cargo3 ~= nil and not isCargo3FarAwayWarned and (cargo3:getUnit(1):getTypeName() ~= "BMD-1" or distDropZoneC3 > 4000)) then
					trigger.action.outText("INFO: (You have delivered cargo 3 too far away from the Drop Zone, or launched a wrong type of cargo)", 60)
					setSoundDelayed("Beep.wav", 15)
					isCargo3FarAwayWarned = true
				end	
								
			end		
	end
	
	----------------------------------------------------------------------------------------------------------------
	
	
	--Missions failed 
		--escolta comboy (Helo o avion)
	if ((missionType == 2 and missionSubType == 1) or (missionType == 3 and missionSubType == 1)) and isMissionEnded == false and isComboyCreated and isGroupDestroyed(comboyAllyGroup) then
		trigger.action.outText("Mission failed. The comboy has been destroyed. You must RTB.", 60)				
		trigger.action.outSoundForCoalition(coalition.side.BLUE, "MFcomboydestroyedR.ogg")		
		isMissionEnded = true
		isMissionLose = true;
		SaveInFile("financings.lua", "\n AccountingBalance = AccountingBalance - 25000 -- Mission Failed ", false)		
	end
		-- Interception hostiles attacking AWACs  (AWACs o tankers destruidos)
	if missionType == 1 and missionSubType == 1 and isMissionEnded == false and isHostilesAirGroupCreated and (Group.getByName("Overlord") == nil or Group.getByName("tanker1") == nil or Group.getByName("tanker2") == nil)  then
		trigger.action.outText("Mission failed. Hostiles have destroyed one of ally support aircrafts. You must RTB.", 60)				
		trigger.action.outSoundForCoalition(coalition.side.BLUE, "MFHostilesdestroyedallysupportaircraftsR.ogg")		
		isMissionEnded = true
		isMissionLose = true;
		SaveInFile("financings.lua", "\n AccountingBalance = AccountingBalance - 25000 -- Mission Failed ", false)		
	end
		-- Interception hostiles attacking runway (AWACs o tankers destruidos o bombas en la base)
	if missionType == 1 and missionSubType == 2 and isMissionEnded == false and isHostilesAirGroupCreated and (Group.getByName("Overlord") == nil or Group.getByName("tanker1") == nil or Group.getByName("tanker2") == nil)
		or isShirazBombed then
		trigger.action.outText("Mission failed. Hostiles have destroyed one of our assets. You must RTB.", 60)				
		trigger.action.outSoundForCoalition(coalition.side.BLUE, "MFHostilesdestroyedoneourassetsR.ogg")		
		isMissionEnded = true
		isMissionLose = true;
		SaveInFile("financings.lua", "\n AccountingBalance = AccountingBalance - 25000 -- Mission Failed ", false)		
	end
	
		-- Interception hostiles swarm (AWACs o tankers destruidos)	
	if missionType == 1 and missionSubType == 4 and isMissionEnded == false and isHostilesAirSwarmCreated and (Group.getByName("Overlord") == nil or Group.getByName("tanker1") == nil or Group.getByName("tanker2") == nil)  then
		trigger.action.outText("Mission failed. Hostiles have destroyed one of our assets. You must RTB.", 60)				
		trigger.action.outSoundForCoalition(coalition.side.BLUE, "MFHostilesdestroyedoneourassetsR.ogg")	
		isMissionEnded = true
		isMissionLose = true;
		SaveInFile("financings.lua", "\n AccountingBalance = AccountingBalance - 25000 -- Mission Failed ", false)		
	end
	
	-- escolta a avion civil (CAP o intercepcion). Civil llega a Shiraz
	if ((missionType == 1 and missionSubType == 5) or (missionType == 1 and missionSubType == 3)) and isCivilAirGroupCreated == true and isCivilIntercepted == false and isMissionLose == false then 
			local civilGroup = Group.getByName(nameCivilAirGroup)
			if civilGroup ~= nil then			
				if getDistancePoint(civilGroup, {x = 381075.66519277, y = -350696.1185350})  <= 50000 then
					trigger.action.outText("[AREA18 COMMAND]: India-25. Command. unidentified aircraft has managed to reach Shiraz airspace. Mission failed. You must RTB. Over.", 60)
					trigger.action.outSoundForCoalition(coalition.side.BLUE, "COMMANDCivilNearShirazR.ogg")
										
					isMissionEnded = true
					isMissionLose = true;
					SaveInFile("financings.lua", "\n AccountingBalance = AccountingBalance - 25000 -- Mission Failed ", false)
				end
			end
	end
	
	-- CAP Nothostileaircraft es derribado por error	
	if (missionType == 1 and missionSubType == 3) and isNotHostileAirGroupCreated == true
		and (notHostileAirGroup == nil or Group.getByName(nameNotHostileAirGroup) == nil) and typeNotHostileInDestiny ~= 1
		and isMissionLose == false then
			trigger.action.outText("Mission failed. You have destroyed a forbiden target and provoked an incident with a non hostile faction. You must RTB.", 60)
			trigger.action.outSoundForCoalition(coalition.side.BLUE, "MFdestroyForbidenTarget.ogg")
			isMissionEnded = true
			isMissionLose = true;
			SaveInFile("financings.lua", "\n AccountingBalance = AccountingBalance - 25000 -- Mission Failed ", false)			
	end
	
	-- CAP Nothostileaircraft llega a Shiraz	
	if (missionType == 1 and missionSubType == 3) and isNotHostileAirGroupCreated == true and isMissionLose == false then 
			local notHostileGroup = Group.getByName(nameNotHostileAirGroup)
			if notHostileGroup ~= nil then			
				if getDistancePoint(notHostileGroup, {x = 381075.66519277, y = -350696.1185350})  <= 30000 then
					trigger.action.outText("[AREA18 COMMAND]: India-25. Command. unidentified aircraft has managed to reach Shiraz airspace. Mission failed. You must RTB. Over.", 60)
					trigger.action.outSoundForCoalition(coalition.side.BLUE, "COMMANDCivilNearShirazR.ogg")
										
					isMissionEnded = true
					isMissionLose = true;
					SaveInFile("financings.lua", "\n AccountingBalance = AccountingBalance - 25000 -- Mission Failed ", false)
				end
			end
	end
	
	-----------------------------------------------------------------------------------------------------------------
	
	
	-- random events
	if isRandomInProgress == false and isMissionEnded == false then					
		if ((missionType == 2 and missionSubType == 1) or (missionType == 3 and missionSubType == 1)) and isComboyMoving then
		-- Escolta comboy(helo o avion). Random Chat/Crear comboy enemigo/neutral 
			local randomizer = secureRandomizer(20)
			--trigger.action.outText("randomizador: " .. randomizer, 10)
			if randomizer == 1 or randomizer == 2 or randomizer == 3 or randomizer == 4 or randomizer == 5 then				
				randomGroundChat(nameComboyGroup)
			elseif randomizer == 10 then
				-- comboy hostil de inicio
				isRandomInProgress = true;				
				local factorx = 0
				local factory = 0				
				local factorHelo = 1
				local tipoComboyHostil = 1
				local hostilesOnRoad = true
				
				if missionType == 3 then --si es helicoptero, creamos el comboy mas cerca, con unidades mas debiles 
					factorHelo = 0.7
					tipoComboyHostil = 4
				end
				
				if destinationComboy.x - originComboy.x > 0 then
					factorx = 8000 * factorHelo
				else
					factorx = -8000 * factorHelo
				end
				
				if destinationComboy.y - originComboy.y > 0 then
					factory = 8000 * factorHelo
				else
					factory = -8000 * factorHelo
				end		
				local PosGroupAlly = comboyAllyGroup:getUnit(1):getPoint();
				local originComboyAttackers = {x = PosGroupAlly.x + factorx, y = PosGroupAlly.z + factory}
				
				if land.getSurfaceType(originComboyAttackers) == land.SurfaceType.WATER or land.getSurfaceType(originComboyAttackers) == land.SurfaceType.SHALLOW_WATER then
					originComboyAttackers = {x = PosGroupAlly.x - factorx, y = PosGroupAlly.z - factory}
				end;
				
				comboyAttackerGroup = createComboyAttackers(originComboyAttackers, hostilesOnRoad, tipoComboyHostil)
				setRouteComboyAttackers(hostilesOnRoad)
				--trigger.action.outText("para por Hostil", 10)
				setComboyStop(comboyAllyGroup)
				
				missionCommands.removeItem(menuReqStop)
				missionCommands.removeItem(menuReqCont)
				isEnemyComboyCreated = true
				trigger.action.outText("[".. string.upper(nameComboyGroup) .. "]: Eco group. " .. nameComboyGroup .. ". Something on the road has punctured a tyre of one of the trucks. Seems some kind of sabotage. Stay put until further orders.", 10, true)
				trigger.action.outSoundForCoalition(coalition.side.BLUE, "ECOSomethingroadpuncturedtyreR.ogg")	
				
				setMessageDelayed("[".. string.upper(nameComboyGroup) .. "]: Eco group. ".. nameComboyGroup .. ". Command informs that hostile vehicles are approaching to our possition. You are ordered to intercept and destroy", 20, 35, true)				
				setMessageDelayed("Bearing from " .. nameComboyGroup .. ": " .. getBearing(comboyAllyGroup:getUnit(1):getPoint(), comboyAttackerGroup:getUnit(1):getPoint()) .. "º/" .. math.floor((getDistanceGroups(comboyAllyGroup, comboyAttackerGroup)* 0.000539957) + 0.5), 90, 35)	
				
				setSoundDelayed("DELECOCommandinformsHOSTILEvehiclesapproachingR.ogg", 35)
				setMessageDelayed("INFO: (use F10 radio menu to identify vehicles when you are in their nearby)", 20, 35)
			elseif randomizer == 11 then
				--comboy neutral de inicio
				isRandomInProgress = true;				
				local factorx = 0
				local factory = 0
				local factorHelo = 1 --si es helicoptero, creamos el comboy mas cerca y con unidades mas flojas
				
				if missionType == 3 then
					factorHelo = 0.7
				end
				
				
				if destinationComboy.x - originComboy.x > 0 then
					factorx = 15000 * factorHelo
				else
					factorx = -15000 * factorHelo
				end
				
				if destinationComboy.y - originComboy.y > 0 then
					factory = 1500 * factorHelo
				else
					factory = -1500 * factorHelo
				end		
				local PosGroupAlly = comboyAllyGroup:getUnit(1):getPoint();
				local originComboyAttackers = {x = PosGroupAlly.x + factorx, y = PosGroupAlly.z + factory}
				
				if land.getSurfaceType(originComboyAttackers) == land.SurfaceType.WATER or land.getSurfaceType(originComboyAttackers) == land.SurfaceType.SHALLOW_WATER then
					originComboyAttackers = {x = PosGroupAlly.x - factorx, y = PosGroupAlly.z - factory}
				end;
				
				comboyAttackerGroup = createComboyAttackers(originComboyAttackers, true, 6)
				setRouteComboyAttackers(true)
				--trigger.action.outText("para por Neutral", 10)
				setComboyStop(comboyAllyGroup)
				
				missionCommands.removeItem(menuReqStop)
				missionCommands.removeItem(menuReqCont)
				isEnemyComboyCreated = true
				trigger.action.outText("[".. string.upper(nameComboyGroup) .. "]: Eco group. " .. nameComboyGroup .. ". Something on the road has punctured a tyre of one of the trucks. Seems some kind of sabotage. Stay put until further orders.", 10, true)
				trigger.action.outSoundForCoalition(coalition.side.BLUE, "ECOSomethingroadpuncturedtyreR.ogg")	
				
				setMessageDelayed("[".. string.upper(nameComboyGroup) .. "]: Eco group. " .. nameComboyGroup .. ". Command informs that unknown vehicles are approaching to our possition. You are ordered to intercept, identify the unknown vehicle comboy and destroy if they are hostiles", 20, 35, true)
				setMessageDelayed("Bearing from " .. nameComboyGroup .. ": " .. getBearing(comboyAllyGroup:getUnit(1):getPoint(), comboyAttackerGroup:getUnit(1):getPoint()) .. "º/" .. math.floor((getDistanceGroups(comboyAllyGroup, comboyAttackerGroup)* 0.000539957) + 0.5), 90, 35)	
				setSoundDelayed("DELECOCommandinformsUNKNOWNvehiclesapproachingR.ogg", 35)
				setMessageDelayed("INFO: (use F10 radio menu to identify vehicles when you are in their nearby)", 20, 35)								
				menuIdentifyUnknown = missionCommands.addCommand('Identify Unknown', menuPrinc3, identifyUnknown, nil)
			elseif randomizer == 12 then
				-- emboscada
				isRandomInProgress = true;				
				local factorx = 0
				local factory = 0								
				local tipoComboyHostil = 5
				local hostilesOnRoad = false
				
				if destinationComboy.x - originComboy.x > 0 then
					factorx = 700 
				else
					factorx = -700 
				end
				
				if destinationComboy.y - originComboy.y > 0 then
					factory = 700 
				else
					factory = -700 
				end		
				local PosGroupAlly = comboyAllyGroup:getUnit(1):getPoint();
				
				local explosionPoint = {x = PosGroupAlly.x + 30, y = PosGroupAlly.y, z = PosGroupAlly.z + 30}				
				trigger.action.explosion(explosionPoint, 100)
				trigger.action.effectSmokeBig(explosionPoint, 2, 1)
				
				local originComboyAttackers = {x = PosGroupAlly.x + factorx, y = PosGroupAlly.z + factory}
				
				if land.getSurfaceType(originComboyAttackers) == land.SurfaceType.WATER or land.getSurfaceType(originComboyAttackers) == land.SurfaceType.SHALLOW_WATER then
					originComboyAttackers = {x = PosGroupAlly.x - factorx, y = PosGroupAlly.z - factory}
				end;				
				
				comboyAttackerGroup = createComboyAttackers(originComboyAttackers, hostilesOnRoad, tipoComboyHostil)
				trigger.action.smoke(comboyAttackerGroup:getUnit(1):getPoint(), 0)
				
				
				setRouteComboyAttackers(hostilesOnRoad)
				--trigger.action.outText("para por Emboscada", 10)
				setComboyStop(comboyAllyGroup)				
				
				missionCommands.removeItem(menuReqStop)
				missionCommands.removeItem(menuReqCont)
				isEnemyComboyCreated = true
				
				setMessageDelayed("[".. string.upper(nameComboyGroup) .. "]: Eco group. " .. nameComboyGroup .. ". We are under attack!!!. Road is mined and hostile forces are on approach!!!", 20, 3, true)				
				setSoundDelayed("DELECOWeareunderattackR.ogg", 3)
				setMessageDelayed("We are taking fire!!! Hostiles marked with green smoke!!! Repeat, hostiles marked green!!!", 20, 10)
				setSoundDelayed("DELWearetakingfireR.ogg", 10)
				
			end
		elseif missionType == 1 and missionSubType == 3 then
			-- CAP
			local Players = coalition.getPlayers(coalition.side.BLUE)	 
			
			for i = 1, #Players do		
				if PlayerWP1 ~= nil and isPlayerInRangeCAP == false and getDistancePoint(Players[i]:getGroup(), {x = PlayerWP1.x, y = PlayerWP1.z})  <= 20000 then
					isPlayerInRangeCAP = true
					--trigger.action.outText("player cerca de waypoint. Empieza cuenta de 3", 10)        							
--				else	
--					if PlayerWP1 ~= nil then
--						trigger.action.outText("player no cerca WP1: " .. getDistancePoint(Players[i]:getGroup(), {x = PlayerWP1.x, y = PlayerWP1.z}), 10)
--					end
				end
			end	
			
			--isPlayerInRangeCAP = true
			--counterCAP = 3
			
			if PlayerWP1 ~= nil and isPlayerInRangeCAP == true and isRandomInProgress == false then
				counterCAP = counterCAP + 1
				--trigger.action.outText("Comienza random event. counterCAP: " .. counterCAP, 10)
				--todo: decir algo desde el command
			end
					
			--CAP random events		
			if counterCAP >= 4 and isPlayerRefueling == false then
				--trigger.action.outText("counterCAP: " .. counterCAP, 10)
				local randomizer = secureRandomizer(30)
				--local randomizer = 7
				--trigger.action.outText("randomizador: " .. randomizer, 10)
				if randomizer == 4 then
					--atacantes fighters
					hostileAirGroup = createHostilesAirGroup({x = 191556.93513, y = -537803.123665}, 2000, 20000)			
					hostileAttackAWACS(hostileAirGroup, Group.getByName("Overlord"))
					isHostilesAirGroupCreated = true;
					isRandomInProgress = true;
					
					if getNumberOfPlayers() >= 4 then
						local mainGroupPos = hostileAirGroup:getUnit(1):getPoint()
						hostileAirGroupExtra = createHostilesAirGroupExtra({x = mainGroupPos.x, y = mainGroupPos.z}, 150000, 200)
						isHostilesAirGroupExtraCreated = true;
					end
					
					setMessageDelayed("[AREA18 COMMAND]: Charlie group. Command. Hostile bombers are on approach. Intercept and destroy them. Out", 20, 3)
					setSoundDelayed("DELCHARLIECommandHostileBOMBERSareapproachR.ogg", 3)
				elseif randomizer == 5 then
					--atacantes fighters + bombers
					local attackers = createHostilesBomberGroup({x = 191556.93513, y = -537803.123665}, 2000, 20000)			
					hostileAirGroup = attackers.HostileEscortGroup
					hostileBomberGroup = attackers.HostileBomberGroup			
					isHostilesAirGroupCreated = true;
					isHostilesBomberGroupCreated = true;
					isRandomInProgress = true;
					
					if getNumberOfPlayers() >= 4 then
						local mainGroupPos = hostileAirGroup:getUnit(1):getPoint()
						hostileAirGroupExtra = createHostilesAirGroupExtra({x = mainGroupPos.x, y = mainGroupPos.z}, 150000, 200)
						isHostilesAirGroupExtraCreated = true;
					end
					
					setMessageDelayed("[AREA18 COMMAND]: Charlie group. Command. Hostile fighters are on approach. Intercept and destroy them. Out", 20, 3)
					setSoundDelayed("DELCHARLIECommandHostileFIGHTERSareapproachR.ogg", 3)
				elseif randomizer == 6 then					
					--civil aircraft
					civilAirGroup = createCivilAirGroup({x = 191556.93513, y = -537803.123665}, 2000, 20000)					
					setAirRoute(civilAirGroup, {x = civilAirGroup:getUnit(1):getPoint().x, y = civilAirGroup:getUnit(1):getPoint().z, z = civilAirGroup:getUnit(1):getPoint().y}, {x = 381075.66519277 , z = 6000, y = -350696.1185350}, 250)
					isCivilAirGroupCreated = true
					isRandomInProgress = true;
					
					setMessageDelayed("[AREA18 COMMAND]: Charlie group. Command. An unidentified aircraft has been detected heading for Shiraz and is not answering to our calls. Intercept and identify before it gets closer. Weapons cold until command authorize to attack the target. Over.", 20, 3)
					setMessageDelayed("INFO:(You can intercept and identify target through F10 radio menu options)", 20, 3)
					setSoundDelayed("DELCHARLIECommandHostileFIGHTERSareapproachR.ogg", 3)
					
					menuPrinc3 = missionCommands.addSubMenu('Other Commands...')								
					menuOtherInterceptCiv = missionCommands.addCommand('Intercept civil aircraft (request intentions)', menuPrinc3, interceptCivilAircraft, nil)			
				elseif randomizer == 7 then
					--Not Hostile aircraft
					--trigger.action.outText("Not Hostile aircraft", 10)
					if math.random(1,4) <= 2 then
						WP1NotHostile = {x = 227173, y = -508378}
						WP2NotHostile = {x = 353084 , z = 15000, y = -571533}
					else
						WP1NotHostile = {x = 353084,  y = -571533}
						WP2NotHostile = {x = 227173,  z = 15000, y = -508378}					
					end
					
					
					notHostileAirGroup = createNotHostileAirGroup(WP1NotHostile, 500, 5000)					
					setAirRoute(notHostileAirGroup, {x = notHostileAirGroup:getUnit(1):getPoint().x, y = notHostileAirGroup:getUnit(1):getPoint().z, z = notHostileAirGroup:getUnit(1):getPoint().y}, WP2NotHostile, 100)
					isNotHostileAirGroupCreated = true
					isRandomInProgress = true;
					
					setMessageDelayed("[OVERLORD]: Overlord. We have new contact flying over international waters close to our maritime boundary. Descent to 1000 feets, intercept the bogie and remain hidden if possible, but do not attack until further orders. Over.", 30, 3)					
					setSoundDelayed("OVERLORDBogieInternWaters.ogg", 3)									
									
				end					
				
				
				
			
			end			
			
		elseif (missionType == 1 and (missionSubType == 3 or missionSubType == 5)) and isCivilAirGroupCreated == true and isCheckCivil == false then
			-- escolta a avion civil (CAP o intercepcion).
			local civilGroup = Group.getByName(nameCivilAirGroup)
			local Players = coalition.getPlayers(coalition.side.BLUE)	 
			--local isPlayerInRange = false
			for i = 1, #Players do
				local distancia = getDistanceGroups(Players[i]:getGroup(), civilGroup)
				--trigger.action.outText("distancia: ".. distancia, 10)    
				if civilGroup ~= nil and getDistanceGroups(Players[i]:getGroup(), civilGroup) < 90000 then
					isPlayerInRange = true
				end
			end	
			
			if isPlayerInRange then
				if math.random(1,4) == 4 then	
					-- En realidad no es un civil
					hostileAirGroup = createHostilesAirGroup({x = civilGroup:getUnit(1):getPoint().x, y = civilGroup:getUnit(1):getPoint().z}, 1, 1, getHeading(civilGroup:getUnit(1)))			
					--Group.getByName(nameHostileAirGroup):getController():setOption(AI.Option.Ground.id.ALARM_STATE, AI.Option.Ground.val.ALARM_STATE.RED)
					Group.getByName(nameHostileAirGroup):getController():setOption(AI.Option.Air.id.ROE, AI.Option.Air.val.ROE.WEAPON_FREE)					
					isHostilesAirGroupCreated = true;
					isRandomInProgress = true;
					civilGroup:destroy()
					isCivilAirGroupCreated = false;
					isCheckCivil = true
				else
					-- si es un civil
					isCheckCivil = true
				end
			end
		elseif (missionType == 2 and (missionSubType == 2 or missionSubType == 3)) then			
			--atacar campamento enemigo o SAMs campamento enemigo
			
			if isHostilesDefenderAirGroupCreated == false and math.random(1,20) == 1 then		
				-- crea defensores aereos campamento enemigo, si hay player en el area
				local isPlayerInRange = false
				local Players = coalition.getPlayers(coalition.side.BLUE)
				
				for i = 1, #Players do					    
					local posCamp = {x = CampStaticTarget:getPoint().x, y = CampStaticTarget:getPoint().z}
					if getDistancePoint(Players[i]:getGroup(), posCamp) < 15000 then
						isPlayerInRange = true						
					end
				end	
								
				if isPlayerInRange == true then
					createHostilesDefenderAirGroup()
					setMessageDelayed("[AWACS]: Overlord. New contact is in direct route to AO. Withdraw or engage at your disposal. Over", 15, 20)
					setSoundDelayed("OVERLORDNewContact.ogg", 20)					
				end
			end
			
		end
	end 
	
	---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	
	--continuous actions
		--Escolta comboy(helo o avion). Comboy continua ruta tras enemigos destruidos
	if ((missionType == 2 and missionSubType == 1) or (missionType == 3 and missionSubType == 1)) and isEnemyComboyCreated == true and isGroupDestroyed(comboyAttackerGroup) then 
		setMessageDelayed("[".. string.upper(nameComboyGroup) .. "]: Eco group. " .. nameComboyGroup .. ". Hostiles destroyed. Proceeding with route", 10, 5)
		setSoundDelayed("DELECOHostilesdestroyedProceedingrouteR.ogg", 3)
		isEnemyComboyCreated = false
		isRandomInProgress = false		
		strRandoms = ""				
		resetRouteAllyComboy()
		menuReqStop = missionCommands.addCommand('Stop comboy', menuPrinc1, requestStopComboy, nil)
		menuReqCont = missionCommands.addCommand('Continue route', menuPrinc1, requestContinueComboy, nil)		
	end
	
	-- escolta a avion civil (CAP o intercepcion). Interceptores salen al encuentro
	if isCivilAirGroupCreated == true and isCivilEscortInterceptorsCreated == false and isMissionEnded == false then 				
			local civilGroup = Group.getByName(nameCivilAirGroup)
			if civilGroup ~= nil then
				if getDistancePoint(civilGroup, {x = 456191, y = -42463})  <= 140000 then							
					isRandomInProgress = true
					if math.random(1,2) == 1 then		
					--interceptores salen al encuentro
						createCivilEscortInterceptors()
						menuExplainMission = missionCommands.addCommand('Explain mission', menuPrinc3, setROECivilEscortInterceptors, nil)
						
						setMessageDelayed("[UNKNOWN]:Trespasser aircraft. This is Hunter 1-5. You are in violation of the glorious Persian Empire airspace. Prepare to face the consequences. Over", 10, 15, true)						
						setSoundDelayed("TRESPASSViolationPersianAirspaceR.ogg", 15)
						
						setMessageDelayed("TIP:(Explain your escort mission to Persian interceptors through F10 Radio Menu)", 10, 30, true)
						setSoundDelayed("Beep.wav", 30)
					else
					-- nadie sale al encuentro
						isCivilEscortInterceptorsCreated = true
					end	
				end
			end		
	end
	
	if isNotHostileAirGroupCreated == true and typeNotHostileInDestiny == 0 and Group.getByName(nameNotHostileAirGroup) ~= nil
		and getDistancePoint(notHostileAirGroup, WP2NotHostile) < 20000 then
		--CAP not hostile group
		if math.random(1,4) <= 2 then
			-- el hostile vira hacia Shiraz		
			setAirRoute(notHostileAirGroup, {x = notHostileAirGroup:getUnit(1):getPoint().x, y = notHostileAirGroup:getUnit(1):getPoint().z, z = notHostileAirGroup:getUnit(1):getPoint().y}, {x = 381075.66519277 , z = 6000, y = -350696.1185350}, 250)
			setMessageDelayed("[OVERLORD]: Overlord. The bogie is heading for Shiraz and is not responding to our calls. You are cleared to engage and destroy. Over", 30, 60, true)
			setSoundDelayed("OVERLORDBogieHeadingShiraz.ogg", 60)
			typeNotHostileInDestiny = 1
		else
			-- el hostile vira hacia mar abierto
			setAirRoute(notHostileAirGroup, {x = notHostileAirGroup:getUnit(1):getPoint().x, y = notHostileAirGroup:getUnit(1):getPoint().z, z = notHostileAirGroup:getUnit(1):getPoint().y}, {x = 344290 , z = 6000, y = -629492}, 250)			
			setMessageDelayed("[OVERLORD]: Overlord. The bogie has left our maritime boundaires. Disengage and return to your CAP mission. Over.", 30, 40, true)			
			setSoundDelayed("OVERLORDBogieLeftMaritimeBound.ogg", 40)
			setRemoveGroupDelayed(notHostileAirGroup:getName(), 120)
			isRandomInProgress = false;
			typeNotHostileInDestiny = 2
		end
		
--	else		
--		trigger.action.outText("distancia: ".. getDistancePoint(notHostileAirGroup, {x = 353084 , z = 15000, y = -571533}), 30, true)    		
	end
	
	
	if isNotHostileAirGroupCreated == true and isRandomInProgress == true and typeNotHostileInDestiny == 1
		and (notHostileAirGroup == nil or Group.getByName(nameNotHostileAirGroup) == nil) then
		setMessageDelayed("[OVERLORD]: Overlord. Kill confirmed. Disengage and return to your CAP mission. Over.", 20, 30, true)
		setSoundDelayed("OVERLORDKillReturnCAP.ogg", 30)
		isRandomInProgress = false;		
	end
	
	
	-- defensores aereos del campamento enemigo atacan a azules si están cerca
	if isHostilesDefenderAirGroupCreated == true and Group.getByName(nameHostileDefenderAirGroup) ~= nil then
		local isPlayerInRange = false
		local azules = coalition.getGroups(coalition.side.BLUE, Group.Category.AIRPLANE)	 		
		local posCamp = {x = CampStaticTarget:getPoint().x, y = CampStaticTarget:getPoint().z}
		for i = 1, #azules do		
			if getDistancePoint(azules[i], posCamp)  <= 40000 then
				isPlayerInRange = true
			end
		end	
		
		azules = coalition.getGroups(coalition.side.BLUE, Group.Category.HELICOPTER)
		for i = 1, #azules do		
			if getDistancePoint(azules[i], posCamp)  <= 40000 then
				isPlayerInRange = true
			end
		end	
	
		if isPlayerInRange then
			--si hay algun miembro azul cerca del campamento, los defensores aereos lo atacaran
			Group.getByName(nameHostileDefenderAirGroup):getController():setOption(AI.Option.Air.id.ROE, AI.Option.Air.val.ROE.WEAPON_FREE)	    
			--trigger.action.outText("atacan", 10)
		else
			-- sino hay ninguno, dejan de atacar
			Group.getByName(nameHostileDefenderAirGroup):getController():setOption(AI.Option.Air.id.ROE, AI.Option.Air.val.ROE.RETURN_FIRE)
			setMessageDelayed("[AWACS]: Overlord. Hostiles are withdrawing. Over", 15, 15)
			setSoundDelayed("OVERLORDHostilesWithdraw.ogg", 15)			
			--trigger.action.outText("dejan de atacar", 10)
		end
		
	end
	
		
end;


function getRadioFreq()	
	   
	if missionType == 1 and missionSubType == 1 then
		trigger.action.outText("CALLSIGN: ", 60, true) 
		trigger.action.outText("   Players: India 12 ", 60, false)  
		trigger.action.outText("FREQUENCIES: ", 60, false) 
		trigger.action.outText("   Shiraz International: 121.9Mhz AM, 250.35Mhz ", 60, false)
		trigger.action.outText("   FARP Base (London): 128.5Mhz AM ", 60, false)
		trigger.action.outText("   FARP Base (Madrid): 130.25Mhz AM ", 60, false)
		trigger.action.outText("   FARP Base (Paris): 135.55Mhz AM ", 60, false)		
		trigger.action.outText("AWACS: ", 60, false)
		trigger.action.outText("   Overlord: 301.3Mhz AM ", 60, false)
		trigger.action.outText("TANKER: ", 60, false) 
		trigger.action.outText("   Arco (basket): TACAN 19X; 253.2Mhz AM ", 60, false) 
		trigger.action.outText("   Texaco (boom): TACAN 18X; 251.5Mhz AM ", 60, false) 
	elseif missionType == 1 and missionSubType == 2 then		
		trigger.action.outText("CALLSIGN: ", 60, true) 
		trigger.action.outText("   Players: India 50 ", 60, false) 
		trigger.action.outText("FREQUENCIES: ", 60, false) 
		trigger.action.outText("   Shiraz International: 121.9Mhz AM, 250.35Mhz ", 60, false)
		trigger.action.outText("   FARP Base (London): 128.5Mhz AM ", 60, false)
		trigger.action.outText("   FARP Base (Madrid): 130.25Mhz AM ", 60, false)
		trigger.action.outText("   FARP Base (Paris): 135.55Mhz AM ", 60, false)		
		trigger.action.outText("AWACS: ", 60, false) 
		trigger.action.outText("   Overlord: 301.3Mhz AM ", 60, false)
		trigger.action.outText("TANKER: ", 60, false) 
		trigger.action.outText("   Arco (basket): TACAN 19X; 253.2Mhz AM ", 60, false) 
		trigger.action.outText("   Texaco (boom): TACAN 18X; 251.5Mhz AM ", 60, false)
	elseif missionType == 1 and missionSubType == 3 then					
		trigger.action.outText("CALLSIGN: ", 60, true) 
		trigger.action.outText("   Players: Charlie 15 ", 60, false) 
		trigger.action.outText("FREQUENCIES: ", 60, false) 
		trigger.action.outText("   Shiraz International: 121.9Mhz AM, 250.35Mhz ", 60, false)
		trigger.action.outText("   FARP Base (London): 128.5Mhz AM ", 60, false)
		trigger.action.outText("   FARP Base (Madrid): 130.25Mhz AM ", 60, false)
		trigger.action.outText("   FARP Base (Paris): 135.55Mhz AM ", 60, false)		
		trigger.action.outText("AWACS: ", 60, false) 
		trigger.action.outText("   Overlord: 301.3Mhz AM ", 60, false)
		trigger.action.outText("TANKER: ", 60, false)
		trigger.action.outText("   Arco (basket): TACAN 19X; 253.2Mhz AM ", 60, false) 
		trigger.action.outText("   Texaco (boom): TACAN 18X; 251.5Mhz AM ", 60, false)
	elseif missionType == 1 and missionSubType == 4 then
		trigger.action.outText("CALLSIGN: ", 60, true) 
		trigger.action.outText("   Players: India 27 ", 60, false)  
		trigger.action.outText("FREQUENCIES: ", 60, false) 
		trigger.action.outText("   Shiraz International: 121.9Mhz AM, 250.35Mhz ", 60, false)
		trigger.action.outText("   FARP Base (London): 128.5Mhz AM ", 60, false)
		trigger.action.outText("   FARP Base (Madrid): 130.25Mhz AM ", 60, false)
		trigger.action.outText("   FARP Base (Paris): 135.55Mhz AM ", 60, false)		
		trigger.action.outText("AWACS: ", 60, false) 
		trigger.action.outText("   Overlord: 301.3Mhz AM ", 60, false)
		trigger.action.outText("TANKER: ", 60, false)
		trigger.action.outText("   Arco (basket): TACAN 19X; 253.2Mhz AM ", 60, false) 
		trigger.action.outText("   Texaco (boom): TACAN 18X; 251.5Mhz AM ", 60, false)
	elseif missionType == 1 and missionSubType == 5 then		
		trigger.action.outText("CALLSIGN: ", 60, true) 
		trigger.action.outText("   Players: India 25 ", 60, false)  
		trigger.action.outText("FREQUENCIES: ", 60, false) 
		trigger.action.outText("   Shiraz International: 121.9Mhz AM, 250.35Mhz ", 60, false)
		trigger.action.outText("   FARP Base (London): 128.5Mhz AM ", 60, false)
		trigger.action.outText("   FARP Base (Madrid): 130.25Mhz AM ", 60, false)
		trigger.action.outText("   FARP Base (Paris): 135.55Mhz AM ", 60, false)		
		trigger.action.outText("AWACS: ", 60, false) 
		trigger.action.outText("   Overlord: 301.3Mhz AM ", 60, false)
		trigger.action.outText("TANKER: ", 60, false)
		trigger.action.outText("   Arco (basket): TACAN 19X; 253.2Mhz AM ", 60, false) 
		trigger.action.outText("   Texaco (boom): TACAN 18X; 251.5Mhz AM ", 60, false)
	elseif missionType == 2 and missionSubType == 1 then		
		trigger.action.outText("CALLSIGN: ", 60, true) 
		trigger.action.outText("   Players: Eco 11 ", 60, false) 
		trigger.action.outText("   Comboy: " .. nameComboyGroup, 60, 35, 60, false) 
		trigger.action.outText("FREQUENCIES: ", 60, 35, false) 
		trigger.action.outText("   Shiraz International: 121.9Mhz AM, 250.35Mhz ", 60, false)
		trigger.action.outText("   FARP Base (London): 128.5Mhz AM ", 60, false)
		trigger.action.outText("   FARP Base (Madrid): 130.25Mhz AM ", 60, false)
		trigger.action.outText("   FARP Base (Paris): 135.55Mhz AM ", 60, false)		
		trigger.action.outText("AWACS: ", 60, false) 
		trigger.action.outText("   Overlord: 301.3Mhz AM ", 60, false)
		trigger.action.outText("TANKER: ", 60, false) 
		trigger.action.outText("   Arco (basket): TACAN 19X; 253.2Mhz AM ", 60, false) 
		trigger.action.outText("   Texaco (boom): TACAN 18X; 251.5Mhz AM ", 60, false)
	elseif missionType == 2 and missionSubType == 2 then
		trigger.action.outText("CALLSIGN: ", 60, true) 
		trigger.action.outText("   Players: Romeo 71 ", 60, false)
		trigger.action.outText("   Enemy camp: Point Tango ", 60, false)
		trigger.action.outText("FREQUENCIES: ", 60, false)
		trigger.action.outText("   Shiraz International: 121.9Mhz AM, 250.35Mhz ", 60, false)
		trigger.action.outText("   FARP Base (London): 128.5Mhz AM ", 60, false)
		trigger.action.outText("   FARP Base (Madrid): 130.25Mhz AM ", 60, false)
		trigger.action.outText("   FARP Base (Paris): 135.55Mhz AM ", 60, false)		
		trigger.action.outText("AWACS: ", 60, false) 
		trigger.action.outText("   Overlord: 301.3Mhz AM ", 60, false)
		trigger.action.outText("TANKER: ", 60, false) 
		trigger.action.outText("   Arco (basket): TACAN 19X; 253.2Mhz AM ", 60, false) 
		trigger.action.outText("   Texaco (boom): TACAN 18X; 251.5Mhz AM ", 60, false)
	elseif missionType == 2 and missionSubType == 3 then
		trigger.action.outText("CALLSIGN: ", 60, true) 
		trigger.action.outText("   Players: Romeo 18 ", 60, false) 
		trigger.action.outText("   Enemy camp: Point Tango ", 60, false) 				
		trigger.action.outText("FREQUENCIES: ", 60, false) 
		trigger.action.outText("   Shiraz International: 121.9Mhz AM, 250.35Mhz ", 60, false)
		trigger.action.outText("   FARP Base (London): 128.5Mhz AM ", 60, false)
		trigger.action.outText("   FARP Base (Madrid): 130.25Mhz AM ", 60, false)
		trigger.action.outText("   FARP Base (Paris): 135.55Mhz AM ", 60, false)		
		trigger.action.outText("AWACS: ", 60, false) 
		trigger.action.outText("   Overlord: 301.3Mhz AM ", 60, false)
		trigger.action.outText("TANKER: ", 60, false)
		trigger.action.outText("   Arco (basket): TACAN 19X; 253.2Mhz AM ", 60, false) 
		trigger.action.outText("   Texaco (boom): TACAN 18X; 251.5Mhz AM ", 60, false)
	elseif missionType == 2 and missionSubType == 4 then
		trigger.action.outText("CALLSIGN: ", 60, true) 
		trigger.action.outText("   Players: Romeo 25 ", 60, false)
		trigger.action.outText("   Enemy camp: Point Tango ", 60, false) 		
		trigger.action.outText("FREQUENCIES: ", 60, false) 
		trigger.action.outText("   Shiraz International: 121.9Mhz AM, 250.35Mhz ", 60, false)
		trigger.action.outText("   FARP Base (London): 128.5Mhz AM ", 60, false)
		trigger.action.outText("   FARP Base (Madrid): 130.25Mhz AM ", 60, false)
		trigger.action.outText("   FARP Base (Paris): 135.55Mhz AM ", 60, false)		
		trigger.action.outText("AWACS: ", 60, false) 
		trigger.action.outText("   Overlord: 301.3Mhz AM ", 60, false)
		trigger.action.outText("TANKER: ", 60, false) 
		trigger.action.outText("   Arco (basket): TACAN 19X; 253.2Mhz AM ", 60, false) 
		trigger.action.outText("   Texaco (boom): TACAN 18X; 251.5Mhz AM ", 60, false)
	elseif missionType == 3 and missionSubType == 1 then
		trigger.action.outText("CALLSIGN: ", 60, true) 
		trigger.action.outText("   Players: Eco 18 ", 60, false) 
		trigger.action.outText("   Comboy: " .. nameComboyGroup, 60, false) 
		trigger.action.outText("FREQUENCIES: ", 60, false) 
		trigger.action.outText("   Shiraz International: 121.9Mhz AM, 250.35Mhz ", 60, false)
		trigger.action.outText("   FARP Base (London): 128.5Mhz AM ", 60, false)
		trigger.action.outText("   FARP Base (Madrid): 130.25Mhz AM ", 60, false)
		trigger.action.outText("   FARP Base (Paris): 135.55Mhz AM ", 60, false)	
		trigger.action.outText("AWACS: ", 60, false) 
		trigger.action.outText("   Overlord: 301.3Mhz AM ", 60, false)
	elseif missionType == 3 and missionSubType == 2 then
		trigger.action.outText("CALLSIGN: ", 60, true) 
		trigger.action.outText("   Players: Romeo 18 ", 60, false)
		trigger.action.outText("   Enemy camp: Point Tango ", 60, false)				
		trigger.action.outText("FREQUENCIES: ", 60, false) 
		trigger.action.outText("   Shiraz International: 121.9Mhz AM, 250.35Mhz ", 60, false)
		trigger.action.outText("   FARP Base (London): 128.5Mhz AM ", 60, false)
		trigger.action.outText("   FARP Base (Madrid): 130.25Mhz AM ", 60, false)
		trigger.action.outText("   FARP Base (Paris): 135.55Mhz AM ", 60, false)		
		trigger.action.outText("AWACS: ", 60, false)
		trigger.action.outText("   Overlord: 301.3Mhz AM ", 60, false)		
	elseif missionType == 3 and missionSubType == 3 then
		trigger.action.outText("CALLSIGN: ", 60, true)
		trigger.action.outText("   Players: Romeo 25 ", 60, false)
		trigger.action.outText("   Enemy camp: Point Tango ", 60, false) 		
		trigger.action.outText("FREQUENCIES: ", 60, false)
		trigger.action.outText("   Shiraz International: 121.9Mhz AM, 250.35Mhz ", 60, false)
		trigger.action.outText("   FARP Base (London): 128.5Mhz AM ", 60, false)
		trigger.action.outText("   FARP Base (Madrid): 130.25Mhz AM ", 60, false)
		trigger.action.outText("   FARP Base (Paris): 135.55Mhz AM ", 60, false)		
		trigger.action.outText("AWACS: ", 60, false)
		trigger.action.outText("   Overlord: 301.3Mhz AM ", 60, false)
	elseif missionType == 3 and missionSubType == 4 then
		trigger.action.outText("CALLSIGN: ", 60, true) 
		trigger.action.outText("   Players: Alpha 19 ", 60, false)		
		trigger.action.outText("FREQUENCIES: ", 60, false)	
		trigger.action.outText("   Shiraz International: 121.9Mhz AM, 250.35Mhz ", 60, false)	
		trigger.action.outText("   FARP Base (London): 128.5Mhz AM ", 60, false)	
		trigger.action.outText("   FARP Base (Madrid): 130.25Mhz AM ", 60, false)	
		trigger.action.outText("   FARP Base (Paris): 135.55Mhz AM ", 60, false)			
		trigger.action.outText("AWACS: ", 60, false)	
		trigger.action.outText("   Overlord: 301.3Mhz AM ", 60, false)
	elseif missionType == 4 and missionSubType == 1 then
		trigger.action.outText("CALLSIGN: ", 60, true) 
		trigger.action.outText("   Players: Eco 41 ", 60, false)		
		trigger.action.outText("   Drop Area: Point Delta ", 60, false) 		
		trigger.action.outText("FREQUENCIES: ", 60, false)	
		trigger.action.outText("   Shiraz International: 121.9Mhz AM, 250.35Mhz ", 60, false)	
		trigger.action.outText("   FARP Base (London): 128.5Mhz AM ", 60, false)	
		trigger.action.outText("   FARP Base (Madrid): 130.25Mhz AM ", 60, false)	
		trigger.action.outText("   FARP Base (Paris): 135.55Mhz AM ", 60, false)			
		trigger.action.outText("AWACS: ", 60, false)	
		trigger.action.outText("   Overlord: 301.3Mhz AM ", 60, false)
	end
end


function setMissionText(pTipoMission)
	--trigger.action.outText("setMissionText ".. pTipoMission, 3)    
	if pTipoMission == "M1_1" then		
		trigger.action.outText("Scramble!!! Scramble!!! A squadron of enemy aircrafts is heading for Shiraz.", 14) 
		trigger.action.outText("Alert crew: take off at once, contact Overlord to get the target information and destroy hostiles before they get closer.", 14) 		
		trigger.action.outText("CALLSIGN: ", 14) 
		trigger.action.outText("   Players: India 12 ", 14) 
		trigger.action.outText("TIP:(You can request reinforcements through F10 radio menu options. ETA 2min)", 14)			
		trigger.action.outText("TIP:(You can request mission radio frequencies through F10 radio menu options)", 14)			
--		setMessageDelayed("FREQUENCIES: ", 60, 2, false) 
--		setMessageDelayed("   Shiraz International: 121.9Mhz AM, 250.35Mhz ", 60, 2, false)
--		setMessageDelayed("   FARP Base (London): 128.5Mhz AM ", 60, 2, false)
--		setMessageDelayed("   FARP Base (Madrid): 130.25Mhz AM ", 60, 2, false)
--		setMessageDelayed("   FARP Base (Paris): 135.55Mhz AM ", 60, 2, false)		
--		setMessageDelayed("AWACS: ", 60, 2, false) 
--		setMessageDelayed("   Overlord: 301.3Mhz AM ", 60, 2, false)
--		setMessageDelayed("TANKER: ", 60, 2, false) 
--		setMessageDelayed("   Arco (basket): TACAN 19X; 253.2Mhz AM ", 60, 2, false) 
--		setMessageDelayed("   Texaco (boom): TACAN 18X; 251.5Mhz AM ", 60, 2, false) 	

		setSoundDelayed("ScrambleAlarm.ogg", 1)
		
		
	elseif pTipoMission == "M1_2" then
		trigger.action.outText("Scramble!!! Scramble!!! A squadron of enemy bombers is heading for Shiraz.", 29) 		
		trigger.action.outText("Alert crew: take off at once, contact Overlord to get the target information and destroy hostiles before they get closer.", 29) 				
		trigger.action.outText("CALLSIGN: ", 29) 
		trigger.action.outText("   Players: India 50 ", 29) 
		trigger.action.outText("TIP:(You can request reinforcements through F10 radio menu options. ETA 2min)", 29)	
		trigger.action.outText("TIP:(You can request mission radio frequencies through F10 radio menu options)", 29)			
--		setMessageDelayed("FREQUENCIES: ", 60, 2, false) 
--		setMessageDelayed("   Shiraz International: 121.9Mhz AM, 250.35Mhz ", 60, 2, false)
--		setMessageDelayed("   FARP Base (London): 128.5Mhz AM ", 60, 2, false)
--		setMessageDelayed("   FARP Base (Madrid): 130.25Mhz AM ", 60, 2, false)
--		setMessageDelayed("   FARP Base (Paris): 135.55Mhz AM ", 60, 2, false)		
--		setMessageDelayed("AWACS: ", 60, 2, false) 
--		setMessageDelayed("   Overlord: 301.3Mhz AM ", 60, 2, false)
--		setMessageDelayed("TANKER: ", 60, 2, false) 
--		setMessageDelayed("   Arco (basket): TACAN 19X; 253.2Mhz AM ", 60, 2, false) 
--		setMessageDelayed("   Texaco (boom): TACAN 18X; 251.5Mhz AM ", 60, 2, false) 	

		setSoundDelayed("ScrambleAlarm.ogg", 1)	
	elseif pTipoMission == "M1_3" then
		trigger.action.outText("Your task for today is to perform a CAP (Combat Air Patrol) near the Iranian coast line. Be advice that, in the last few days, hostile recon flights has been detected in the region.", 44)
		trigger.action.outText("High command believes that this could be an attempt to obtain tactical information, prior to an attack on our territory. ", 44)		
		trigger.action.outText("The ROE for this mission are to intercept and destroy any hostile aircraft in the region. Choose your payload, take off and follow your asigned route", 44) 				
		trigger.action.outText("CALLSIGN: ", 44) 
		trigger.action.outText("   Players: Charlie 15 ", 44)
		trigger.action.outText("INFO:(You can request CAP coords through F10 radio menu options ONCE IN THE COCKPIT)", 44)				
		trigger.action.outText("TIP:(You can request reinforcements through F10 radio menu options. ETA 2min)", 44)				
		trigger.action.outText("TIP:(You can request temporal relieve for AAR through F10 radio if run out of gas.)", 44)				
		trigger.action.outText("TIP:(You can request mission radio frequencies through F10 radio menu options)", 44)			
--		setMessageDelayed("FREQUENCIES: ", 60, 2, false) 
--		setMessageDelayed("   Shiraz International: 121.9Mhz AM, 250.35Mhz ", 60, 2, false)
--		setMessageDelayed("   FARP Base (London): 128.5Mhz AM ", 60, 2, false)
--		setMessageDelayed("   FARP Base (Madrid): 130.25Mhz AM ", 60, 2, false)
--		setMessageDelayed("   FARP Base (Paris): 135.55Mhz AM ", 60, 2, false)		
--		setMessageDelayed("AWACS: ", 60, 2, false) 
--		setMessageDelayed("   Overlord: 301.3Mhz AM ", 60, 2, false)
--		setMessageDelayed("TANKER: ", 60, 2, false)
--		setMessageDelayed("   Arco (basket): TACAN 19X; 253.2Mhz AM ", 60, 2, false) 
--		setMessageDelayed("   Texaco (boom): TACAN 18X; 251.5Mhz AM ", 60, 2, false)		
				
	elseif pTipoMission == "M1_4" then
		trigger.action.outText("A nearby ally country has informed that a rebel faction of their military has stolen a squadron of fighters from one of their bases. This faction is hostile to our country and want to launch an attack on our capital in order to initiate a war between both countries.", 44)		
		trigger.action.outText("Fortunately, it seems that the stolen fighters belongs to a nearly retired squadron, composed of old fighters, and the rebels were not able to arm them with missiles before their coup.", 44)		
		trigger.action.outText("Hostiles are trying to sneak through our territory and for now we haven't detected them. Take off and wait for further orders.", 44)		
		trigger.action.outText("CALLSIGN: ", 44) 
		trigger.action.outText("   Players: India 27 ", 44)  
		trigger.action.outText("TIP:(You can request aditional interceptors through F10 radio menu options, preferably before init taxi to runway)", 44)				
		trigger.action.outText("TIP:(You can request mission radio frequencies through F10 radio menu options)", 44)			
--		setMessageDelayed("FREQUENCIES: ", 60, 2, false) 
--		setMessageDelayed("   Shiraz International: 121.9Mhz AM, 250.35Mhz ", 60, 2, false)
--		setMessageDelayed("   FARP Base (London): 128.5Mhz AM ", 60, 2, false)
--		setMessageDelayed("   FARP Base (Madrid): 130.25Mhz AM ", 60, 2, false)
--		setMessageDelayed("   FARP Base (Paris): 135.55Mhz AM ", 60, 2, false)		
--		setMessageDelayed("AWACS: ", 60, 2, false) 
--		setMessageDelayed("   Overlord: 301.3Mhz AM ", 60, 2, false)
--		setMessageDelayed("TANKER: ", 60, 2, false)
--		setMessageDelayed("   Arco (basket): TACAN 19X; 253.2Mhz AM ", 60, 2, false) 
--		setMessageDelayed("   Texaco (boom): TACAN 18X; 251.5Mhz AM ", 60, 2, false)
	elseif pTipoMission == "M1_5" then
		trigger.action.outText("Scramble!!! Scramble!!! An unidentified aircraft has been detected heading for Shiraz and is not answering to our calls.", 29) 		
		trigger.action.outText("Alert crew: take off at once, contact Overlord to get the target information, intercept and identify before it get closer.", 29) 		
		trigger.action.outText("ROE: Weapons cold until command authorize to attack the target", 29)							
		trigger.action.outText("CALLSIGN: ", 29) 
		trigger.action.outText("   Players: India 25 ", 29)  
		trigger.action.outText("INFO:(You can intercept and identify target through F10 radio menu options)", 29)			
		trigger.action.outText("TIP:(You can request mission radio frequencies through F10 radio menu options)", 29)	
--		setMessageDelayed("FREQUENCIES: ", 60, 2, false) 
--		setMessageDelayed("   Shiraz International: 121.9Mhz AM, 250.35Mhz ", 60, 2, false)
--		setMessageDelayed("   FARP Base (London): 128.5Mhz AM ", 60, 2, false)
--		setMessageDelayed("   FARP Base (Madrid): 130.25Mhz AM ", 60, 2, false)
--		setMessageDelayed("   FARP Base (Paris): 135.55Mhz AM ", 60, 2, false)		
--		setMessageDelayed("AWACS: ", 60, 2, false) 
--		setMessageDelayed("   Overlord: 301.3Mhz AM ", 60, 2, false)
--		setMessageDelayed("TANKER: ", 60, 2, false)
--		setMessageDelayed("   Arco (basket): TACAN 19X; 253.2Mhz AM ", 60, 2, false) 
--		setMessageDelayed("   Texaco (boom): TACAN 18X; 251.5Mhz AM ", 60, 2, false)
		
		setSoundDelayed("ScrambleAlarm.ogg", 1)	
		
	elseif pTipoMission == "M2_1" then
		trigger.action.outText("An ally comboy has requested us to escort them in their route through enemy territory. Rendevouz with them at point Omega and proceed with a CAS (Close Air Support) task along the comboy's route. Their callsign will be " .. nameComboyGroup, 34) 
		trigger.action.outText("Be advice: their valuable cargo is a juicy target for any faction operating in the area, so expect heavy resistance", 34)						
		trigger.action.outText("CALLSIGN: ", 34) 
		trigger.action.outText("   Players: Eco 11 ", 34) 
		trigger.action.outText("   Comboy: " .. nameComboyGroup, 34) 
		trigger.action.outText("INFO:(ONCE IN THE COCKPIT, using F10 radio menu, you can request the coords of the comboy when you want to establish its position at any time)", 34)				
		trigger.action.outText("TIP:(The comboy's planned route can be viewed in the F10 map, if you click on the comboy)", 34)
		trigger.action.outText("TIP:(You can order the comboy to stop the route and wait, if you need to rearm and refuel)", 34)
		trigger.action.outText("TIP:(You can request a backup escort, if you want to leave the mission, but you will not earn IBCs for a sucessful mission)", 34)
		trigger.action.outText("TIP:(You can request mission radio frequencies through F10 radio menu options)", 34)	
--		setMessageDelayed("FREQUENCIES: ", 60, 2, false) 
--		setMessageDelayed("   Shiraz International: 121.9Mhz AM, 250.35Mhz ", 60, 2, false)
--		setMessageDelayed("   FARP Base (London): 128.5Mhz AM ", 60, 2, false)
--		setMessageDelayed("   FARP Base (Madrid): 130.25Mhz AM ", 60, 2, false)
--		setMessageDelayed("   FARP Base (Paris): 135.55Mhz AM ", 60, 2, false)		
--		setMessageDelayed("AWACS: ", 60, 2, false) 
--		setMessageDelayed("   Overlord: 301.3Mhz AM ", 60, 2, false)
--		setMessageDelayed("TANKER: ", 60, 2, false) 
--		setMessageDelayed("   Arco (basket): TACAN 19X; 253.2Mhz AM ", 60, 2, false) 
--		setMessageDelayed("   Texaco (boom): TACAN 18X; 251.5Mhz AM ", 60, 2, false) 
		
	elseif pTipoMission == "M2_2" then 	
		trigger.action.outText("After a previous sucessful recon mission, we have been able to pin poin one of the main campaments one of the enemy factions operating in the area has established.", 34) 
		trigger.action.outText("Command has chosen a " .. varCampTargetName .. " located into this campament as most valuable target. Your mission is to destroy it.", 34) 
		trigger.action.outText("The campament could be protected by SAM emplacements, so be careful.", 34)						
		trigger.action.outText("CALLSIGN: ", 34) 
		trigger.action.outText("   Players: Romeo 71 ", 34)
		trigger.action.outText("   Enemy camp: Point Tango ", 34)
		trigger.action.outText("INFO:(You can request the campament coords through F10 radio menu options ONCE IN THE COCKPIT)", 34)				
		trigger.action.outText("TIP:(You can request mission radio frequencies through F10 radio menu options)", 34)	
--		setMessageDelayed("FREQUENCIES: ", 60, 2, false)
--		setMessageDelayed("   Shiraz International: 121.9Mhz AM, 250.35Mhz ", 60, 2, false)
--		setMessageDelayed("   FARP Base (London): 128.5Mhz AM ", 60, 2, false)
--		setMessageDelayed("   FARP Base (Madrid): 130.25Mhz AM ", 60, 2, false)
--		setMessageDelayed("   FARP Base (Paris): 135.55Mhz AM ", 60, 2, false)		
--		setMessageDelayed("AWACS: ", 60, 2, false) 
--		setMessageDelayed("   Overlord: 301.3Mhz AM ", 60, 2, false)
--		setMessageDelayed("TANKER: ", 60, 2, false) 
--		setMessageDelayed("   Arco (basket): TACAN 19X; 253.2Mhz AM ", 60, 2, false) 
--		setMessageDelayed("   Texaco (boom): TACAN 18X; 251.5Mhz AM ", 60, 2, false) 
		
	elseif pTipoMission == "M2_3" then 	
		trigger.action.outText("Our next target is a campament that one of the enemy factions operating in the area has established.", 34)
		trigger.action.outText("Previous surveillance flights have found that this campament is protected by AAA and SAMs systems, so we must soften the defenses before the attack.", 34)
		trigger.action.outText("You are order to destroy the SAMs defenses protecting an enemy camp. Engage AAA as a TOO if possible.", 34)				
		trigger.action.outText("CALLSIGN: ", 34) 
		trigger.action.outText("   Players: Romeo 18 ", 34) 
		trigger.action.outText("   Enemy camp: Point Tango ", 34) 				
		trigger.action.outText("INFO:(You can request the campament coords through F10 radio menu options ONCE IN THE COCKPIT)", 34)				
		trigger.action.outText("TIP:(You can request mission radio frequencies through F10 radio menu options)", 34)	
--		setMessageDelayed("FREQUENCIES: ", 60, 2, false) 
--		setMessageDelayed("   Shiraz International: 121.9Mhz AM, 250.35Mhz ", 60, 2, false)
--		setMessageDelayed("   FARP Base (London): 128.5Mhz AM ", 60, 2, false)
--		setMessageDelayed("   FARP Base (Madrid): 130.25Mhz AM ", 60, 2, false)
--		setMessageDelayed("   FARP Base (Paris): 135.55Mhz AM ", 60, 2, false)		
--		setMessageDelayed("AWACS: ", 60, 2, false) 
--		setMessageDelayed("   Overlord: 301.3Mhz AM ", 60, 2, false)
--		setMessageDelayed("TANKER: ", 60, 2, false)
--		setMessageDelayed("   Arco (basket): TACAN 19X; 253.2Mhz AM ", 60, 2, false) 
--		setMessageDelayed("   Texaco (boom): TACAN 18X; 251.5Mhz AM ", 60, 2, false)
		
	elseif pTipoMission == "M2_4" then 			
		trigger.action.outText("Command has established the position of a campament that one of the enemy factions operating in the area has established recently.", 34)		
		trigger.action.outText("Your task is recon the area to get some intel on the campament defences and structures.", 34)		
		trigger.action.outText("INFO: (You can request the campament coords through F10 radio menu options ONCE IN THE COCKPIT)", 34)						
		trigger.action.outText("CALLSIGN: ", 34) 
		trigger.action.outText("   Players: Romeo 25 ", 34)
		trigger.action.outText("   Enemy camp: Point Tango ", 34)
		trigger.action.outText("INFO:(MB-339 or T-45 is recomended for this mission)", 34)				
		trigger.action.outText("TIP:(You can request mission radio frequencies through F10 radio menu options)", 34)	
--		setMessageDelayed("FREQUENCIES: ", 60, 2, false) 
--		setMessageDelayed("   Shiraz International: 121.9Mhz AM, 250.35Mhz ", 60, 2, false)
--		setMessageDelayed("   FARP Base (London): 128.5Mhz AM ", 60, 2, false)
--		setMessageDelayed("   FARP Base (Madrid): 130.25Mhz AM ", 60, 2, false)
--		setMessageDelayed("   FARP Base (Paris): 135.55Mhz AM ", 60, 2, false)		
--		setMessageDelayed("AWACS: ", 60, 2, false) 
--		setMessageDelayed("   Overlord: 301.3Mhz AM ", 60, 2, false)
--		setMessageDelayed("TANKER: ", 60, 2, false) 
--		setMessageDelayed("   Arco (basket): TACAN 19X; 253.2Mhz AM ", 60, 2, false) 
--		setMessageDelayed("   Texaco (boom): TACAN 18X; 251.5Mhz AM ", 60, 2, false)
		
	elseif pTipoMission == "M3_1" then 	
		trigger.action.outText("An ally comboy has requested us to escort them in their route through enemy territory. Rendevouz with them at point Omega and proceed with a CAS (Close Air Support) task along the comboy's route. Their callsign will be " .. nameComboyGroup, 34) 
		trigger.action.outText("Be advice: their valuable cargo is a juicy target for any faction operating in the area, so expect heavy resistance", 34)						
		trigger.action.outText("CALLSIGN: ", 34) 
		trigger.action.outText("   Players: Eco 18 ", 34) 
		trigger.action.outText("   Comboy: " .. nameComboyGroup, 34) 
		trigger.action.outText("INFO: (This is a helicopter mission)", 34)
		trigger.action.outText("INFO:(ONCE IN THE COCKPIT, using F10 radio menu, you can request the coords of the comboy when you want to establish its position at any time)", 34)				
		trigger.action.outText("TIP:(The comboy's planned route can be viewed in the F10 map, if you click on the comboy)", 34)
		trigger.action.outText("TIP:(you can request a backup escort, if you want to leave the mission, but you will not earn IBCs for a sucessful mission)", 34)
		trigger.action.outText("TIP:(You can request mission radio frequencies through F10 radio menu options)", 34)	
--		setMessageDelayed("FREQUENCIES: ", 60, 2, false) 
--		setMessageDelayed("   Shiraz International: 121.9Mhz AM, 250.35Mhz ", 60, 2, false)
--		setMessageDelayed("   FARP Base (London): 128.5Mhz AM ", 60, 2, false)
--		setMessageDelayed("   FARP Base (Madrid): 130.25Mhz AM ", 60, 2, false)
--		setMessageDelayed("   FARP Base (Paris): 135.55Mhz AM ", 60, 2, false)	
--		setMessageDelayed("AWACS: ", 60, 2, false) 
--		setMessageDelayed("   Overlord: 301.3Mhz AM ", 60, 2, false)
		
	elseif pTipoMission == "M3_2" then 			
		trigger.action.outText("Our next target is a campament that one of the enemy factions operating in the area has established.", 34)
		trigger.action.outText("Previous surveillance flights have found that this campament is protected by AAA and SAMs systems, so we must soften the defenses before the attack.", 34)
		trigger.action.outText("You are order to destroy the SAMs defenses protecting an enemy camp. Engage AAA as a TOO if possible.", 34)				
		trigger.action.outText("CALLSIGN: ", 34) 
		trigger.action.outText("   Players: Romeo 18 ", 34)
		trigger.action.outText("   Enemy camp: Point Tango ", 34)				
		trigger.action.outText("INFO:(You can request the campament coords through F10 radio menu options ONCE IN THE COCKPIT of the helicopter)", 34)
		trigger.action.outText("INFO:(This is a helicopter mission)", 34)
		trigger.action.outText("TIP:(You can request mission radio frequencies through F10 radio menu options)", 34)	
--		setMessageDelayed("FREQUENCIES: ", 60, 2, false) 
--		setMessageDelayed("   Shiraz International: 121.9Mhz AM, 250.35Mhz ", 60, 2, false)
--		setMessageDelayed("   FARP Base (London): 128.5Mhz AM ", 60, 2, false)
--		setMessageDelayed("   FARP Base (Madrid): 130.25Mhz AM ", 60, 2, false)
--		setMessageDelayed("   FARP Base (Paris): 135.55Mhz AM ", 60, 2, false)		
--		setMessageDelayed("AWACS: ", 60, 2, false)
--		setMessageDelayed("   Overlord: 301.3Mhz AM ", 60, 2, false)
		
	elseif pTipoMission == "M3_3" then 			
		trigger.action.outText("Command has established the position of a campament that one of the enemy factions operating in the area has established recently.", 44)		
		trigger.action.outText("Your task is to act as JTAC for " ..  nameAllyBombersGroup .. " attack group. They will stay orbiting the area until you provide target coordinates for a precision strike on the enemy defences.", 44)		
		trigger.action.outText("Establish a close observation point on the defenses, mark the targets and wait for " .. nameAllyBombersGroup .. " attack on the defences.", 44)		
		trigger.action.outText("Assist the attack at your discretion", 44)			
		trigger.action.outText("CALLSIGN: ", 34)
		trigger.action.outText("   Players: Romeo 25 ", 34)
		trigger.action.outText("   Enemy camp: Point Tango ", 34)
		trigger.action.outText("INFO:(You can request the campament coords through F10 radio menu options ONCE IN THE COCKPIT of the Helicopter)", 44)						
		trigger.action.outText("INFO:(This is a helicopter mission)", 44)			
		trigger.action.outText("TIP:(You must be close to the camp and have line of sight to at least one of the defenders. Then use the radio menu options 'F10 -> misssion' to authorize the attack.)", 44)				
		trigger.action.outText("TIP:(You can request mission radio frequencies through F10 radio menu options)", 44)	
--		setMessageDelayed("FREQUENCIES: ", 60, 2, false)
--		setMessageDelayed("   Shiraz International: 121.9Mhz AM, 250.35Mhz ", 60, 2, false)
--		setMessageDelayed("   FARP Base (London): 128.5Mhz AM ", 60, 2, false)
--		setMessageDelayed("   FARP Base (Madrid): 130.25Mhz AM ", 60, 2, false)
--		setMessageDelayed("   FARP Base (Paris): 135.55Mhz AM ", 60, 2, false)		
--		setMessageDelayed("AWACS: ", 60, 2, false)
--		setMessageDelayed("   Overlord: 301.3Mhz AM ", 60, 2, false)
		
	elseif pTipoMission == "M3_4" then 			
		trigger.action.outText("We have received recently reports of an enemy comboy transporting armament. Surveillance has located the target near one of our FARPs.", 34)		
		trigger.action.outText("You are ordered to take off, get the possition of the target and destroy the armament. Good hunting", 34)						
		trigger.action.outText("CALLSIGN: ", 34) 
		trigger.action.outText("   Players: Alpha 19 ", 34)		
		trigger.action.outText("INFO:(You can request the target coords through F10 radio menu options ONCE IN THE COCKPIT of the Helicopter)", 34)				
		trigger.action.outText("INFO:(This is a helicopter mission)", 34)		
		trigger.action.outText("TIP:(You can request mission radio frequencies through F10 radio menu options)", 34)	
--		setMessageDelayed("FREQUENCIES: ", 60, 2, false)	
--		setMessageDelayed("   Shiraz International: 121.9Mhz AM, 250.35Mhz ", 60, 2, false)	
--		setMessageDelayed("   FARP Base (London): 128.5Mhz AM ", 60, 2, false)	
--		setMessageDelayed("   FARP Base (Madrid): 130.25Mhz AM ", 60, 2, false)	
--		setMessageDelayed("   FARP Base (Paris): 135.55Mhz AM ", 60, 2, false)			
--		setMessageDelayed("AWACS: ", 60, 2, false)	
--		setMessageDelayed("   Overlord: 301.3Mhz AM ", 60, 2, false)

	elseif pTipoMission == "M4_1" then 			
		trigger.action.outText("At last our scouts have been able to pinpoint the location of the enemy commander of one of the rebel factions operating in our territory.", 54)				
		trigger.action.outText("He and a small band of partisans hide among the caves that exist in the area, so an air attack has been discarted.", 54)				
		trigger.action.outText("Your mission is to transport some combat vehicles to this area, to allow our scout forces to attack the partisan perimeter defenses.", 54)				
		trigger.action.outText("Get to the drop zone and perform a Low Speed Airdrop of 3 BMD-1 transports. Our forces will mark the area with green smoke on your command.", 54)
		trigger.action.outText("CALLSIGN: ", 34) 
		trigger.action.outText("   Players: Eco 41 ", 34)		
		trigger.action.outText("   Drop Area: Point Delta ", 34) 		
		trigger.action.outText("INFO:(You can request the area coords through F10 radio menu options ONCE IN THE COCKPIT of the aircraft)", 54)				
		trigger.action.outText("INFO:(This is a C-130 Hercules mission)", 54)		
		trigger.action.outText("TIP:(Do not land in the drop area. You are ordered to release the cargo in flight)", 54)
		trigger.action.outText("TIP:(You can request mission radio frequencies through F10 radio menu options)", 34)	
--		setMessageDelayed("FREQUENCIES: ", 60, 2, false)	
--		setMessageDelayed("   Shiraz International: 121.9Mhz AM, 250.35Mhz ", 60, 2, false)	
--		setMessageDelayed("   FARP Base (London): 128.5Mhz AM ", 60, 2, false)	
--		setMessageDelayed("   FARP Base (Madrid): 130.25Mhz AM ", 60, 2, false)	
--		setMessageDelayed("   FARP Base (Paris): 135.55Mhz AM ", 60, 2, false)			
--		setMessageDelayed("AWACS: ", 60, 2, false)	
--		setMessageDelayed("   Overlord: 301.3Mhz AM ", 60, 2, false)
		
	end
	
end


function setMissionType(pmissionType)

	--trigger.action.outText("pmissionType: " .. pmissionType, 10)			
	
	if pmissionType == 0 then		
		pmissionType = math.random(1,4)		
	end
		
	missionType = pmissionType
	
	
	missionCommands.removeItem(menuPrinc)
	missionCommands.removeItem(menuPrinc2)
	
	if pmissionType == 1 then
		-- Aircraft A2A
		missionSubType = math.random(1,5) --rndType
		if missionSubType == 1 then
			-- Interception hostiles fighters attacking AWACs			
			hostileAirGroup = createHostilesAirGroup({x = VarPosOriginal.x, y = VarPosOriginal.z}, 180000, 220000)			
			hostileAttackAWACS(hostileAirGroup, Group.getByName("Overlord"))
			isHostilesAirGroupCreated = true;
			
			if getNumberOfPlayers() >= 4 then
				local mainGroupPos = hostileAirGroup:getUnit(1):getPoint()
				hostileAirGroupExtra = createHostilesAirGroupExtra({x = mainGroupPos.x, y = mainGroupPos.z}, 180000, 200)
				isHostilesAirGroupExtraCreated = true;
			end
			
			setMissionText("M1_1")
			
			menuPrinc1 = missionCommands.addSubMenu('Request...')			
			menuReqBalance = missionCommands.addCommand('Accounting Balance', menuPrinc1, getFinances, nil)
			menuReqFreq = missionCommands.addCommand('Request Radio Freq', menuPrinc1, getRadioFreq, nil)
			menuReqHelp = missionCommands.addCommand('Request reinforcements (ETA 2min)', menuPrinc1, requestEscort, nil)
			menuReqTanker = missionCommands.addCommand('Request Tanker', menuPrinc1, requestTankers, nil)
			
			
			
		elseif missionSubType == 2 then
			-- Interception hostiles bombers attacking Runway			
			local attackers = createHostilesBomberGroup({x = VarPosOriginal.x, y = VarPosOriginal.z}, 180000, 220000)			
			hostileAirGroup = attackers.HostileEscortGroup
			hostileBomberGroup = attackers.HostileBomberGroup			
			isHostilesAirGroupCreated = true;
			isHostilesBomberGroupCreated = true;
			
			if getNumberOfPlayers() >= 4 then
				local mainGroupPos = hostileAirGroup:getUnit(1):getPoint()
				hostileAirGroupExtra = createHostilesAirGroupExtra({x = mainGroupPos.x, y = mainGroupPos.z}, 180000, 200)
				isHostilesAirGroupExtraCreated = true;
			end
			
			setMissionText("M1_2")
			
			menuPrinc1 = missionCommands.addSubMenu('Request...')			
			menuReqBalance = missionCommands.addCommand('Accounting Balance', menuPrinc1, getFinances, nil)
			menuReqFreq = missionCommands.addCommand('Request Radio Freq', menuPrinc1, getRadioFreq, nil)
			menuReqTanker = missionCommands.addCommand('Request Tanker', menuPrinc1, requestTankers, nil)
			menuReqHelp = missionCommands.addCommand('Request reinforcements (ETA 2min)', menuPrinc1, requestEscort, nil)			
			
		elseif missionSubType == 3 then
			-- CAP con random event		
			setMissionText("M1_3")
			menuPrinc1 = missionCommands.addSubMenu('Request...')			
			menuReqBalance = missionCommands.addCommand('Accounting Balance', menuPrinc1, getFinances, nil)
			menuReqFreq = missionCommands.addCommand('Request Radio Freq', menuPrinc1, getRadioFreq, nil)
			menuReqCoord = missionCommands.addCommand('Request CAP coordinates', menuPrinc1, loadPlayerCAP, nil)
			menuReqTanker = missionCommands.addCommand('Request Tanker', menuPrinc1, requestTankers, nil)
			menuReqHelp = missionCommands.addCommand('Request reinforcements (ETA 2min)', menuPrinc1, requestEscort, nil)
			menuReqAAR = missionCommands.addCommand('Request backup for AAR', menuPrinc1, requestCAPbackUp, nil)
			
			
		elseif missionSubType == 4 then
			-- Swarm hostiles attack
			--los enemigos se crean en un evento cuando despega el jugador
			--trigger.action.outText("aqui", 3)    
			setMissionText("M1_4")
			
			menuPrinc1 = missionCommands.addSubMenu('Request...')	
			menuReqBalance = missionCommands.addCommand('Accounting Balance', menuPrinc1, getFinances, nil)
			menuReqFreq = missionCommands.addCommand('Request Radio Freq', menuPrinc1, getRadioFreq, nil)
			menuReqTanker = missionCommands.addCommand('Request Tanker', menuPrinc1, requestTankers, nil)			
			menuReqHelp = missionCommands.addCommand('Request Support Flight', menuPrinc1, createAllyAirGroup, nil)
			
		elseif missionSubType == 5 then
			-- escort Civilian aircraft			
			civilAirGroup = createCivilAirGroup({x = 381075.66519277, y = -350696.1185350}, 180000, 200000)			
			--civilAirGroup = createCivilAirGroup({x = 456191, y = -42463}, 100, 80000)
			
			setAirRoute(civilAirGroup, {x = civilAirGroup:getUnit(1):getPoint().x, y = civilAirGroup:getUnit(1):getPoint().z, z = civilAirGroup:getUnit(1):getPoint().y}, {x = 381075.66519277 , z = 6000, y = -350696.1185350}, 200)
			isCivilAirGroupCreated = true			
			setMissionText("M1_5")
			
			menuPrinc1 = missionCommands.addSubMenu('Request...')	
			menuReqBalance = missionCommands.addCommand('Accounting Balance', menuPrinc1, getFinances, nil)			
			menuReqFreq = missionCommands.addCommand('Request Radio Freq', menuPrinc1, getRadioFreq, nil)
			menuReqTanker = missionCommands.addCommand('Request Tanker', menuPrinc1, requestTankers, nil)
			menuPrinc3 = missionCommands.addSubMenu('Other Commands...')								
			menuOtherInterceptCiv = missionCommands.addCommand('Intercept civil aircraft (request intentions)', menuPrinc3, interceptCivilAircraft, nil)			
		end
	elseif pmissionType == 2 then
		-- Aircraft A2G
		missionSubType = math.random(1,4) --rndType
		if missionSubType == 1 then
			-- comboy escort			
			comboyAllyGroup = createComboy(VarPosOriginal, 100000, true)
			isComboyCreated = true;	
			
			--se calcula la ruta del comboy, pero se pone en stop hasta nueva orden								
			destinationComboy = setDestiny(comboyAllyGroup, 4000, true, 1)
			local PosGroup = comboyAllyGroup:getUnit(1):getPoint()		
			originComboy = {x = PosGroup.x, y = PosGroup.z}
			setGroundRoute(comboyAllyGroup, originComboy, destinationComboy, 40, true)			
			setComboyStop(comboyAllyGroup)
							
			
			setMissionText("M2_1")
							
			menuPrinc1 = missionCommands.addSubMenu('Request...')			
			menuReqBalance = missionCommands.addCommand('Accounting Balance', menuPrinc1, getFinances, nil)
			menuReqFreq = missionCommands.addCommand('Request Radio Freq', menuPrinc1, getRadioFreq, nil)
			menuReqTanker = missionCommands.addCommand('Request Tanker', menuPrinc1, requestTankers, nil)			
			menurequestBackup = missionCommands.addCommand('Backup escort (end mission)', menuPrinc1, RequestBackUp, nil)
			menuPrinc2 = missionCommands.addSubMenu('Comboy...')
			menuReqCoord = missionCommands.addCommand('Request coordinates', menuPrinc2, loadComboyCoordinates, nil)			
			menuProcRoute = missionCommands.addCommand('Proceed with route', menuPrinc2, setRouteAllyComboy, true)	
			menuPrinc3 = missionCommands.addSubMenu('Other Commands...')								
		elseif missionSubType == 2 then
			-- destroy campament
			createHostileCampament({x = VarPosOriginal.x, y = VarPosOriginal.z }, 0, 0, 1)
			
			timer.scheduleFunction(createSAMRouteCampament, nil, timer.getTime() + math.random(400, 700))					
			
			setMissionText("M2_2")
			
			menuPrinc1 = missionCommands.addSubMenu('Request...')			
			menuReqBalance = missionCommands.addCommand('Accounting Balance', menuPrinc1, getFinances, nil)
			menuReqFreq = missionCommands.addCommand('Request Radio Freq', menuPrinc1, getRadioFreq, nil)
			menuReqCoordCamp = missionCommands.addCommand('Request coordinates', menuPrinc1, loadCampCoordinates, nil)			
			menuReqTanker = missionCommands.addCommand('Request Tanker', menuPrinc1, requestTankers, nil)
			menuReqSatellite = missionCommands.addCommand('Request Satellite', menuPrinc1, requestSatellite, {x = CampStaticTarget:getPoint().x, y = CampStaticTarget:getPoint().z})
			menuReqSEAD = missionCommands.addCommand('Request SEAD mission in target', menuPrinc1, requestSEAD, CampSAMTarget)
			--menutemp = missionCommands.addCommand('Destruir objetivos', menuPrinc2, tempDestObj, nil)
		elseif missionSubType == 3 then
			-- destroy campament SAM
			createHostileCampament({x = VarPosOriginal.x, y = VarPosOriginal.z }, 1, 0, 1)
			
			timer.scheduleFunction(createSAMRouteCampament, nil, timer.getTime() + math.random(400, 700))			
			
			setMissionText("M2_3")
			
			menuPrinc1 = missionCommands.addSubMenu('Request...')			
			menuReqBalance = missionCommands.addCommand('Accounting Balance', menuPrinc1, getFinances, nil)
			menuReqFreq = missionCommands.addCommand('Request Radio Freq', menuPrinc1, getRadioFreq, nil)
			menuReqCoordCamp = missionCommands.addCommand('Request coordinates', menuPrinc1, loadCampCoordinates, nil)			
			menuReqTanker = missionCommands.addCommand('Request Tanker', menuPrinc1, requestTankers, nil)
			menuReqSatellite = missionCommands.addCommand('Request Satellite', menuPrinc1, requestSatellite, {x = CampStaticTarget:getPoint().x, y = CampStaticTarget:getPoint().z})
			--menutemp = missionCommands.addCommand('Destruir objetivos', menuPrinc2, tempDestObj, nil)
		elseif missionSubType == 4 then
			-- recon campament
			createHostileCampament({x = VarPosOriginal.x, y = VarPosOriginal.z }, -1, 0, 1)
			
			timer.scheduleFunction(createSAMRouteCampament, nil, timer.getTime() + math.random(400, 700))			
			
			setMissionText("M2_4")
			
			menuPrinc1 = missionCommands.addSubMenu('Request...')			
			menuReqBalance = missionCommands.addCommand('Accounting Balance', menuPrinc1, getFinances, nil)
			menuReqFreq = missionCommands.addCommand('Request Radio Freq', menuPrinc1, getRadioFreq, nil)
			menuReqCoordCamp = missionCommands.addCommand('Request coordinates', menuPrinc1, loadCampCoordinates, nil)			
			menuReqTanker = missionCommands.addCommand('Request Tanker', menuPrinc1, requestTankers, nil)
			menuPrinc3 = missionCommands.addSubMenu('Other Commands...')								
			menuReconCamp = missionCommands.addCommand('recon campament', menuPrinc3, reconCampament, nil)			
		else
			trigger.action.outText("ERROR: no mission set!!!!", 10) 	
		end	
	elseif pmissionType == 3 then		
		-- Helo A2G
		missionSubType = math.random(1,4) --rndType
		if missionSubType == 1 then
			-- comboy escort						
			comboyAllyGroup = createComboy(VarPosOriginal, 20000, true)
			isComboyCreated = true;
			
			--se calcula la ruta del comboy, pero se pone en stop hasta nueva orden								
			destinationComboy = setDestiny(comboyAllyGroup, 4000, true, 0.5)
			local PosGroup = comboyAllyGroup:getUnit(1):getPoint()		
			originComboy = {x = PosGroup.x, y = PosGroup.z}
			setGroundRoute(comboyAllyGroup, originComboy, destinationComboy, 40, true)			
			setComboyStop(comboyAllyGroup)
			
			setMissionText("M3_1")
								
			menuPrinc1 = missionCommands.addSubMenu('Request...')			
			menuReqBalance = missionCommands.addCommand('Accounting Balance', menuPrinc1, getFinances, nil)
			menuReqFreq = missionCommands.addCommand('Request Radio Freq', menuPrinc1, getRadioFreq, nil)
			menurequestBackup = missionCommands.addCommand('Backup escort (end mission)', menuPrinc1, RequestBackUp, nil)
			menuPrinc2 = missionCommands.addSubMenu('Comboy...')
			menuReqCoord = missionCommands.addCommand('Request coordinates', menuPrinc2, loadComboyCoordinates, nil)
			menuProcRoute = missionCommands.addCommand('Proceed with route', menuPrinc2, setRouteAllyComboy, true)
			menuPrinc3 = missionCommands.addSubMenu('Other Commands...')								
		elseif missionSubType == 2 then
			-- destroy campament SAM
			createHostileCampament({x = VarPosOriginal.x, y = VarPosOriginal.z }, 1, 1, 1)
			
			setMissionText("M3_2")
			
			menuPrinc2 = missionCommands.addSubMenu('Request...')			
			menuReqBalance = missionCommands.addCommand('Accounting Balance', menuPrinc2, getFinances, nil)
			menuReqFreq = missionCommands.addCommand('Request Radio Freq', menuPrinc1, getRadioFreq, nil)
			menuReqCoordCamp = missionCommands.addCommand('Request coordinates', menuPrinc2, loadCampCoordinates, nil)			
			menuReqSatellite = missionCommands.addCommand('Request Satellite', menuPrinc1, requestSatellite, {x = CampStaticTarget:getPoint().x, y = CampStaticTarget:getPoint().z})
			--menutemp = missionCommands.addCommand('Destruir objetivos', menuPrinc2, tempDestObj, nil)	
		elseif missionSubType == 3 then
			-- Spotter			
			setOriginLocalizated(1)			
			createHostileCampament({x = VarPosOriginal.x, y = VarPosOriginal.z }, -1, 2, 2)
			nameAllyBombersGroup = getAirCallsign()
			
			setMissionText("M3_3")
										
			menuPrinc2 = missionCommands.addSubMenu('Mission...')
			menuSpotTargets = missionCommands.addCommand('Mark targets and autorize attack', menuPrinc2, markTargetsBombing, nil)	
			menuPrinc1 = missionCommands.addSubMenu('Request...')			
			menuReqBalance = missionCommands.addCommand('Accounting Balance', menuPrinc1, getFinances, nil)
			menuReqFreq = missionCommands.addCommand('Request Radio Freq', menuPrinc1, getRadioFreq, nil)
			menuReqCoordCamp = missionCommands.addCommand('Request coordinates', menuPrinc1, loadCampCoordinates, nil)			
			menuReqSatellite = missionCommands.addCommand('Request Satellite', menuPrinc1, requestSatellite, {x = CampStaticTarget:getPoint().x, y = CampStaticTarget:getPoint().z})
		elseif missionSubType == 4 then	
			--attack comboy directly			
			setOriginLocalizated(2)
			local xHostiles = VarPosOriginal.x + math.random(-20000, 20000)
			local yHostiles = VarPosOriginal.z + math.random(-20000, 20000)
			local heading = math.random(259)
						
			comboyAttackerGroup = createComboyAttackers({x = xHostiles, y = yHostiles}, 1, 8)			
			isEnemyComboyCreated = true
			
			local hostileDestination = {x = xHostiles + math.random(-35000, 35000), y = yHostiles + math.random(-35000, 35000)}
			local distance = getDistancePointPoint({x = xHostiles, y = yHostiles}, hostileDestination)			
			--trigger.action.outText("distance: " .. distance, 10) 
			local counter = 0
			while distance < 17000 and counter < 10 do
				--trigger.action.outText("distance: " .. distance .. "; counter: " .. counter, 10) 				
				hostileDestination = {x = xHostiles + math.random(-35000, 35000), y = yHostiles + math.random(-35000, 35000)}
				distance = getDistancePointPoint({x = xHostiles, y = yHostiles}, hostileDestination)			
				counter = counter +1 
			end
			
			setGroundRoute(comboyAttackerGroup, {x = xHostiles, y = yHostiles}, hostileDestination, 20, 1)
										
			menuPrinc1 = missionCommands.addSubMenu('Request...')			
			menuReqBalance = missionCommands.addCommand('Accounting Balance', menuPrinc1, getFinances, nil)
			menuReqFreq = missionCommands.addCommand('Request Radio Freq', menuPrinc1, getRadioFreq, nil)
			menuReqCoordCamp = missionCommands.addCommand('Request hostiles last coordinates', menuPrinc1, loadHostileComboyCoordinates, nil)			
			
			setMissionText("M3_4")			
		else
			trigger.action.outText("ERROR: no mission set!!!!", 10) 	
		end			
	
	elseif pmissionType == 4 then
		--Hercules
		missionSubType = math.random(1,1) --rndType
		if missionSubType == 1 then
			-- Air drop BDM-1
			menuPrinc1 = missionCommands.addSubMenu('Request...')
			menuReqCoordDrop = missionCommands.addCommand('Request Drop Zone coordinates', menuPrinc1, loadCombatDropCoordinates, nil)			
			menuReqDropZoneSmoke = missionCommands.addCommand('Mark zone with green smoke', menuPrinc1, markDropZoneSmoke, nil)			
			menuReqBalance = missionCommands.addCommand('Accounting Balance', menuPrinc1, getFinances, nil)
			menuReqFreq = missionCommands.addCommand('Request Radio Freq', menuPrinc1, getRadioFreq, nil)
			
			allyTroopsGroup = createAllyTroops(VarPosOriginal, 120000, 100000)
			
			setMissionText("M4_1")			
		end
		
	else
		trigger.action.outText("Work in progress", 10) 	
		addInitialMenu()
	end
end;


function addInitialMenu()
	--trigger.action.outText("addInitialMenu", 3) 
	menuPrinc = missionCommands.addSubMenu('Choose your task for today...')
	N11 = missionCommands.addCommand('Fighter Aircraft (A2A)', menuPrinc, setMissionType, 1)
	N12 = missionCommands.addCommand('Attack Aircraft (A2G)', menuPrinc, setMissionType, 2)
	N13 = missionCommands.addCommand('Attack Helo (A2G)', menuPrinc, setMissionType, 3)	
	N14 = missionCommands.addCommand('Transport Aircraft', menuPrinc, setMissionType, 4)	
	--N15 = missionCommands.addCommand('Transport Helo', menuPrinc, setMissionType, 5)	
	N16 = missionCommands.addCommand('Random mission type', menuPrinc, setMissionType, 0)		
	menuPrinc2 = missionCommands.addSubMenu('Request...')
	menuReqBalance = missionCommands.addCommand('Accounting Balance', menuPrinc2, getFinances, nil)
end;


function tempDestObj()	
	--trigger.action.explosion(CampStaticTarget:getPoint(), 1000)
	trigger.action.explosion(CampSAMTarget:getUnit(1):getPoint(), 100)
	trigger.action.explosion(CampSAMTarget:getUnit(2):getPoint(), 100)
	trigger.action.explosion(CampSAMTarget:getUnit(3):getPoint(), 100)
end


function getFinances()		
	trigger.action.outText("Current balance: " .. AccountingBalance .. " IBCs", 10, true) 		
end


function setNextMission()
	if Mission1Done == false and AccountingBalance >= 500000 then
		trigger.action.setUserFlag(10,100)
		trigger.action.outSoundForCoalition(coalition.side.BLUE, "historyMissionWarning.ogg")	
		trigger.action.outText("Next mission after current one: history mission1", 20) 	
		
	elseif Mission1Done == true and Mission2Done == false and AccountingBalance >= 1000000 then
		trigger.action.setUserFlag(10,99)
		trigger.action.outSoundForCoalition(coalition.side.BLUE, "historyMissionWarning.ogg")	
		trigger.action.outText("Next mission after current one: history mission2", 20) 	
		
	elseif Mission1Done == true and Mission2Done == true and Mission3Done == false and AccountingBalance >= 1500000 then
		trigger.action.setUserFlag(10,98)
		trigger.action.outSoundForCoalition(coalition.side.BLUE, "historyMissionWarning.ogg")	
		trigger.action.outText("Next mission after current one: history mission3", 20) 	
		
    elseif Mission1Done == true and Mission2Done == true and Mission3Done == true and Mission4Done == false and AccountingBalance >= 2000000 then
		trigger.action.setUserFlag(10,97)
		trigger.action.outSoundForCoalition(coalition.side.BLUE, "historyMissionWarning.ogg")	
		trigger.action.outText("Next mission after current one: history mission4", 20) 
				
    elseif Mission1Done == true and Mission2Done == true and Mission3Done == true and Mission4Done == true and Mission5Done == false and AccountingBalance >= 2500000 then
		trigger.action.setUserFlag(10,96)
		trigger.action.outSoundForCoalition(coalition.side.BLUE, "historyMissionWarning.ogg")	
		trigger.action.outText("Next mission after current one: history mission5", 20) 
				
	elseif Mission1Done == true and Mission2Done == true and Mission3Done == true and Mission4Done == true and Mission5Done == true and
			Mission6Done == false and AccountingBalance >= 3000000 then
		trigger.action.setUserFlag(10,95)
		trigger.action.outSoundForCoalition(coalition.side.BLUE, "historyMissionWarning.ogg")	
		trigger.action.outText("Next mission after current one: history mission6", 20) 	
		
	elseif Mission1Done == true and Mission2Done == true and Mission3Done == true and Mission4Done == true and Mission5Done == true and
			Mission6Done == true and Mission7Done == false and AccountingBalance >= 3500000 then
		trigger.action.setUserFlag(10,94)
		trigger.action.outSoundForCoalition(coalition.side.BLUE, "historyMissionWarning.ogg")	
		trigger.action.outText("Next mission after current one: history mission7", 20) 	
		
	elseif Mission1Done == true and Mission2Done == true and Mission3Done == true and Mission4Done == true and Mission5Done == true and
			Mission6Done == true and Mission7Done == true and Mission8Done == false and AccountingBalance >= 4000000 then
		trigger.action.setUserFlag(10,93)
		trigger.action.outSoundForCoalition(coalition.side.BLUE, "historyMissionWarning.ogg")	
		trigger.action.outText("Next mission after current one: history mission8", 20) 	
		
	end
end;



function setAirbases()
	if Mission1Done == true then
		Group.getByName("LavanBlue"):activate()
	end
	if Mission6Done == true then
		Group.getByName("KishBlue"):activate()
	end
end


--trigger.action.outText("cargado file scripts v3", 10)  
