//------------------------------------------------------------------------------
// File: Campaign2.cs 
// Second main map
//------------------------------------------------------------------------------

// PrepForMadRussian Quest Log Globals
$PrepForMadRussian::LogQuest    = "Mad Russian Scramble";
$PrepForMadRussian::LogDesc     = "Get things ready to take on the Mad Russian.";
$PrepForMadRussian::LogReward   = "Reward: A safe town to leave behind.";
$PrepForMadRussian::LogBrief[0] = "Put out the Fire.";
$PrepForMadRussian::LogBrief[1] = "Employ a Mayor.";
$PrepForMadRussian::LogBrief[2] = "Hire a Sheriff.";
$PrepForMadRussian::LogBrief[3] = "Build Train Tracks.";
$PrepForMadRussian::LogLong[0]  = "Put out the Fire before this whole place goes up in smoke.";
$PrepForMadRussian::LogLong[1]  = "Employ a Citizen as Mayor so there is someone to watch over town while you're on the trail.";
$PrepForMadRussian::LogLong[2]  = "Hire a Sheriff to help the Mayor keep order.";
$PrepForMadRussian::LogLong[3]  = "Get a rail line set up to keep you in supplies when you head off.";
$Campaign2::Repairkey = "Repair the Gate Key.";
$Campaign2::Secondkey = "Find the remaining half of the gate key.";
   
function Campaign2StartTasks()
{
   InitializeQuestGui();
   GameCamera.FlySpeed = 80;
   slgActivateTask("Campaign2Tasks");
   TaskModifier.strMarkVertex("Campaign2Tasks", "Campaign2Intro", $TSV_AVAIL);
   TaskModifier.strMarkVertex("Campaign2Tasks", "Treasurehunt2secret", $TSV_AVAIL);
   TaskModifier.strMarkVertex("Campaign2Tasks", "Treasurehunt2sandtrap", $TSV_AVAIL);
   TaskModifier.strMarkVertex("Campaign2Tasks", "MapSnakeValleyTrigger", $TSV_AVAIL);
   MainmapDisastersMedium();
   
   //Reward
   tsModifyResource($Resource::Experience, 50, true);
   SendProductionToClient(HeroCharacter, "50 experience");
    
   // White/wong choice task (happens once only)
   slgActivateTask("WhiteWongChoice", true);
   // Award Pioneer Badge
   tsAwardBadge("badge_pioneer3");
   
   // Temp Triggers 
   //TaskModifier.strMarkVertex("Campaign2Tasks", "openBanditGate", $TSV_AVAIL);
   //TaskModifier.strMarkVertex("Campaign2Tasks", "forgekey", $TSV_AVAIL);
   //slgActivateTask("PrepForMadRussian");
   //TaskModifier.strMarkVertex("PrepForMadRussian", "MadRussianCaptureTrigger", $TSV_AVAIL);
}
// Used to deactivate tasks from the second campaign when moving to satellite maps
function deactivateCampaign2Tasks()
{
   tsEndTask("Campaign2Tasks");
   tsEndTask("PrepForMadRussian");
}

////////////////////////////////////////////////////////////////////////////////
// Starts all silent triggers for the campaign 2 map.
////////////////////////////////////////////////////////////////////////////////
function Campaign2Intro::OnEnter(%this)
{
   tsSendTaskPopUpDlg("ID_Campaign2", "ID_CampaignIntro", $TaskButton::Okay, "herocharacter", "ID_CampaignIntro");
   
   //Quest log
   tsAddQuestToTracker(true, "Bandit Base", "", "The Copperhead gang is heavily fortified to the southwest.  Destroy their base and capture their leader.", "Reward: The Mad Russian's where-abouts.");
   tsReadyQuest("Bandit Base");
   tsAddTaskToTracker("Bandit Base", "Destroy the Bandit base.", "Destroy the Bandit base to the southwest.");
   
   //Unlock Platform task
   TaskModifier.strMarkVertex("Campaign2Tasks", "UnlockPlatform", $TSV_AVAIL);
   
   //Bridge Warning task
   TaskModifier.strMarkVertex("Campaign2Tasks", "WagonBridge", $TSV_AVAIL);
   
   //Hidden Cave Treasure map task
   TaskModifier.strMarkVertex("Campaign2Tasks", "HiddenCaveStart", $TSV_AVAIL);
   
   //Tornado Valley
   TaskModifier.strMarkVertex("Campaign2Tasks", "MapTornadoValleyPop", $TSV_AVAIL);
   
   // Complete Vertex:Campaign2Intro 
   TaskModifier.strMarkVertex("Campaign2Tasks", "Campaign2Intro", $TSV_CMPLETE);
}
// Walking into platformzone converts mapplatform to team 1
function UnlockPlatform::onExit(%this)
{
   tsConvertObjTeam("mapPlatform", $OST_PLAYER);
   
   //Bake off task trigger
   TaskModifier.strMarkVertex("Campaign2Tasks", "MainmapBakeoffTrigger", $TSV_AVAIL);
}


////////////////////////////////////////////////////////////////////////////////
// Tornado Valley Trigger
////////////////////////////////////////////////////////////////////////////////
// Triggers when Population reaches 10
function MapTornadoValleyPop::onUpdate()
{
   %resourceCount = rsGetResourceCount($Resource::People);
   if(%resourceCount >= 10)
   {  
      TaskModifier.StrMarkVertex("Campaign2Tasks", "MapTornadoValleyTrigger", $TSV_AVAIL);
      TaskModifier.StrMarkVertex("Campaign2Tasks", "MapTornadoValleyPop", $TSV_CMPLETE);
   }
}
function MapTornadoValleyTrigger::onExit()
{
   //Spawn Trigger characte
   tsCreateObj("MaleCiv", "TVdude", "0", "-375 -448", "TVdude");
   tsSkinObj("TVdude", "default");
   tsNameObj("TVdude", "Clark Wimbleton");
}
// Move character on create
function MapTornadoValleyMove::onExit(%this)
{
   tsMoveObjToTarget("TVdude", "-382.5 -338.5");   
}
// 5 sec delay
function MapTornadoValleyDelay::onExit()
{
   tsSendTaskClickDlg("ID_TASK_TornadoValley", "ID_MapTornadoIntro", $TaskButton::Okay, "TVdude", "ID_MapTornadoIntro");
   //Quest log
   tsAddQuestToTracker(false, "Tornado Valley", "","Dorothy Bloom, an eccentric entrepreneur, has challenged anyone to build a prosperous town in the middle of the most dangerous Tornado Valley in the area. Crazy, sure, but she's willing to pay a generous reward for the feat.", "Reward: 1000 Gold and 100 Experience");
   tsReadyQuest("Tornado Valley");
   tsAddTaskToTracker("Tornado Valley", "Build a town in Tornado Valley.", "Build a town in Tornado Valley.");
}
// Dialog complete ID_MapTornadoIntro

// Todo add hotel requirement
function MapTornadoValleyReset::onExit()
{
   //tsSendTaskClickDlg("ID_TASK_TornadoValley", "ID_MapTornadoValleyAccept", $TaskButton::Accept, "TVdude", "ID_MapTornadoValleyAccept");
   
   %dlgData = tsCreateTaskDlgData("ID_TASK_TornadoValley", true, true, "ID_MapTornadoValleyAccept");
   tsAddTaskDialog("ID_MapTornadoValleyAccept", %dlgData);
   tsSetAcceptButtonText("ID_ACCEPT_READY", %dlgData);
   tsSetCancelButtonText("ID_CANCEL_NOTYET", %dlgData);
   tsSendTaskDlgMsg(%dlgData, "TVdude");
   tsDestroyTaskDlgData(%dlgData);
}
//******************************
// Load Tornado Valley Map
//******************************
function LoadTornadoValley::onExit(%this)
{
   Parent::onExit(%this);
   
   %scenario = new SLScenario() {
      stack   = true;
      mapName = "assets/data/missions/sandlot/tornadoValley.mis";
      mapMinimap = "assets/client/ui/minimaps/tornadominimap.png";
      mapMain = false;
      
      // Resources
      resourceGold       = "250 0";
      resourceWood       = "250 0";
      resourceFood       = "20 0";
      resourceFoodMax    = "20 0";
      resourceWater      = "0 0";
      resourceWaterMax   = "0 0";
      resourceHappiness  = "80 0";
      
   };
   
   LoadScenario(%scenario, deactivateCampaign2Tasks, startTornadoValleyTasks, resetTornadoValleyTasks);
}


////////////////////////////////////////////////////////////////////////////////
// Snake Valley Trigger
////////////////////////////////////////////////////////////////////////////////
// Player triggers zone near Trading Post
function MapSnakeValleyTrigger::onExit()
{
   tsSendTaskClickDlg("ID_TASKNAME_SNAKEVALLEY", "ID_MapSnakeValleyTrigger", $TaskButton::Okay, "SVdude", "ID_MapSnakeValleyTrigger");
   
   //Quest log
   tsAddQuestToTracker(false, "Snake Valley", "",SVDude.name @ "'s supplies are being guarded by a gang of Copperheads in the Snake Valley Canyons.", "Reward: Trading Post.");
   tsReadyQuest("Snake Valley");
   tsAddTaskToTracker("Snake Valley", "Help "@ SVDude.name @".", "Recover " @ SVDude.name @" supplies from the Copperheads.");
}
// Reset delay 
function MapSnakeValleyResetDelay::onExit()
{
   //tsSendTaskClickDlg("ID_TASKNAME_SNAKEVALLEY", "ID_MapSnakeValleyAccept", $TaskButton::Accept, "SVdude", "ID_MapSnakeValleyAccept");
   
   %dlgData = tsCreateTaskDlgData("ID_TASKNAME_SNAKEVALLEY", true, true, "ID_MapSnakeValleyAccept");
   tsAddTaskDialog("ID_MapSnakeValleyAccept", %dlgData);
   tsSetAcceptButtonText("ID_ACCEPT_READY", %dlgData);
   tsSetCancelButtonText("ID_CANCEL_NOTYET", %dlgData);
   tsSendTaskDlgMsg(%dlgData, "SVdude");
   tsDestroyTaskDlgData(%dlgData);
}

/******************************************************************************/
/*** Load Snake Valley
/******************************************************************************/
function LoadSnakeValley::onExit(%this)
{
   Parent::onExit(%this);
   
   %scenario = new SLScenario() {
      stack   = true;
      mapName = "assets/data/missions/sandlot/snakevalley.mis";
      mapMinimap = "assets/client/ui/minimaps/snakevalleyminimap.png";
      mapMain = false;
      
      // Resources
      resourceGold       = "0 1";
      resourceWood       = "0 1";
      resourceFood       = "20 0";
      resourceFoodMax    = "20 0";
      resourceWater      = "0 0";
      resourceWaterMax   = "0 0";
      resourceHappiness  = "80 0";
      
      // Disaster fields
      addDisasterNode        = "0 100 0";
      disasterBanditRate     = "0 0";
      disasterDroughtRate    = "0 0";
      disasterEarthquakeRate = "0 0";
      disasterFamineRate     = "0 0";
      disasterFireRate       = "0 0";
      disasterPlagueRate     = "0 0";
      disasterTornadoRate    = "0 0";
      disasterStack = $DisasterStack::Push;
      
      // Units
      toughLawmen       = true;
      neutralLawmen     = true;
      toughGunslinger   = true;
      niceGunslinger   = true;
      neutralGunslinger = true;
   };
   
   LoadScenario(%scenario, deactivateCampaign2Tasks, startSnakeValleyTasks, resetSnakeValleyTasks);
}
// Snake Valley Return Dialog
function MapSnakeValleyReturn::onExit()
{
   tsSendTaskPopUpDlg("ID_TASKNAME_SNAKEVALLEY", "id_snakevalley_return1", $TaskButton::More, "SVdude", "id_snakevalley_return1");
   tsSendTaskPopUpDlg("ID_TASKNAME_SNAKEVALLEY", "id_snakevalley_return2", $TaskButton::More, "herocharacter", "id_snakevalley_return2");
   tsSendTaskPopUpDlg("ID_TASKNAME_SNAKEVALLEY", "id_snakevalley_return3", $TaskButton::Okay, "SVdude", "id_snakevalley_return3");
   
   convertSVdude();
}
function convertSVdude()
{
   tsConvertObjTeam("SVdude", $OST_PLAYER);
   tsSkinObj("SVdude","base");
}

////////////////////////////////////////////////////////////////////////////////
// Treasure Map 2
////////////////////////////////////////////////////////////////////////////////
// Destroy prop on cliff edge passed fense
function Treasurehunt2secret::onExit(%this)
{
   Parent::onExit(%this);
   
   // Get id of character that triggered zone
   %teamList = tsCreateObjList();
   %objList = slgGetServerCharacterList();
   %objList.getTeamList($OST_PLAYER, %teamList);
   %count = 0;
   for(%index = 0; %index < %teamList.getSize(); %index++)
   {
      %charID = %teamList.getID(%index);
      if(%charID.isInZone(treasurehintzone))
      {
         %count++;
         break;
      }
   }
   if(%count == 0){
      %charID = "herocharacter";
   }
   tsDestroyObjList(%teamList); 
      
   // Parchment Image
   if(firstword(getRes()) > 800)
   {
      %imagePos = "32 64";
   }
   else
   {
      %imagePos = "25 50";
   }
   %image1 = new SLImage()
   {
      stateUp = "~/client/ui/icons/dot.png"; // Invisible image 
      iconEnabled = "~/client/ui/icons/parchment.png";
      iconOffset = "0 0";
      extent = "90 82";
      position = %imagePos;
      input = "0";
      HorizSizing = "relative";
      VertSizing = "relative";
   };
   %dlgData = tsCreateTaskDlgData("ID_TreasureHuntTwo", false, $TaskButton::Okay, "ID_Treasurehunt2Secret");
   tsAddTaskDialog("ID_Treasurehunt2Secret", %dlgData);
   tsSetTaskDialogImage(%image1, %dlgData);
   tsSendTaskDlgMsg(%dlgData, %charID);
   tsDestroyTaskDlgData(%dlgData);
}
// Check if building has been placed in zone sandtrapzone
// If so destory building after a few seconds send up dialog to random civ or hero reset vertex
// If building is a Well uncover hidden treasure map
function Treasurehunt2sandtrap::onMessage(%this, %msg, %params)
{
   // Get id of character that triggered zone
   Parent::onMessage(%this, %msg, %params);
   if(%this.isMarkedComplete())
   {
      %objlist = tsGetObjListFromMsg(%msg, %params);
      %buildingID = %objlist.getID(0);
      if(slgIsBuilding(%buildingID) && %buildingID.isInZone(sandtrapzone))
      { 
         //Check to see if Building is a well
         if(stricmp(%buildingID.getType(),"well") == 0)
         {
            //Uncover Hidden Treasure map
            TaskModifier.strMarkVertex("Campaign2Tasks", "Treasurehunt2sandtrap", $TSV_CLOSED);
            TaskModifier.strMarkVertex("Campaign2Tasks", "Treasurehunt2well", $TSV_AVAIL);  
         }
         else
         {
            // Set Vertex Timer to destroy building reset vertex
            %buildingID.setName("sandtrapbuilding");
         }
      }
   }
}
// Destroys Building in sandtrapzone
function Treasurehunt2destroy::onExit(%this)
{
   if(isObject("sandtrapbuilding")) 
   {
      sandtrapbuilding.health = 0;
      //Sandtrap Dialog
      tsSendTaskPopUpDlg("ID_TreasureHuntTwo", "ID_Treasurehunt2Sandtrap", $TaskButton::Okay, "herocharacter");
   }
   Treasurehunt2reset();
}
function Treasurehunt2reset()
{
   TaskModifier.strResetVertex("Campaign2Tasks", "Treasurehunt2sandtrap");
   TaskModifier.strMarkVertex("Campaign2Tasks", "Treasurehunt2sandtrap", $TSV_AVAIL);
}
// Dialog after building well in sandtrap
function Treasurehunt2well::onExit(%this)
{
   // KEY Image
   if(firstword(getRes()) > 800)
   {
      %imagePos = "32 64";
   }
   else
   {
      %imagePos = "25 50";
   }
   %image1 = new SLImage()
   {
      stateUp = "~/client/ui/icons/dot.png"; // Invisible image 
      iconEnabled = "~/client/ui/icons/key.png";
      iconOffset = "0 0";
      extent = "90 59";
      position = %imagePos;
      input = "0";
      HorizSizing = "relative";
      VertSizing = "relative";
   };
   %dlgData = tsCreateTaskDlgData("ID_TreasureHuntTwo", false, $TaskButton::Okay, "ID_Treasurehunt2Well");
   tsAddTaskDialog("ID_Treasurehunt2Well", %dlgData);
   tsSetTaskDialogImage(%image1, %dlgData);
   tsSendTaskDlgMsg(%dlgData, "herocharacter");
   tsDestroyTaskDlgData(%dlgData);
   
   //Quest log
   tsAddQuestToTracker(false, "A Well-Found Treasure", "", "An old key and a note hint that a great treasure is hidden somewhere in the area. Follow the clues to uncover it.", "Reward: Unknown.");
   tsReadyQuest("A Well-Found Treasure");
   tsAddTaskToTracker("A Well Found Treasure", "Search for the shelter in the woods.", "The note we found said to search for the shelter in the woods that isn't a tree.");
   
}
function TreasureHunt2Cabin::onExit(%this)
{
   Parent::onExit(%this);
   
   // Get id of character that triggered zone
   %teamList = tsCreateObjList();
   %objList = slgGetServerCharacterList();
   %objList.getTeamList($OST_PLAYER, %teamList);
   %count = 0;
   for(%index = 0; %index < %teamList.getSize(); %index++)
   {
      %charID = %teamList.getID(%index);
      if(%charID.isInZone(treasurehintzone))
      {
         %count++;
         break;
      }
   }
   if(%count == 0){
      %charID = "herocharacter";
   }
   tsDestroyObjList(%teamList);
      // KEY Image
      if(firstword(getRes()) > 800)
      {
         %imagePos = "32 64";
      }
      else
      {
         %imagePos = "25 50";
      }
      %image1 = new SLImage()
      {
         stateUp = "~/client/ui/icons/dot.png"; // Invisible image 
         iconEnabled = "~/client/ui/icons/key.png";
         iconOffset = "0 0";
         extent = "90 59";
         position = %imagePos;
         input = "0";
         HorizSizing = "relative";
         VertSizing = "relative";
      };
      
      tsSendTaskPopUpDlg("ID_TreasureHuntTwo", "ID_Treasurehunt2openCabin", $TaskButton::More, %charID);
      // Dialog Image
      %dlgData = tsCreateTaskDlgData("ID_TreasureHuntTwo", false, $TaskButton::Okay, "ID_Treasurehunt2Cabin");
      tsAddTaskDialog("ID_Treasurehunt2Cabin", %dlgData);
      tsSetTaskDialogImage(%image1, %dlgData);
      tsSendTaskDlgMsg(%dlgData, %charID);
      tsDestroyTaskDlgData(%dlgData);
      
      //Quest log
      tsAddTaskToTracker("A Well-Found Treasure", "Find whatever the key opens.", "An old key and a miner's hat were found in the cabin. Find whatever the key opens.");
      tsCompleteTaskInTracker("A Well-Found Treasure", "Search for the Old Cabin in the woods.");
}
function TreasureHunt2Cave::onExit(%this)
{
   Parent::onExit(%this);
   
   // Get id of character that triggered zone
   %teamList = tsCreateObjList();
   %objList = slgGetServerCharacterList();
   %objList.getTeamList($OST_PLAYER, %teamList);
   %count = 0;
   for(%index = 0; %index < %teamList.getSize(); %index++)
   {
      %charID = %teamList.getID(%index);
      if(%charID.isInZone(treasurehintzone))
      {
         
         %count++;
         break;
      }
   }
   if(%count == 0){
      %charID = "herocharacter";
   }
   tsDestroyObjList(%teamList);
   
   if(stricmp(%charID.getName(),"herocharacter") == 0)
   {
      %charID = "herocharacter";
   }
   else
   {
      %charID.setName("cavedude");
   }
   tsSendTaskPopUpDlg("ID_TreasureHuntTwo", "ID_Treasurehunt2OpenDoor", $TaskButton::Okay, %charID, "ID_Treasurehunt2OpenDoor");
}
function TreasureHunt2openCave::onExit(%this)
{
   // Open Cave door
   RemoveObject(treasuregate);
   treasuregate.rotateZ(-90);
   PlaceObject(treasuregate);
   // Quest log
   tsCompleteTaskInTracker("A Well-Found Treasure", "Find whatever the key opens.");  
}
function TreasureHunt2CaveTimer::onExit(%this)
{
   if(isobject("cavedude"))
   {
      %objname = "cavedude";
   }
   else
   {
      %objname = "herocharacter";
   }
   tsSendTaskPopUpDlg("ID_TreasureHuntTwo", "ID_Treasurehunt2entercave", $TaskButton::okay, %objname);
   tsSendTaskPopUpDlg("ID_TreasureHuntTwo", "ID_Treasurehunt2reward", $TaskButton::More, %objname, "ID_Treasurehunt2reward");
}
function TreasureHunt2Complete::onExit(%this)
{
   // Give Resources, send resources to unit that triggered zone.
   tsModifyResource($Resource::gold, 600, true);
   tsModifyResource($Resource::wood, 600, true);
   tsModifyResource($Resource::Experience, 30, true);
   tsActivateBuildingXP("fountain"); // Unlock fountain
   if(isobject("cavedude"))
   {
      SendProductionToClient(cavedude, "600 gold");
      SendProductionToClient(cavedude, "600 wood");
      SendProductionToClient(cavedude, "30 experience");
   }
   else
   {
      SendProductionToClient(herocharacter, "600 gold");
      SendProductionToClient(herocharacter, "600 wood");
      SendProductionToClient(herocharacter, "30 experience");
   }
   // 2st Treasure requirement for Treasure Hunter Badge
   TaskModifier.strMarkVertex("Badgetasks", "BadgeTreasure2", $TSV_CMPLETE);
}
////////////////////////////////////////////////////////////////////////////////
// Animal Trap Secret Map
////////////////////////////////////////////////////////////////////////////////
// Build 3 ranches with 3 different animal types
function AnimalTrapMapTrigger::onExit(%this)
{   
   // Spawn horse
   %horseobj = tsCreateObj("HorseUnit", "AThorse", $OST_PLAYER, "-376 -449", "AThorse");
   %horseobj.name = "Wild Horse";
   
   // initialize the animal trap satellite
   mapsatellite_animaltrap.visible = true;
   
   // unlock the sheep badge
   tsUnlockBadge("badge_sheep");
}
function ATMapSpotHorse::onExit(%this)
{   
   // Random civ spots horse Dialog
   tsSendTaskPopUpDlg("ID_AnimalTrap", "ID_MapAnimaltrapSpot", $TaskButton::Okay, "Herocharacter");
   tsMoveObjToTarget("ATHorse", "-377.5 -410.5");
}
// Move the horse to a well
function ATMapHorsetoWater::onExit(%this)
{   
   tsSendTaskPopUpDlg("ID_AnimalTrap", "ID_MapAnimalThirst", $TaskButton::Okay, "Herocharacter");
   tsConvertObjTeam("AThorse", $OST_NEUTRAL); 
}
function ATMapHorsewait::onExit(%this)
{   
   tsConvertObjTeam("AThorse", $OST_NEUTRAL);
   //Spawn Owner
   %charobj = tsCreateObj("maleciv", "ATowner", $OST_NEUTRAL, "-487 -243", "ATowner");
   tsSkinObj(%charobj, "default");
   %charobj.name = "Fredrick Doolittle";
}
// Move Owner to horse
function ATMapCreateOwner::onExit(%this)
{   
   tsMoveObjToTarget("ATowner", "ATHorse");   
}
function ATMapWalktoHorse::onExit(%this)
{   
   tsSendTaskPopUpDlg("ID_AnimalTrap", "ID_MapAnimalfound", $TaskButton::Okay, "ATowner");
   //Quest log

   tsAddQuestToTracker(false, "Animal Roundup", "", "Fredrick Doolittle has come to you to get help capturing some wild animals.", "Reward: Unknown");
   tsReadyQuest("Animal Roundup");
   tsAddTaskToTracker("Animal Roundup", "Help Fredrick capture wild animals.", "Fredrick Doolittle needs some help capturing a few wild animals.");
}
function ATMapOwnertoHorse::onExit(%this)
{
  //TODO Do something here? Dialog? 
}
//Reset Load Accept Delay
function ATMapAcceptDelay::onExit(%this)
{
   //Loads Secret Animal Trap quest
   %dlgData = tsCreateTaskDlgData("ID_AnimalTrap", true, true, "ID_MapAnimalAccept");
   tsAddTaskDialog("ID_MapAnimalAccept", %dlgData);
   tsSetAcceptButtonText("ID_ACCEPT_READY", %dlgData);
   tsSetCancelButtonText("ID_CANCEL_NOTYET", %dlgData);
   tsSendTaskDlgMsg(%dlgData, "ATowner");
   tsDestroyTaskDlgData(%dlgData); 
}
// Load Secret Animal Trap Map
function LoadAnimalTrap::onExit(%this)
{
   Parent::onExit(%this);
   
   %scenario = new SLScenario() {
      stack   = true;
      mapName = "assets/data/missions/sandlot/animaltrap.mis";
      mapMinimap = "assets/client/ui/minimaps/animaltrapminimap.png";
      mapMain = false;
      
      // Resources
      resourceGold       = "0 0";
      resourceWood       = "0 0";
      resourceFood       = "20 0";
      resourceFoodMax    = "20 0";
      resourceWater      = "0 0";
      resourceWaterMax   = "0 0";
      resourceHappiness  = "80 0";
      
      // Disaster fields
      addDisasterNode        = "0 100 0";
      disasterBanditRate     = "0 0";
      disasterDroughtRate    = "0 0";
      disasterEarthquakeRate = "0 0";
      disasterFamineRate     = "0 0";
      disasterFireRate       = "0 0";
      disasterPlagueRate     = "0 0";
      disasterTornadoRate    = "0 0";
      disasterStack = $DisasterStack::Push;
      
   };
   
   LoadScenario(%scenario, deactivateCampaign2Tasks, AnimalTrapStartTasks, resetAnimalTrapTasks);
}
// Return from Animal Trap
function ReturnAnimalTrap::onExit(%this)
{
   tsSendTaskPopUpDlg("ID_AnimalTrap", "ID_MapAnimaltrapReturn", $TaskButton::Okay, "ATowner");   
   tsRemoveObj("ATowner");
   AThorse.deleteObject();
   //Quest log
   tsCompleteTaskInTracker("Animal Roundup", "Help Fredrick capture wild animals.");
}

////////////////////////////////////////////////////////////////////////////////
// Map Trigger for Bake Off Map
////////////////////////////////////////////////////////////////////////////////
function MainmapBakeoffTrigger::onExit(%this)
{
   // Spawn Jill Evans
   %jillobj = tsCreateObj("Femaleciv", "jillevans", $OST_NEUTRAL, "-487 -243", "jillevans");
   tsSkinObj("jillevans", "default");
   %jillobj.name = "Jillian Evans";
   
   //Quest log
   tsAddQuestToTracker(false, "Cakey Makey", "", "Jillian is having a hard time gathering enough food for her orders.", "Reward: 200 Gold 200 Wood and 50 Experience");
   tsReadyQuest("Cakey Makey");
   tsAddTaskToTracker("Cakey Makey", "Help Jillian complete her order.", "Jillian's bakery is not far from here.  Help her collect enough food for her orders.");
}
function MainmapBakeoffOnCreate::onExit(%this)
{
   // Move Jill Evans
   tsMoveObjToTarget("jillevans", "-410 -259");
}
function LoadBakeOffAccept::onExit(%this)
{
   // Dialog
   tsSendTaskClickDlg("ID_Campaign2Bakeoff", "ID_BakeoffAccept", $TaskButton::Accept, "jillevans", "ID_BakeoffAccept");
}
function LoadBakeOff::onExit(%this)
{
   Parent::onExit(%this);
   
   %scenario = new SLScenario() {
      stack   = true;
      mapName = "assets/data/missions/sandlot/bakethosepies.mis";
      mapMinimap = "assets/client/ui/minimaps/bakeoffminimap.png";
      mapMain = false;
      
      // Resources
      resourceGold       = "500 0";
      resourceWood       = "500 0";
      resourceFood       = "15 0";
      resourceFoodMax    = "20 0";
      resourceWater      = "0 0";
      resourceWaterMax   = "0 0";
      resourceHappiness  = "80 0";
      
      // Disaster fields
      addDisasterNode = "0 30 1";
      disasterAnimalRate     = "0 0";
      disasterBanditRate     = "0 0";
      disasterDroughtRate    = "0 0";
      disasterEarthquakeRate = "0 0";
      disasterFamineRate     = "0 0";
      disasterFireRate       = "0 0";
      disasterPlagueRate     = "0 0";
      disasterTornadoRate    = "0 0";
      
      disasterStack = $DisasterStack::Push;
   };
   
   LoadScenario(%scenario, deactivateMainMapTasks, startFoodBakerTasks, resetFoodBakerTasks);
}
function resetFoodBakerTasks()
{
   TaskModifier.strResetVertex("Campaign2Tasks", "LoadBakeOffAccept");
   TaskModifier.strMarkVertex("Campaign2Tasks", "LoadBakeOffAccept", $TSV_AVAIL);
}
// Walking into wagonbridgezone sends dialogpopup 
function WagonBridge::onMessage(%this, %msg, %params)
{
   // Get id of character that triggered zone
   Parent::onMessage(%this, %msg, %params);
   if(%this.isMarkedComplete())
   {
      %objlist = tsGetObjListFromMsg(%msg, %params);
      %charID = %objlist.getID(0);
      
      tsSendTaskPopUpDlg("ID_Campaign2Bridge", "ID_Map2WagonBridge", $TaskButton::Okay, %charID);
   }
}

// Walks into hiddencavezone Starts treasure map
function HiddenCaveStart::onMessage(%this, %msg, %params)
{
   // Get id of character that triggered zone
   Parent::onMessage(%this, %msg, %params);
   if(%this.isMarkedComplete())
   {
      %objlist = tsGetObjListFromMsg(%msg, %params);
      %charID = %objlist.getID(0);
      if(!(TreasureHunt2Cabin.isMarkedComplete()))
      {
         tsSendTaskPopUpDlg("ID_Campaign2", "ID_Treasurehunt2Door", $TaskButton::Okay, %charID, "ID_Treasurehunt2Door");
      }
   }
}

// Vertex Completes when player character enters zone: gatezone
function BanditGatezone::onMessage(%this, %msg, %params)
{
   // Get id of character that triggered zone
   Parent::onMessage(%this, %msg, %params);
   if(%this.isMarkedComplete())
   {
      %objlist = tsGetObjListFromMsg(%msg, %params);
      %charID = %objlist.getID(0);
      tsSendTaskPopUpDlg("ID_Campaign2", "ID_CampaignGateZone", $TaskButton::More, %charID);
      tsSendTaskPopUpDlg("ID_Campaign2", "ID_CampaignGateBanditkey", $TaskButton::More, "GateBandit1");
      tsSendTaskPopUpDlg("ID_Campaign2", "ID_CampaignGateBanditlost", $TaskButton::More, "GateBandit2");
      tsSendTaskPopUpDlg("ID_Campaign2", "ID_CampaignGateBanditmad", $TaskButton::More, "GateBandit1");
      tsSendTaskPopUpDlg("ID_Campaign2", "ID_CampaignGateIdea", $TaskButton::Okay, %charID, "ID_CampaignGateIdea");
      
      // Quest log
      tsAddQuestToTracker(true, "Gate Keeper", "", "Find the pieces of the gate key and have your blacksmith repair it.", "Reward: Get into the Bandit base.");
      tsReadyQuest("Gate Keeper");
      tsAddTaskToTracker("Gate Keeper", "Find 2 halves of the gate key.", "Search the nearby swimming holes to find the two halves of the gate key.");
     
      // Start Swimming pool zone triggers
      TaskModifier.strMarkVertex("Campaign2Tasks", "SwimmingPool1", $TSV_AVAIL);
      TaskModifier.strMarkVertex("Campaign2Tasks", "SwimmingPool2", $TSV_AVAIL);
      TaskModifier.strMarkVertex("Campaign2Tasks", "SwimmingPool3", $TSV_AVAIL);
   }
}
// Vertex completes a few seconds after Dialog ID_CampaignGateIdea
function BanditGateNoise::onExit()
{
   tsSendTaskPopUpDlg("ID_Campaign2", "ID_CampaignGateBanditnoise", $TaskButton::Okay, "GateBandit2" ,"ID_CampaignGateBanditnoise");
}
////////////////////////////////////////////////////////////////////////////////
// Swimming hole vertices
////////////////////////////////////////////////////////////////////////////////
// 1 half of the key is found here
function SwimmingPool1::onExit(%this)
{
   Parent::onExit(%this);
   
   // Get id of character that triggered zone
   %teamList = tsCreateObjList();
   %objList = slgGetServerCharacterList();
   %objList.getTeamList($OST_PLAYER, %teamList);
   %count = 0;
   for(%index = 0; %index < %teamList.getSize(); %index++)
   {
      %charID = %teamList.getID(%index);
      if(%charID.isInZone(swimhole1zone))
      {
         
         %count++;
         break;
      }
   }
   if(%count == 0){
      %charID = "herocharacter";
   }
   tsDestroyObjList(%teamList);   
   
   // Quest log
   if(SwimmingPool2.isComplete() || SwimmingPool2.isMarkedComplete())
   {
      // Mark 2nd half of key found
      tsSendTaskPopUpDlg("ID_Campaign2", "ID_Campaign2ndkey", $TaskButton::Okay, %charID);
      tsAddTaskToTracker("Gate Keeper", $Campaign2::Repairkey, "Repair the gate key at a Blacksmith.");
      
      tsCompleteTaskInTracker("Gate Keeper", $Campaign2::Secondkey);
      // Reward
      tsModifyResource($Resource::Experience, 10, true);
      SendProductionToClient(%charID, "10 experience");
   }
   else
   {
      // Mark that 1st half of the key has been found
      tsSendTaskPopUpDlg("ID_Campaign2", "ID_Campaign1stkey", $TaskButton::Okay, %charID);
      tsReplaceTaskInTracker("Gate Keeper", "Find 2 halves of the gate key.", $Campaign2::Secondkey, "Search the nearby swimming holes to find the two halves of the gate key.");
      // Reward         
      tsModifyResource($Resource::Experience, 10, true);
      SendProductionToClient(%charID, "10 experience");     
   }
}
// Another half of the key is found here
function SwimmingPool2::onExit(%this)
{
   Parent::onExit(%this);   
   // Get id of character that triggered zone
   %teamList = tsCreateObjList();
   %objList = slgGetServerCharacterList();
   %objList.getTeamList($OST_PLAYER, %teamList);
   %count = 0;
   for(%index = 0; %index < %teamList.getSize(); %index++)
   {
      %charID = %teamList.getID(%index);
      if(%charID.isInZone(swimhole2zone))
      {
         
         %count++;
         break;
      }
   }
   if(%count == 0){
      %charID = "herocharacter";
   }
   tsDestroyObjList(%teamList); 
      
   // Quest log
   if(SwimmingPool1.isComplete() || SwimmingPool1.isMarkedComplete())
   {
      // Mark 2nd half of key found
      tsSendTaskPopUpDlg("ID_Campaign2", "ID_Campaign2ndkey", $TaskButton::Okay, %charID);
      tsAddTaskToTracker("Gate Keeper", $Campaign2::Repairkey, "Repair the gate key at a Blacksmith.");
      tsCompleteTaskInTracker("Gate Keeper", $Campaign2::Secondkey);
      // Reward         
      tsModifyResource($Resource::Experience, 10, true);
      SendProductionToClient(%charID, "10 experience");
   }
   else
   {
      // Mark that 1st half of the key has been found
      tsSendTaskPopUpDlg("ID_Campaign2", "ID_Campaign1stkey", $TaskButton::Okay, %charID);
      tsReplaceTaskInTracker("Gate Keeper", "Find 2 halves of the gate key.", $Campaign2::Secondkey, "Search the nearby swimming holes to find the two halves of the gate key.");
      // Reward         
      tsModifyResource($Resource::Experience, 10, true);
      SendProductionToClient(%charID, "10 experience");
   }
}
// No key is found here.
function SwimmingPool3::onExit(%this)
{
   Parent::onExit(%this);
   // Get id of character that triggered zone
   %teamList = tsCreateObjList();
   %objList = slgGetServerCharacterList();
   %objList.getTeamList($OST_PLAYER, %teamList);
   %count = 0;
   for(%index = 0; %index < %teamList.getSize(); %index++)
   {
      %charID = %teamList.getID(%index);
      if(%charID.isInZone(swimhole3zone))
      {
         
         %count++;
         break;
      }
   }
   if(%count == 0){
      %charID = "herocharacter";
   }
   tsDestroyObjList(%teamList);
   tsSendTaskPopUpDlg("ID_Campaign2", "ID_CampaignNokey", $TaskButton::Okay, %charID);  
}
// Vertex completes after SwimmingPool1 andSwimmingPool2 are complete
function forgekey::onExit()
{
   // Close vertex no longer needed.
   TaskModifier.strMarkVertex("Campaign2Tasks", "SwimmingPool3", $TSV_CLOSED);
   
   // Check to see if a Blacksmith exists
   %objList = tsCreateObjList();
   tsFindObjTypeOnMap("blacksmith", "bldg", %objList);
   %BlacksmithCnt = 0;
   %EmployedCnt = 0;
   for(%index = 0; %index < %objList.getSize(); %index++)
   {
      %mapobject = %objList.getID(%index);
      if(%mapobject.getTeam() == "1")
      {  
         %teamObj = %objList.getID(%index);
         %cmpBldg = slgQueryInterface(%teamObj, $CID_BUILDING);
         if(%cmpBldg.getEmployeeCount() > 0)
         {
            %SmithCharID = %cmpBldg.getEmployee(0);
            %EmployedCnt++;
         }
         %BlacksmithCnt++;
      }
   }
   tsDestroyObjList(%objList);
   if(%BlacksmithCnt > 0)
   {
      if(%EmployedCnt > 0)
      {
         // Blacksmith Dialog
         %SmithCharID.setName("smithy");
         %SmithCharID.setInternalName("smithy");
         tsSendTaskPopUpDlg("ID_Campaign2", "ID_CampaignBlacksmith", $TaskButton::Okay, %SmithCharID);
         TaskModifier.strMarkVertex("Campaign2Tasks", "completekey", $TSV_AVAIL);
      }
      else
      {
        // You need to employ your blacksmith 
        tsSendTaskPopUpDlg("ID_Campaign2", "ID_CampaignEmploysmithy", $TaskButton::Okay, "herocharacter");
        TaskModifier.strMarkVertex("Campaign2Tasks", "EmployBlacksmith", $TSV_AVAIL);
      }
   }
   else
   {
      // You need to build a blacksmith
      tsSendTaskPopUpDlg("ID_Campaign2", "ID_CampaignBuildsmithy", $TaskButton::Okay, "herocharacter");
      TaskModifier.strMarkVertex("Campaign2Tasks", "BuildBlacksmith", $TSV_AVAIL);
   }
}
// Vertex completes few secs after Blacksmith is built
function Buildsmithdelay::onExit()
{
  tsSendTaskPopUpDlg("ID_Campaign2", "ID_CampaignEmploysmithy", $TaskButton::Okay, "herocharacter");
  TaskModifier.strMarkVertex("Campaign2Tasks", "EmployBlacksmith", $TSV_AVAIL); 
}
// Vertex completes a few secs after Blacksmith is employed
function Employsmithdelay::onExit()
{
   // Check to see if a Blacksmith exists
   %objList = tsCreateObjList();
   tsFindObjTypeOnMap("blacksmith", "bldg", %objList);
   for(%index = 0; %index < %objList.getSize(); %index++)
   {
      %mapobject = %objList.getID(%index);
      if(%mapobject.getTeam() == "1")
      {  
         %teamObj = %objList.getID(%index);
         %cmpBldg = slgQueryInterface(%teamObj, $CID_BUILDING);
         if(%cmpBldg.getEmployeeCount() > 0)
         {
            %SmithCharID = %cmpBldg.getEmployee(0);
            %SmithCharID.setName("smithy");
            %SmithCharID.setInternalName("smithy");
         }
      }
   }
   tsDestroyObjList(%objList);
   tsSendTaskPopUpDlg("ID_Campaign2", "ID_CampaignBlacksmith", $TaskButton::Okay, %SmithCharID);
   TaskModifier.strMarkVertex("Campaign2Tasks", "completekey", $TSV_AVAIL);
}
function completekey::onExit()
{
   tsSendTaskPopUpDlg("ID_Campaign2", "ID_Campaignkeycomplete", $TaskButton::Okay, "smithy", "ID_Campaignkeycomplete");
}
function TownhallAccept::onExit()
{
   // Bring hero to Blacksmith
   tsSendTaskClickDlg("ID_Campaign2", "ID_CampaignTownHallAccept", $TaskButton::Accept, "HeroCharacter", "ID_CampaignTownHallAccept");
}
function LoadTownhallDefense::onExit()
{
      %scenario = new SLScenario() {
      stack   = true;
      mapName = "assets/data/missions/sandlot/townhalldefense.mis";
      mapMinimap = "assets/client/ui/minimaps/townhalldefminimap.png";
      mapMain = false;
      
      addDisasterNode = "0 60 1";
      
      // Resources
      resourceGold       = "200 0";
      resourceWood       = "250 0";
      resourceFood       = "20 0";
      resourceFoodMax    = "20 0";
      resourceWater      = "0 0";
      resourceWaterMax   = "0 0";
      resourceHappiness  = "80 0";
      
      // Disaster fields
      disasterAnimalRate     = "0 0";
      disasterBanditRate     = "0 0";
      disasterDroughtRate    = "0 0";
      disasterEarthquakeRate = "0 0";
      disasterFamineRate     = "0 0";
      disasterFireRate       = "0 0";
      disasterPlagueRate     = "0 0";
      disasterTornadoRate    = "0 0";
      
      // Units
      niceLawmen        = true;
      toughLawmen       = true;
      neutralLawmen     = true;
      niceGunslinger    = true;
      toughGunslinger   = true;
      neutralGunslinger = true;
      
      disasterStack = $DisasterStack::Push;
   };
   
   LoadScenario(%scenario, deactivateMainMapTasks, startTownHallDefenseTasks, resetTownHallDefenseTasks);

}
function ReturnWithKey::onExit()
{
   tsSendTaskPopUpDlg("ID_Campaign2", "ID_Campaignpickupkey", $TaskButton::Okay, "HeroCharacter");
   // Quest log
   tsAddTaskToTracker("Gate Keeper", "Have "@herocharacter.name@" open the bandit gate.", "Use the key that Henry Pound gave to "@herocharacter.name@" to open the bandit gate.");
   tsCompleteTaskInTracker("Gate Keeper", $Campaign2::Repairkey);
   Campaign2DisastersHigh();
}
function openBanditGate::onExit()
{
   // Open Bandit Gate
   RemoveObject(leftgate);
   leftgate.rotateZ(90);
   PlaceObject(leftgate);
   
   RemoveObject(rightgate);
   rightgate.rotateZ(-90);
   PlaceObject(rightgate);
   
   // Change gate bandits team to 2
   tsConvertObjTeam("GateBandit1", 2);
   tsConvertObjTeam("GateBandit2", 2);
   
   TaskModifier.strMarkVertex("Campaign2Tasks", "DestroyBanditSaloon", $TSV_AVAIL);
   TaskModifier.strMarkVertex("Campaign2Tasks", "DestroyBanditStore", $TSV_AVAIL);
   TaskModifier.strMarkVertex("Campaign2Tasks", "DestroyBanditSmith", $TSV_AVAIL);
   
   tsSendTaskPopUpDlg("ID_Campaign2", "ID_CampaignOpengate", $TaskButton::Okay, "HeroCharacter");
   // Quest log   
   tsCompleteTaskInTracker("Gate Keeper", "Have "@herocharacter.name@" open the bandit gate.");
}
function DefeatCampBandits::onExit()
{
   tsSendTaskPopUpDlg("ID_Campaign2", "ID_CampaignBanditsDefeat", $TaskButton::Okay, "HeroCharacter");
}
function DestroyBanditSaloon::onExit()
{
   // Spawn Mad Russian
   %madrussian = tsCreateObj("MadRussianData", "Bigphony", $OST_NEUTRAL, "-100 -153", "Bigphony");
   %madrussian.name = "Mad'Russian";
   tsAddTaskToTracker("Bandit Base", "Defeat the Mad Russian.","Defeat the Mad Russian and his gang of bandits.");
   tsCompleteTaskInTracker("Bandit Base", "Destroy the Bandit base.");
}
function DestroyBanditStore::onExit()
{
   // Spawn More Bandits
   tsCreateObj("MaleBandit", "storebandit", $OST_NEUTRAL, "-89 -155", "storebandit");
   tsNameObj("storebandit", "Elijah Frost");
}
function BanditStoreonCreate::onExit()
{
   // Name and convert bandit
   tsConvertObjTeam("storebandit", 2);
}
function DestroyBanditSmith::onExit()
{
   // Spawn More Bandits
   tsCreateObj("MaleBandit", "Blacksmithbandit1", $OST_NEUTRAL, "-72 -128", "Blacksmithbandit1");
   tsNameObj("Blacksmithbandit1", "Rinehart Glott");
   tsCreateObj("FemaleBandit", "Blacksmithbandit2", $OST_NEUTRAL, "-68 -138", "Blacksmithbandit2");
   tsNameObj("Blacksmithbandit2", "Elsabeth Wistrom");
}
function BanditSmithonCreate::onExit()
{
   // Name and convert bandits
   tsConvertObjTeam("Blacksmithbandit1", 2);
   tsConvertObjTeam("Blacksmithbandit2", 2);
}
function OnCreateBigPhony::onExit()
{
   tsSendTaskPopUpDlg("ID_Campaign2", "ID_CampaignPhonyRussian", $TaskButton::Okay, "Bigphony");
   tsConvertObjTeam("Bigphony", 2); 
}
function BigPhonyisHealing::onUpdate(%this)
{
   Parent::onUpdate(%this);

      if(Bigphony.isHealing)
      {
         //Complete Vertex
         TaskModifier.strMarkVertex("Campaign2Tasks", "BigPhonyisHealing", $TSV_CMPLETE);
         // Quest Log
         tsCompleteTaskInTracker("Bandit Base", "Defeat the Mad Russian.");
      }
}
function BigPhonySurrender::onEnter()
{
   //Surrender Dialog
   tsConvertObjTeam("Bigphony", $OST_NEUTRAL); 
   tsSendTaskPopUpDlg("ID_Campaign2", "ID_CampaignPhonySurrender", $TaskButton::Okay, "Bigphony");
   tsSendTaskPopUpDlg("ID_Campaign2", "ID_CampaignPhonywin", $TaskButton::Okay, "herocharacter", "ID_CampaignPhonywin");
   TaskModifier.strMarkVertex("Campaign2Tasks", "BigPhonySurrender", $TSV_CMPLETE);
   // Reward
   tsModifyResource($Resource::Experience, 15, true);
   SendProductionToClient(HeroCharacter, "15 experience");
   
}
function WhiteWongAcceptDelay::onExit()
{
   tsSendTaskClickDlg("ID_Campaign2whitewong", "ID_CampaignLoadWowAccept", $TaskButton::Accept, "Bigphony", "ID_CampaignLoadWowAccept");
}
////////////////////////////////////////////////////////////////////////////////
// Load White or Wong Satellite map
////////////////////////////////////////////////////////////////////////////////
function LoadWhiteWong::onExit()
{
   Parent::onExit(%this);
    
   %scenario = new SLScenario() {
      stack   = true;
      mapName = "assets/data/missions/sandlot/whitewonghunt.mis";
      mapMinimap = "assets/client/ui/minimaps/whitewongminimap.png";
      mapMain = false;
      
      // Resources
      resourceGold       = "0 1";
      resourceWood       = "0 1";
      resourceFood       = "20 0";
      resourceFoodMax    = "20 0";
      resourceWater      = "0 0";
      resourceWaterMax   = "0 0";
      resourceHappiness  = "80 0";
      
      // Disaster fields
      addDisasterNode = "0 30 1";
      disasterAnimalRate     = "0 0";
      disasterBanditRate     = "0 0";
      disasterDroughtRate    = "0 0";
      disasterEarthquakeRate = "0 0";
      disasterFamineRate     = "0 0";
      disasterFireRate       = "0 0";
      disasterPlagueRate     = "0 0";
      disasterTornadoRate    = "0 0";
      
      // Units
      niceLawmen        = true;
      toughLawmen       = true;
      neutralLawmen     = true;
      niceGunslinger    = true;
      toughGunslinger   = true;
      neutralGunslinger = true;
      
      disasterStack = $DisasterStack::Push;
   };
   
   LoadScenario(%scenario, deactivateCampaign2Tasks, startWhiteWongTasks, resetWhiteWongTasks);
}
////////////////////////////////////////////////////////////////////////////////
//! Resets Load White or Wong Accept
////////////////////////////////////////////////////////////////////////////////
function resetWhiteWongTasks()
{
   TaskModifier.strResetVertex("Campaign2Tasks", "WhiteWongAcceptDelay");
   TaskModifier.strMarkVertex("Campaign2Tasks", "WhiteWongAcceptDelay", $TSV_AVAIL);
}

////////////////////////////////////////////////////////////////////////////////
// Story Arc Prepare for the Mad Russian
// Occurs after hunt and choice of white vs wong
////////////////////////////////////////////////////////////////////////////////
// Starts the prepare for mad russian story arc
function startPrepForMadRussian()
{
   tsStartTask("PrepForMadRussian", "ReturnFromWhiteOrWongHunt");
   
   // Check for Mr. White
   /*
      %objList = tsCreateObjList();
      tsFindObjTypeOnMap("mrwhitedata", "char", %objList);
      if(%objList.getSize() > 0)
      {
         %char = %objList.getID(0);
         tsNameObj(%char, "Mr.White");
         echo(%char.name);
      }
      tsDestroyObjList(%objList);
      
      // Check for Mr. Wong
      %objList = tsCreateObjList();
      tsFindObjTypeOnMap("mrwongdata", "char", %objList);
      if(%objList.getSize() > 0)
      {
         %char = %objList.getID(0);
         tsNameObj(%char, "Mr.Wong");
         echo(%char.name);
      }
      tsDestroyObjList(%objList);
      */
}
// Returns the bandit you have chosen, white or wong
function getWhiteOrWongChoice()
{
   if(WhiteChosen.isComplete()) {
      return ("mrwhite");
   }
   else {
      return ("mrwong");
   }
}
// Returns the bandit you have not chosen, white or wong
function getWhiteOrWongReject()
{
   if(WhiteChosen.isComplete()) {
      return ("mrwong");
   }
   else {
      return ("mrwhite");
   }
}
// Responsible for firing the town after return from white/wong hunt
function WhiteOrWongRevenge::onEnter(%this)
{
   Parent::onEnter(%this);
   
   // Create the fire disaster
   %scenario = new SLScenario() {
      stack = true;
      
      // Disaster fields
      addDisasterNode = "0 30 1";
      disasterAnimalRate     = "0 0";
      disasterBanditRate     = "0 0";
      disasterDroughtRate    = "0 0";
      disasterEarthquakeRate = "0 0";
      disasterFamineRate     = "0 0";
      disasterFireRate       = "100 0";
      disasterPlagueRate     = "0 0";
      disasterTornadoRate    = "0 0";
      disasterStack = $DisasterStack::Push;
   };
   %scenario.disasterFireScenario = new SLFireScenario() {
      chance = 100;
      duration = -1;
      
      startStrength = 1;
      
      spreadCount = 2;
      spreadTime = 15;
      spreadChance = 30;
      spreadRadius = 25;
      spreadStrength = 3;
      
      burnTime = 14;
      burnStrength = 1;
      burnMax = 2;
      
      // does no damage
      damageTime = 0.1;
      damageStrength = 0.2;
   };
   LoadScenario(%scenario);
   
   // Create fire disaster on all player buildings (start fire does this for you
   // with other building checks as well)
   %fire = DisasterManager.OnCreateDisaster();
   %bldgs = slgGetServerBuildingList();
   %count = %bldgs.getSize();
   for(%i = 0; %i < %count; %i++) {
      %bldgobj = %bldgs.getID(%i);
      setBuildingAblaze(%bldgobj, %fire);
   }
}
// Handles the dialog between white or wong and townsfolk
function WhiteOrWongBlameMadRussian::onEnter(%this)
{
   Parent::onEnter(%this);
   
   // Log start for prep quest
   tsAddQuestToTracker(true, $PrepForMadRussian::LogQuest, "", $PrepForMadRussian::LogDesc, $PrepForMadRussian::LogReward);
   tsReadyQuest($PrepForMadRussian::LogQuest);

   // If any team buildings are on fire
   if(areTeamBuildingsOnFire($OST_PLAYER)) {
      // Get random character
      %team  = tsCreateObjList();
      %chars = slgGetServerCharacterList();
      %chars.getTeamList($OST_PLAYER, %team);
      %speaker = %team.getRandomObject();
      tsDestroyObjList(%team);
      
      // Get white or wong
      %sidekick = getWhiteOrWongChoice();
               
      // Dialog exchange
      tsSendTaskPopUpDlg("ID_Campaign2", "id_wow_blamedlg1", $TaskButton::More, %sidekick);
      tsSendTaskPopUpDlg("ID_Campaign2", "id_wow_blamedlg2", $TaskButton::More, %speaker);
      tsSendTaskPopUpDlg("ID_Campaign2", "id_wow_blamedlg3", $TaskButton::Okay, %sidekick);
      
      // Log update about fire
      tsAddTaskToTracker($PrepForMadRussian::LogQuest, $PrepForMadRussian::LogBrief[0], $PrepForMadRussian::LogLong[0]);
   }
   
   // Mark this as complete
   tsCompleteVertexes("PrepForMadRussian", "WhiteOrWongBlameMadRussian");
}
// Completes once the town is no longer on fire
function WaitForTownFireExtinguish::onUpdate(%this)
{
   Parent::onUpdate(%this);
   
   // Done if true
   if(!areTeamBuildingsOnFire($OST_PLAYER)) {
      // Pop disaster stack
      %scenario = new SLScenario() {
         stack = true;
         disasterStack = $DisasterStack::Pop;
      };
      LoadScenario(%scenario);
      tsCompleteVertexes("PrepForMadRussian", "WaitForTownFireExtinguish");
   }
}
// Dialog to prepare for the mad russian capture. It is between white/wong and hero
function PrepForMadRussianDialog::onEnter(%this)
{
   Parent::onEnter(%this);
   
   %sidekick = getWhiteOrWongChoice();
   
   // Dialog exchange
   tsSendTaskPopUpDlg("ID_Campaign2", "id_wow_prepforrussian1", $TaskButton::More, %sidekick);
   tsSendTaskPopUpDlg("ID_Campaign2", "id_wow_prepforrussian2", $TaskButton::More, "HeroCharacter");
   tsSendTaskPopUpDlg("ID_Campaign2", "id_wow_prepforrussian3", $TaskButton::More, %sidekick);
   tsSendTaskPopUpDlg("ID_Campaign2", "id_wow_prepforrussian4", $TaskButton::Okay, "HeroCharacter");
   
   // Update log
   tsAddTaskToTracker($PrepForMadRussian::LogQuest, $PrepForMadRussian::LogBrief[1], $PrepForMadRussian::LogLong[1]);
   tsAddTaskToTracker($PrepForMadRussian::LogQuest, $PrepForMadRussian::LogBrief[2], $PrepForMadRussian::LogLong[2]);
   tsAddTaskToTracker($PrepForMadRussian::LogQuest, $PrepForMadRussian::LogBrief[3], $PrepForMadRussian::LogLong[3]);
   tsCompleteTaskInTracker($PrepForMadRussian::LogQuest, $PrepForMadRussian::LogBrief[0]);
   
   // Complete vertex
   tsCompleteVertexes("PrepForMadRussian", "PrepForMadRussianDialog");
}
// Waits for the sheriff and mayor to be hired before sending capture mad russian trigger
function WaitForSheriff::onEnter(%this)
{
   Parent::onEnter(%this);
   
   // Check if we already have sheriff
   %chars = slgGetServerCharacterList();
   %count = %chars.getSize();
   for(%i = 0; %i < %count; %i++) {
      %charobj = %chars.getID(%i);
      if(!%charobj.isOnTeam($OST_PLAYER)) {
         continue;
      }
      if(%charobj.isOfType("Nicesheriff") || %charobj.isOfType("Toughsheriff")) {
         break;
      }
   }
   
   // Have sheriff if true
   if(%i < %count) {
      tsCompleteVertexes("PrepForMadRussian", "WaitForSheriff");      
   }
}
function WaitForSheriff::onMessage(%this, %msg, %params)
{
   Parent::onMessage(%this, %msg, %params);
   if(%this.isFunctionComplete($TSF_CREATE, 0) 
   || %this.isFunctionComplete($TSF_CREATE, 1)) {
      tsCompleteVertexes("PrepForMadRussian", "WaitForSheriff");
   }
}
function WaitForSheriff::onExit(%this)
{
   Parent::onExit(%this);
   
   // Update log
   tsCompleteTaskInTracker($PrepForMadRussian::LogQuest, $PrepForMadRussian::LogBrief[2]);
}
function WaitForMayor::onEnter(%this)
{
   Parent::onEnter(%this);
   
   // Check if mayor already exists
   %bldgs = slgGetServerBuildingList();
   %count = %bldgs.getSize();
   for(%i = 0; %i < %count; %i++) {
      %bldgobj = %bldgs.getID(%i);
      if(!%bldgobj.isOnTeam($OST_PLAYER)) {
        continue;
      }
      if(%bldgobj.isOfType(TownHall)) {
         %bldgcmp = slgQueryInterface(%bldgobj, $CID_BUILDING);
         if(%bldgcmp.getEmployeeCount() > 0) {
            break;
         }
      }
   }
   
   // Done if true
   if(%i < %count) {
      tsCompleteVertexes("PrepForMadRussian", "WaitForMayor");
   }
}
function WaitForMayor::onExit(%this)
{
   Parent::onExit(%this);
   
   // Update log
   tsCompleteTaskInTracker($PrepForMadRussian::LogQuest, $PrepForMadRussian::LogBrief[1]);
}
// Wait for the train tracks to be purchased before sending capture mad russian trigger
function WaitForTrainTracks::onUpdate(%this)
{
   if(csIsCmdUpgradePurchased($CSUP_TRACK)) {
      tsCompleteVertexes("PrepForMadRussian", "WaitForTrainTracks");
   }
}
function WaitForTrainTracks::onExit(%this)
{
   Parent::onExit(%this);
   
   // Update log
   tsCompleteTaskInTracker($PrepForMadRussian::LogQuest, $PrepForMadRussian::LogBrief[3]);
}
// Responsible for sending trigger and launching the capture mad russian task
function MadRussianCaptureTrigger::onExit(%this)
{
   Parent::onEnter(%this);
   
   tsSendTaskClickDlg("ID_Campaign2madrussian", "id_mrc_trigger", $TaskButton::Accept, "HeroCharacter", "id_mrc_trigger");
}
function LoadMadRussianTask::onExit(%this)
{
   Parent::onExit(%this);
   
   // Launch mad russian scenario
   %scenario = new SLScenario() {
      stack   = true;
      mapName = "assets/data/missions/sandlot/capturemadrussian.mis";
      mapMinimap = "assets/client/ui/minimaps/madrussianminimap.png";
      mapMain = false;
      
      // Resources
      resourceGold       = "0 0";
      resourceWood       = "0 0";
      resourceFood       = "20 0";
      resourceFoodMax    = "20 0";
      resourceWater      = "0 0";
      resourceWaterMax   = "0 0";
      resourceHappiness  = "80 0";
      
      // Disaster fields
      addDisasterNode        = "0 100 0";
      disasterBanditRate     = "0 0";
      disasterDroughtRate    = "0 0";
      disasterEarthquakeRate = "0 0";
      disasterFamineRate     = "0 0";
      disasterFireRate       = "0 0";
      disasterPlagueRate     = "0 0";
      disasterTornadoRate    = "0 0";
      disasterStack = $DisasterStack::Push;
      
      // Units
      //neutralLawmen     = true;
      niceGunslinger    = true;
      toughGunslinger   = true;
      neutralGunslinger = true;
   };
   LoadScenario(%scenario, deactivateCampaign2Tasks, startMadRussianTasks, resetMadRussianTask);
   
   // initialize the world map images
   tutorialworldmap.visible = false;
   campaign1worldmap.visible = false;
   campaign2worldmap.visible = false;
   fullworldmap.visible = true;
   
   // update the campaign icons
   campaign2worldicon.visible = true;
   
   // update the satellite icons
   SetMadRussianSatellites(true);
}

//***************************************************************
//* Disasters
//***************************************************************

// add average disasters
function MainmapDisastersMedium()
{
   
   %scenario = new SLScenario()
   {
      // update disasters only; do not change the map
      stack = true;
      
      // every 2 minutes, a disaster can occur
      addDisasterNode = "0 70 2";
      
      // frequency pool, respawning time
      disasterBanditRate = "15 120";
      disasterDroughtRate = "15 100";
      disasterEarthquakeRate = "10 100";
      disasterFamineRate = "15 100";
      disasterFireRate = "15 100";
      disasterPlagueRate = "15 100";
      disasterTornadoRate = "15 100";
      
      disasterStack = $DisasterStack::Push;
   };
   
   // update the bandit scenario
   %scenario.disasterBanditScenario = new SLBanditAttackScenario()
   {
      chance = 25;
      duration = 1000;

      fadeTime = 1;
      goldMin = 0;
      goldMax = 100;
      goldLow = 5;
      goldHigh = 10;
      lowCount = 1;
      highCount = 3;

      happinessCount = -25;
      happinessIncrease = 0;
      happinessPlateau = 10;
      happinessDecrease = 0;
   };
   
   // update the drought scenario
   %scenario.disasterDroughtScenario = new SLDroughtScenario()
   {
      chance = 20;
      addRequirement = well;
      duration = 45;
      
      cost = 0.9;
   };
   
   // update the earthquake scenario
   %scenario.disasterEarthquakeScenario = new SLEarthquakeScenario()
   {
      chance = 15;
      duration = 5;
      
      shakeDistance = 0.4;
      damageLow = 25;
      damageHigh = 35;
   };
   
   // update the famine scenario
   %scenario.disasterFamineScenario = new SLFamineScenario()
   {
      chance = 45;
      //addRequirement = Granary;
      duration = 0;
      
      resource = $Resource::Food;
      cost = 0.50;
   };
   
   // update the fire scenario
   %scenario.disasterFireScenario = new SLFireScenario()
   {
      chance = 20;
      duration = -1;
      
      startStrength = 2;
      
      spreadCount = 2;
      spreadTime = 15;
      spreadChance = 40;
      spreadRadius = 25;
      spreadStrength = 1;
      
      burnTime = 15;
      burnStrength = 1;
      burnMax = 4;      
      
      damageTime = 0.4;
      damageStrength = 1;
   };
   
   // update the plague scenario
   %scenario.disasterPlagueScenario = new SLPlagueScenario()
   {
      chance = 45;
      addRequirement = Farm;
      addRequirement = Ranch;
      duration = 30;
      
      produceRate = 0.5;
      addProduce = "wheat";
      addProduce = "corn";
      addProduce = "pumpkin";
      addProduce = "chicken";
      addProduce = "pig";
      addProduce = "cow";
   };
   
   // update the tornado scenario
   %scenario.disasterTornadoScenario = new SLTornadoScenario()
   {
      object = "tornado";

      chance = 20;
      duration = 60;

      travelAngle = 35;
      travelRandom = 25;
      travelTimeLow = 3;
      travelTimeHigh = 6;
      travelSpeedLow = 3;
      travelSpeedHigh = 5;
      radius = 8;
      damage = 25;
   };
   
   LoadScenario(%scenario);
}

function Campaign2DisastersHigh()
{
   
   %scenario = new SLScenario()
   {
      // update disasters only; do not change the map
      stack = true;
      
      // every 1 minutes, a disaster can occur
      addDisasterNode = "0 60 2";
      
      // frequency pool, respawning time
      disasterBanditRate = "15 120";
      disasterDroughtRate = "15 100";
      disasterEarthquakeRate = "10 100";
      disasterFamineRate = "15 100";
      disasterFireRate = "15 100";
      disasterPlagueRate = "15 100";
      disasterTornadoRate = "15 100";
      
      disasterStack = $DisasterStack::Push;
   };
   
   // update the bandit scenario
   %scenario.disasterBanditScenario = new SLBanditAttackScenario()
   {
      chance = 35;
      duration = 1000;

      fadeTime = 1;
      goldMin = 0;
      goldMax = 100;
      goldLow = 5;
      goldHigh = 10;
      lowCount = 1;
      highCount = 3;

      happinessCount = -25;
      happinessIncrease = 0;
      happinessPlateau = 10;
      happinessDecrease = 0;
   };
   
   // update the drought scenario
   %scenario.disasterDroughtScenario = new SLDroughtScenario()
   {
      chance = 40;
      addRequirement = well;
      duration = 45;
      
      cost = 0.9;
   };
   
   // update the earthquake scenario
   %scenario.disasterEarthquakeScenario = new SLEarthquakeScenario()
   {
      chance = 25;
      duration = 5;
      
      shakeDistance = 0.4;
      damageLow = 25;
      damageHigh = 35;
   };
   
   // update the famine scenario
   %scenario.disasterFamineScenario = new SLFamineScenario()
   {
      chance = 45;
      //addRequirement = Granary;
      duration = 0;
      
      resource = $Resource::Food;
      cost = 0.50;
   };
   
   // update the fire scenario
   %scenario.disasterFireScenario = new SLFireScenario()
   {
      chance = 30;
      duration = -1;
      
      startStrength = 2;
      
      spreadCount = 2;
      spreadTime = 15;
      spreadChance = 40;
      spreadRadius = 25;
      spreadStrength = 1;
      
      burnTime = 15;
      burnStrength = 1;
      burnMax = 4;      
      
      damageTime = 0.4;
      damageStrength = 1;
   };
   
   // update the plague scenario
   %scenario.disasterPlagueScenario = new SLPlagueScenario()
   {
      chance = 45;
      addRequirement = Farm;
      addRequirement = Ranch;
      duration = 30;
      
      produceRate = 0.5;
      addProduce = "wheat";
      addProduce = "corn";
      addProduce = "pumpkin";
      addProduce = "chicken";
      addProduce = "pig";
      addProduce = "cow";
   };
   
   // update the tornado scenario
   %scenario.disasterTornadoScenario = new SLTornadoScenario()
   {
      object = "tornado";

      chance = 60;
      duration = 60;

      travelAngle = 35;
      travelRandom = 25;
      travelTimeLow = 3;
      travelTimeHigh = 6;
      travelSpeedLow = 3;
      travelSpeedHigh = 5;
      radius = 8;
      damage = 25;
   };
   
   LoadScenario(%scenario);
}
//*********************************************
//*  End Game Dialog
//*********************************************

function WW2EndGameDelay::onExit(%vertex)
{
   %wow = getWhiteOrWongChoice();   
   if(stricmp(%wow,"mrwong") == 0)
   {
      tsSendTaskPopUpDlg("ID_TASK_EndGame", "ID_endgamewongone", $TaskButton::More, "madrussian");
      tsSendTaskPopUpDlg("ID_TASK_EndGame", "ID_endgamehero", $TaskButton::More, "herocharacter");
      tsSendTaskPopUpDlg("ID_TASK_EndGame", "ID_endgamewongtwo", $TaskButton::More, "mrwong");
   }
   else
   {
      tsSendTaskPopUpDlg("ID_TASK_EndGame", "ID_endgamewhiteone", $TaskButton::More, "madrussian");
      tsSendTaskPopUpDlg("ID_TASK_EndGame", "ID_endgamehero", $TaskButton::More, "herocharacter");
      tsSendTaskPopUpDlg("ID_TASK_EndGame", "ID_endgamewhitetwo", $TaskButton::More, "mrwhite");
   }
   tsSendTaskPopUpDlg("ID_TASK_EndGame", "ID_endgameCongrats", $TaskButton::More, "herocharacter"); 
}
