
//------------------------------------------------------------------------------
function setUpFavPrefs()
{
   if($pref::FavCurrentSelect $= "")
      $pref::FavCurrentSelect = 0;   
   for(%i = 0; %i < 10; %i++)
   {
      if($pref::FavNames[%i] $= "")
         $pref::FavNames[%i] = "Favorite " @ %i + 1;
      if($pref::Favorite[%i] $= "")
         $pref::Favorite[%i] = "armor\tLight Armor";
   }
   if($pref::FavCurrentList $= "")
      $pref::FavCurrentList = 0;
}

$FavCurrent = 0;
setUpFavPrefs();

// ----------------------------------------------------------------------
// Armors
// ----------------------------------------------------------------------

$InvArmor[0] = "Scout";
$NameToInv["Scout"]  = "Light";
$InvArmor[1] = "Assault";
$NameToInv["Assault"] = "Medium";
$InvArmor[2] = "Engineer";
$NameToInv["Engineer"] = "Engineer";
$InvArmor[3] = "Juggernaut";
$NameToInv["Juggernaut"]  = "Heavy";

// ----------------------------------------------------------------------
// Weapons
// ----------------------------------------------------------------------

$InvWeapon[0] = "Blaster";
$NameToInv["Blaster"] = "Blaster";
$InvWeapon[1] = "Chaingun";
$NameToInv["Chaingun"] = "Chaingun";
$InvWeapon[2] = "Cone Rifle";
$NameToInv["Cone Rifle"] = "ConeRifle";
$InvWeapon[3] = "ELF Projector";
$NameToInv["ELF Projector"] = "ELFGun";
$InvWeapon[4] = "Flame Thrower";
$NameToInv["Flame Thrower"] = "Flamer";
$InvWeapon[5] = "Grenade Launcher";
$NameToInv["Grenade Launcher"] = "GrenadeLauncher";
$InvWeapon[6] = "Handheld Mortar";
$NameToInv["Handheld Mortar"] = "Mortar";
$NameToInv["Fusion Mortar"] = "Mortar";
$InvWeapon[7] = "Laser Rifle";
$NameToInv["Laser Rifle"] = "SniperRifle";
$InvWeapon[8] = "Magnum Pistol";
$NameToInv["Magnum Pistol"] = "Magnum";
$InvWeapon[9] = "Missile Launcher";
$NameToInv["Missile Launcher"] = "MissileLauncher";
$InvWeapon[10] = "Particle Cannon";
$NameToInv["Particle Cannon"] = "ParticleCannon";
$InvWeapon[11] = "Plasma Rifle";
$NameToInv["Plasma Rifle"] = "Plasma";
$InvWeapon[12] = "Shocklance";
$NameToInv["Shocklance"] = "ShockLance";
$InvWeapon[13] = "Sniper Rifle";
$NameToInv["Sniper Rifle"] = "Rifle";
$InvWeapon[14] = "Shotgun";
$NameToInv["Shotgun"] = "Shotgun";
$InvWeapon[15] = "Spinfusor";
$NameToInv["Spinfusor"] = "Disc";

// ----------------------------------------------------------------------
// Packs
// ----------------------------------------------------------------------

$InvPack[0] = "AA Turret Barrel";
$NameToInv["AA Turret Barrel"] = "AABarrelPack";
$InvPack[1] = "Ammunition Pack";
$NameToInv["Ammunition Pack"] = "AmmoPack";
$InvPack[2] = "Anti-Vehicle Mine";
$NameToInv["Anti-Vehicle Mine"] = "VehicleMine";
$InvPack[3] = "Auto-Rocket Pack";
$NameToInv["Auto-Rocket Pack"] = "AutoRocketPack";
$InvPack[4] = "Base Alarm";
$NameToInv["Base Alarm"] = "BaseAlarmPack";
$InvPack[5] = "Blast Wall";
$NameToInv["Blast Wall"] = "BlastWallPack";
$InvPack[6] = "Cloak Pack";
$NameToInv["Cloak Pack"] = "CloakingPack";
$InvPack[7] = "Deployable Inventory Station";
$NameToInv["Deployable Inventory Station"] = "InventoryDeployable";
$NameToInv["Inventory Station"] = "InventoryDeployable";
$InvPack[8] = "Deployable Turret Base";
$NameToInv["Deployable Turret Base"] = "DeployableTurretBase";
$InvPack[9] = "Depth Charge Turret Barrel";
$NameToInv["Depth Charge Turret Barrel"] = "DepthChargeBarrelPack";
$InvPack[10] = "ELF Turret Barrel";
$NameToInv["ELF Turret Barrel"] = "ELFBarrelPack";
$InvPack[11] = "Emergency Generator";
$NameToInv["Emergency Generator"] = "DeployGenItem";
$InvPack[12] = "Energy Pack";
$NameToInv["Energy Pack"] = "EnergyPack";
$InvPack[13] = "Forcefield Generator";
$NameToInv["Forcefield Generator"] = "ForceFieldDeployable";
$InvPack[14] = "Land Spike Turret";
$NameToInv["Land Spike Turret"] = "TurretOutdoorDeployable";
$NameToInv["Landspike Turret"] = "TurretOutdoorDeployable";
$InvPack[15] = "Missile Command Station";
$NameToInv["Missile Command Station"] = "MCSPack";
$InvPack[16] = "Missile Turret Barrel";
$NameToInv["Missile Turret Barrel"] = "MissileBarrelPack";
$InvPack[17] = "Mortar Turret Barrel";
$NameToInv["Mortar Turret Barrel"] = "MortarBarrelPack";
$InvPack[18] = "Motion Sensor Pack";
$NameToInv["Motion Sensor Pack"] = "MotionSensorDeployable";
$InvPack[19] = "Plasma Turret Barrel";
$NameToInv["Plasma Turret Barrel"] = "PlasmaBarrelPack";
$InvPack[20] = "Pulse Sensor Pack";
$NameToInv["Pulse Sensor Pack"] = "PulseSensorDeployable";
$InvPack[21] = "Repair Drone";
$NameToInv["Repair Drone"] = "RepairDronePack";
$InvPack[22] = "Repair Pack";
$NameToInv["Repair Pack"] = "RepairPack";
$InvPack[23] = "Satchel Charge";
$NameToInv["Satchel Charge"] = "SatchelCharge";
$InvPack[24] = "Sensor Jammer";
$NameToInv["Sensor Jammer"] = "DeployableSensorJammerPack";
$InvPack[25] = "Sensor Jammer Pack";
$NameToInv["Sensor Jammer Pack"] = "SensorJammerPack";
$InvPack[26] = "Sensor Tap";
$NameToInv["Sensor Tap"] = "SensorTapPack";
$InvPack[27] = "Shield Pack";
$NameToInv["Shield Pack"] = "ShieldPack";
$InvPack[28] = "Shoulder Mounted Missiles";
$NameToInv["Shoulder Mounted Missiles"] = "SMissilePack";
$InvPack[29] = "Solid Rocket Pack";
$NameToInv["Solid Rocket Pack"] = "JetPack";
$InvPack[30] = "Spider Clamp Turret";
$NameToInv["Spider Clamp Turret"] = "TurretIndoorDeployable";
$InvPack[31] = "Springboard";
$NameToInv["Springboard"] = "SpringboardPack";
$InvPack[32] = "Target Acquistion Gear";
$NameToInv["Target Acquistion Gear"] = "TAG";
$InvPack[33] = "Teleporter Pad";
$NameToInv["Teleporter Pad"] = "TeleporterPack";

// Packs allowed in None Team Play
$NTInvPack[0] = "Energy Pack";
$NTInvPack[1] = "Repair Pack";
$NTInvPack[2] = "Shield Pack";
$NTInvPack[3] = "Cloak Pack";
$NTInvPack[4] = "Ammunition Pack";
$NTInvPack[5] = "Satchel Charge";
$NTInvPack[6] = "Shoulder Mounted Missiles";
$NTInvPack[7] = "Auto-Rocket Pack";

// ----------------------------------------------------------------------
// Grenades
// ----------------------------------------------------------------------

$InvGrenade[0] = "Concussion Grenade";
$NameToInv["Concussion Grenade"] = "ConcussionGrenade";
$InvGrenade[1] = "ECM Grenade";
$NameToInv["ECM Grenade"] = "ECMGrenade";
$InvGrenade[2] = "EMP Grenade";
$NameToInv["EMP Grenade"] = "EMPGrenade";
$InvGrenade[3] = "Flare Grenade";
$NameToInv["Flare Grenade"] = "FlareGrenade";
$InvGrenade[4] = "Hand Grenade";
$NameToInv["Hand Grenade"] = "Grenade";
$InvGrenade[5] = "Incendiary Grenade";
$NameToInv["Incendiary Grenade"] = "IncendiaryGrenade";
$InvGrenade[6] = "Mini-Camera";
$NameToInv["Camera Grenade"] = "CameraGrenade";
$NameToInv["Mini-Camera"] = "CameraGrenade";
$InvGrenade[7] = "Shaped Charge";
$NameToInv["Shaped Charge"] = "PlasticExplosive";
$InvGrenade[8] = "Stun Grenade";
$NameToInv["Stun Grenade"] = "FlashGrenade";

// ----------------------------------------------------------------------
// Mines
// ----------------------------------------------------------------------

$InvMine[0] = "Concussion Mine";
$NameToInv["Concussion Mine"] = "ConcussionMine";
$InvMine[1] = "EMP Mine";
$NameToInv["EMP Mine"] = "EMPMine";
$InvMine[2] = "Incendiary Mine";
$NameToInv["Incendiary Mine"] = "IncendiaryMine";
$InvMine[3] = "Mine";
$NameToInv["Mine"] = "Mine";
$InvMine[4] = "Stun Mine";
$NameToInv["Stun Mine"] = "StunMine";

// ----------------------------------------------------------------------
// Specials
// ----------------------------------------------------------------------

$InvSpecial[0] = "Code Breaker";
$NameToInv["Code Breaker"] = "CodeBreaker";
$InvSpecial[1] = "Engineer's Assistant";
$NameToInv["Engineer's Assistant"] = "EngAssistant";
$InvSpecial[2] = "Grappling Core";
$NameToInv["Grappling Core"] = "GrapplingHook";
$InvSpecial[3] = "Hologram Projector";
$NameToInv["Hologram Projector"] = "Hologram";
$InvSpecial[4] = "Inertial Dampner";
$NameToInv["Inertial Dampner"] = "InertialDampner";
$InvSpecial[5] = "Light Shield";
$NameToInv["Light Shield"] = "LightShield";
$InvSpecial[6] = "Speed Booster";
$NameToInv["Speed Booster"] = "SpeedBooster";
$InvSpecial[7] = "Stimulant Kit";
$NameToInv["Stimulant Kit"] = "Adren";
$InvSpecial[8] = "Targeting Beacons";
$NameToInv["Targeting Beacons"] = "TargetingBeacon";
$InvSpecial[9] = "Weapons Control System";
$NameToInv["Weapons Control System"] = "WCS";

$InvBanList[DeployInv, "InventoryDeployable"] = 1;
$InvBanList[DeployInv, "DeployGenItem"] = 1;
$InvBanList[DeployInv, "MCSPack"] = 1;

$TeamTeleporterMax = 6;
//------------------------------------------------------------------------------
function InventoryScreen::loadHud( %this, %tag )
{
   $Hud[%tag] = InventoryScreen;
   $Hud[%tag].childGui = INV_Root;
   $Hud[%tag].parent = INV_Root;
}

//------------------------------------------------------------------------------
function InventoryScreen::setupHud( %this, %tag )
{
   %favListStart = $pref::FavCurrentList * 10;
   %this.selId = $pref::FavCurrentSelect - %favListStart + 1;

   // Add the list menu:
   $Hud[%tag].staticData[0, 0] = new ShellPopupMenu(INV_ListMenu) 
   {
      profile = "ShellPopupProfile";
      horizSizing = "right";
      vertSizing = "bottom";
      position = "16 313";
      extent = "170 36";
      minExtent = "8 8";
      visible = "1";
      setFirstResponder = "0";
      modal = "1";
      helpTag = "0";
      maxPopupHeight = "220";
      text = "";
   };
   
   // Add favorite tabs:  
   for( %i = 0; %i < 10; %i++ )
   {
      %yOffset = ( %i * 30 ) + 10;
      $Hud[%tag].staticData[0, %i + 1] = new ShellTabButton() {
         profile = "ShellTabProfile";
         horizSizing = "right";
         vertSizing = "bottom";
         position = "4 " @ %yOffset;
         extent = "206 38";
         minExtent = "8 8";
         visible = "1";
         setFirstResponder = "0";
         modal = "1";
         helpTag = "0";
         command = "InventoryScreen.onTabSelect(" @ %favListStart + %i @ ");";
         text = strupr( $pref::FavNames[%favListStart + %i] );
      };
      $Hud[%tag].staticData[0, %i + 1].setValue( ( %favListStart + %i ) == $pref::FavCurrentSelect );
            
      $Hud[%tag].parent.add( $Hud[%tag].staticData[0, %i + 1] );
   }
 
   %text = "Favorites " @ %favListStart + 1 SPC "-" SPC %favListStart + 10;
   $Hud[%tag].staticData[0, 0].onSelect( $pref::FavCurrentList, %text, true );
 
   $Hud[%tag].parent.add( $Hud[%tag].staticData[0, 0] );

   // Add the SAVE button:
   $Hud[%tag].staticData[1, 0] = new ShellBitmapButton() 
   {
      profile = "ShellButtonProfile";
      horizSizing = "right";
      vertSizing = "bottom";
      position = "409 295";
      extent = "75 38";
      minExtent = "8 8";
      visible = "1";
      setFirstResponder = "0";
      modal = "1";
      helpTag = "0";
      command = "saveFavorite();";
      text = "SAVE";
   };      
   
   // Add the name edit control:
   $Hud[%tag].staticData[1, 1] = new ShellTextEditCtrl() 
   {
      profile = "NewTextEditProfile";
      horizSizing = "right";
      vertSizing = "bottom";
      position = "217 295";
      extent = "196 38";
      minExtent = "8 8";
      visible = "1";
      altCommand = "saveFavorite()";
      setFirstResponder = "1";
      modal = "1";
      helpTag = "0";
      historySize = "0";
      maxLength = "16";
   };
   
   $Hud[%tag].staticData[1, 1].setValue( $pref::FavNames[$pref::FavCurrentSelect] );
   
   $Hud[%tag].parent.add( $Hud[%tag].staticData[1, 0] );
   $Hud[%tag].parent.add( $Hud[%tag].staticData[1, 1] );
}

//------------------------------------------------------------------------------
function InventoryScreen::addLine( %this, %tag, %lineNum, %type, %count )
{
   $Hud[%tag].count = %count;

   // Add label:
   %yOffset = ( %lineNum * 26 ) + 28;
   $Hud[%tag].data[%lineNum, 0] = new GuiTextCtrl() 
   {
      profile = "ShellTextRightProfile";
      horizSizing = "right";
      vertSizing = "bottom";
      position = "228 " @ %yOffset;
      extent = "80 22";
      minExtent = "8 8";
      visible = "1";
      setFirstResponder = "0";
      modal = "1";
      helpTag = "0";
      text = "";
   };

   // Add drop menu:
   $Hud[%tag].data[%lineNum, 1] = new ShellPopupMenu(INV_Menu) 
   {
      profile = "ShellPopupProfile";
      horizSizing = "right";
      vertSizing = "bottom";
      position = "305 " @ %yOffset - 9;
      extent = "180 36";
      minExtent = "8 8";
      visible = "1";
      setFirstResponder = "0";
      modal = "1";
      helpTag = "0";
      maxPopupHeight = "200";
      text = "";
      type = %type;
   };

   return 2;
}
   
//------------------------------------------------------------------------------
function InventoryScreen::updateHud( %this, %client, %tag )
{
   %noSniperRifle = true;
   %armor = getArmorDatablock( %client, $NameToInv[%client.favorites[0]] );
   if ( %client.lastArmor !$= %armor )
   {
      %client.lastArmor = %armor;
      for ( %x = 0; %x < %client.lastNumFavs; %x++ )
         messageClient( %client, 'RemoveLineHud', "", 'inventoryScreen', %x );
      %setLastNum = true;
   }

   %cmt = $CurrentMissionType;
//Create - ARMOR - List
   %armorList = %client.favorites[0];
   for ( %y = 0; $InvArmor[%y] !$= ""; %y++ )
      if ( $InvArmor[%y] !$= %client.favorites[0] )  
         %armorList = %armorList TAB $InvArmor[%y];

//Create - WEAPON - List
   for ( %y = 0; $InvWeapon[%y] !$= ""; %y++ )
   {
      %notFound = true;
      for ( %i = 0; %i < getFieldCount( %client.weaponIndex ); %i++ )
      {
         %WInv = $NameToInv[$InvWeapon[%y]];
         if ( ( $InvWeapon[%y] $= %client.favorites[getField( %client.weaponIndex,%i )] ) || !%armor.max[%WInv] )  
         {
            %notFound = false;
            break;
         }
         else if ( "SniperRifle" $= $NameToInv[%client.favorites[getField( %client.weaponIndex,%i )]] )
         {
            %noSniperRifle = false;
            %packList = "noSelect\tEnergy Pack\tEnergy Pack must be used when \tLaser Rifle is selected!";     
            %client.favorites[getField(%client.packIndex,0)] = "Energy Pack";
         }   
      }

      if ( !($InvBanList[%cmt, %WInv]) )
      {
         if ( %notFound && %weaponList $= "" )
            %weaponList = $InvWeapon[%y];
         else if ( %notFound )
            %weaponList = %weaponList TAB $InvWeapon[%y];
      }
   }

//Create - PACK - List
   if ( %noSniperRifle )
   {
      if ( getFieldCount( %client.packIndex ) )
         %packList = %client.favorites[getField( %client.packIndex, 0 )];
      else
      {
         %packList = "EMPTY";
         %client.numFavs++;
      }
      for ( %y = 0; $InvPack[%y] !$= ""; %y++ )
      {
         %PInv = $NameToInv[$InvPack[%y]];
         if ( ( $InvPack[%y] !$= %client.favorites[getField( %client.packIndex, 0 )]) && 
         %armor.max[%PInv] && !($InvBanList[%cmt, %PInv]))  
            %packList = %packList TAB $Invpack[%y];
      }
   }   
//Create - GRENADE - List
   for ( %y = 0; $InvGrenade[%y] !$= ""; %y++ )
   {
      %notFound = true;
      for(%i = 0; %i < getFieldCount( %client.grenadeIndex ); %i++)
      {
         %GInv = $NameToInv[$InvGrenade[%y]];
         if ( ( $InvGrenade[%y] $= %client.favorites[getField( %client.grenadeIndex, %i )] ) || !%armor.max[%GInv] )  
         {
            %notFound = false;
            break;
         }
      }
      if ( !($InvBanList[%cmt, %GInv]) )
      { 
         if ( %notFound && %grenadeList $= "" )
            %grenadeList = $InvGrenade[%y];
         else if ( %notFound )
            %grenadeList = %grenadeList TAB $InvGrenade[%y];
      }
   }

//Create - MINE - List
   for ( %y = 0; $InvMine[%y] !$= "" ; %y++ )
   {
      %notFound = true;
      %MInv = $NameToInv[$InvMine[%y]];
      for ( %i = 0; %i < getFieldCount( %client.mineIndex ); %i++ )
         if ( ( $InvMine[%y] $= %client.favorites[getField( %client.mineIndex, %i )] ) || !%armor.max[%MInv] )  
         {
            %notFound = false;
            break;
         }
      
      if ( !($InvBanList[%cmt, %MInv]) )
      {
         if ( %notFound && %mineList $= "" )
            %mineList = $InvMine[%y];
         else if ( %notFound )
            %mineList = %mineList TAB $InvMine[%y];
      }
   }
   %client.numFavsCount++;
   messageClient( %client, 'SetLineHud', "", %tag, 0, "Armor:", %armorList, armor, %client.numFavsCount );
   %lineCount = 1;

   for ( %x = 0; %x < %armor.maxWeapons; %x++ )
   {
      %client.numFavsCount++;
      if ( %x < getFieldCount( %client.weaponIndex ) )
      {
         %list = %client.favorites[getField( %client.weaponIndex,%x )];
         if ( %list $= Invalid )
         {
            %client.favorites[%client.numFavs] = "INVALID";
            %client.weaponIndex = %client.weaponIndex TAB %client.numFavs;
         }   
      }
      else
      {
         %list = "EMPTY";
         %client.favorites[%client.numFavs] = "EMPTY";
         %client.weaponIndex = %client.weaponIndex TAB %client.numFavs;
         %client.numFavs++;
      }
      if ( %list $= empty )
         %list = %list TAB %weaponList;
      else
         %list = %list TAB %weaponList TAB "EMPTY";
      messageClient( %client, 'SetLineHud', "", %tag, %x + %lineCount, "Weapon Slot " @ %x + 1 @ ": ", %list , weapon, %client.numFavsCount );
   }
   %lineCount = %lineCount + %armor.maxWeapons;
   
   %client.numFavsCount++;
   if ( getField( %packList, 0 ) !$= empty && %noSniperRifle )
      %packList = %packList TAB "EMPTY";
   %packText = %packList;
   %packOverFlow = "";
   if ( strlen( %packList ) > 255 )
   {
      %packText = getSubStr( %packList, 0, 255 );
      %packOverFlow = getSubStr( %packList, 255, 512 );
   }
   messageClient( %client, 'SetLineHud', "", %tag, %lineCount, "Pack:", %packText, pack, %client.numFavsCount, %packOverFlow );
   %lineCount++;
   
   for( %x = 0; %x < %armor.maxGrenades; %x++ )
   {
      %client.numFavsCount++;
      if ( %x < getFieldCount( %client.grenadeIndex ) )
      {
         %list = %client.favorites[getField( %client.grenadeIndex, %x )];
         if (%list $= Invalid)
         {
            %client.favorites[%client.numFavs] = "INVALID";
            %client.grenadeIndex = %client.grenadeIndex TAB %client.numFavs;
         }
      }
      else
      {
         %list = "EMPTY";
         %client.favorites[%client.numFavs] = "EMPTY";
         %client.grenadeIndex = %client.grenadeIndex TAB %client.numFavs;
         %client.numFavs++;
      }
      
      if ( %list $= empty )
         %list = %list TAB %grenadeList;
      else
         %list = %list TAB %grenadeList TAB "EMPTY";

      messageClient( %client, 'SetLineHud', "", %tag, %x + %lineCount, "Grenade:", %list, grenade, %client.numFavsCount );
   }
   %lineCount = %lineCount + %armor.maxGrenades;
   
   for ( %x = 0; %x < %armor.maxMines; %x++ )
   {
      %client.numFavsCount++;
      if ( %x < getFieldCount( %client.mineIndex ) )
      {
         %list = %client.favorites[getField( %client.mineIndex, %x )];
         if ( %list $= Invalid )
         {
            %client.favorites[%client.numFavs] = "INVALID";
            %client.mineIndex = %client.mineIndex TAB %client.numFavs;
         }
      }
      else
      {
         %list = "EMPTY";
         %client.favorites[%client.numFavs] = "EMPTY";
         %client.mineIndex = %client.mineIndex TAB %client.numFavs;
         %client.numFavs++;
      }
      
      if ( %list !$= Invalid )
      {
         if ( %list $= empty )
            %list = %list TAB %mineList;
         else if ( %mineList !$= "" )
            %list = %list TAB %mineList TAB "EMPTY";
         else 
            %list = %list TAB "EMPTY";
      }
         
      messageClient( %client, 'SetLineHud', "", %tag, %x + %lineCount, "Mine:", %list, mine, %client.numFavsCount );
   }

   if ( %setLastNum )
      %client.lastNumFavs = %client.numFavs;
}

//------------------------------------------------------------------------------
function buyFavorites(%client)
{
   // don't forget -- for many functions, anything done here also needs to be done
   // below in buyDeployableFavorites !!!
   %client.player.clearInventory();
   %client.setWeaponsHudClearAll();
   %cmt = $CurrentMissionType;

   %curArmor = %client.player.getDatablock();
   %curDmgPct = getDamagePercent(%curArmor.maxDamage, %client.player.getDamageLevel());
   
   // armor
   %client.player.getDataBlock().UnMountEngineerModel(%client.player);

   %client.armor = $NameToInv[%client.favorites[0]];
   %client.player.setArmor( %client.armor );
   %newArmor = %client.player.getDataBlock();

   %client.player.getDataBlock().MountEngineerModel(%client.player);

   %client.player.setDamageLevel(%curDmgPct * %newArmor.maxDamage);

   // weapons
   for(%i = 0; %i < getFieldCount( %client.weaponIndex ); %i++)
   {
      %inv = $NameToInv[%client.favorites[getField( %client.weaponIndex, %i )]];
      %client.player.setInventory(%inv, 1);
      %AmmoName = %inv.image.ammo;
      %PlayerMax = %client.player.getDataBlock().max[%AmmoName];
      %client.player.setInventory(%AmmoName, %PlayerMax * 2);
   }
   %client.player.weaponCount = getFieldCount( %client.weaponIndex );

   // pack
   %pCh = $NameToInv[%client.favorites[%client.packIndex]];
   if ( %pCh $= "" )
      %client.clearBackpackIcon();
   else
      %client.player.setInventory( %pCh, 1 );

   // if this pack is a deployable that has a team limit, warn the purchaser
	// if it's a deployable turret, the limit depends on the number of players (deployables.cs)
	if(%pCh $= "TurretIndoorDeployable" || %pCh $= "TurretOutdoorDeployable")
		%maxDep = countTurretsAllowed(%pCh);
	else
	   %maxDep = $TeamDeployableMax[%pCh];

   if(%maxDep !$= "")
   {
      %depSoFar = $TeamDeployedCount[%client.player.team, %pCh];
      %packName = %client.favorites[%client.packIndex];

      if(Game.numTeams > 1)
         %msTxt = "Your team has "@%depSoFar@" of "@%maxDep SPC %packName@"s deployed.";
      else
         %msTxt = "You have deployed "@%depSoFar@" of "@%maxDep SPC %packName@"s.";

      messageClient(%client, 'MsgTeamDepObjCount', %msTxt);
   }

   // grenades
   for ( %i = 0; %i < getFieldCount( %client.grenadeIndex ); %i++ )
      %client.player.setInventory( $NameToInv[%client.favorites[getField( %client.grenadeIndex,%i )]], 30 );

   // if player is buying cameras, show how many are already deployed
   if(%client.favorites[%client.grenadeIndex] $= "Deployable Camera")
   {
      %maxDep = $TeamDeployableMax[DeployedCamera];
      %depSoFar = $TeamDeployedCount[%client.player.team, DeployedCamera];
      if(Game.numTeams > 1)
         %msTxt = "Your team has "@%depSoFar@" of "@%maxDep@" Deployable Cameras placed.";
      else
         %msTxt = "You have placed "@%depSoFar@" of "@%maxDep@" Deployable Cameras.";
      messageClient(%client, 'MsgTeamDepObjCount', %msTxt);
   }

   // mines
   for ( %i = 0; %i < getFieldCount( %client.mineIndex ); %i++ )
      %client.player.setInventory( $NameToInv[%client.favorites[getField( %client.mineIndex,%i )]], 30 );
         
   // miscellaneous stuff -- Repair Kit, Beacons, Targeting Laser
   if ( !($InvBanList[%cmt, RepairKit]) )
      %client.player.setInventory( RepairKit, 1 );
   if ( !($InvBanList[%cmt, Beacon]) )
      %client.player.setInventory( Beacon, 400 );
   if ( !($InvBanList[%cmt, TargetingLaser]) )
      %client.player.setInventory( TargetingLaser, 1 );

   // ammo pack pass -- hack! hack!
   if( %pCh $= "AmmoPack" )
      invAmmoPackPass(%client);
}

//------------------------------------------------------------------------------
function buyDeployableFavorites(%client)
{
   %player = %client.player;
	%prevPack = %player.getMountedImage($BackpackSlot);
   %player.clearInventory();
   %client.setWeaponsHudClearAll();
   %cmt = $CurrentMissionType;

   // players cannot buy armor from deployable inventory stations
	%weapCount = 0;
   for ( %i = 0; %i < getFieldCount( %client.weaponIndex ); %i++ )
   {
      %inv = $NameToInv[%client.favorites[getField( %client.weaponIndex, %i )]];
      if ( !($InvBanList[DeployInv, %inv]) )
      {
         %player.setInventory( %inv, 1 );
			// increment weapon count if current armor can hold this weapon
         if(%player.getDatablock().max[%inv] > 0)      
				%weapCount++;
         switch$ ( %inv )
         {
            case Plasma:
               %player.setInventory( PlasmaAmmo,400 );
            case Disc:
               %player.setInventory( DiscAmmo, 400 );
            case GrenadeLauncher:
               %player.setInventory( GrenadeLauncherAmmo, 400 );
            case Mortar:
               %player.setInventory( MortarAmmo, 400 );
            case MissileLauncher:
               %player.setInventory( MissileLauncherAmmo, 400 );
            case Chaingun:
               %player.setInventory( ChaingunAmmo, 400 );
         }
			if(%weapCount >= %player.getDatablock().maxWeapons)
				break;
      }
   }
   %player.weaponCount = %weapCount;
   // give player the grenades and mines they chose, beacons, and a repair kit
   for ( %i = 0; %i < getFieldCount( %client.grenadeIndex ); %i++)
   {   
      %GInv = $NameToInv[%client.favorites[getField( %client.grenadeIndex, %i )]];
      if ( !($InvBanList[DeployInv, %GInv]) )
         %player.setInventory( %GInv, 30 );
   }

   // if player is buying cameras, show how many are already deployed
   if(%client.favorites[%client.grenadeIndex] $= "Deployable Camera")
   {
      %maxDep = $TeamDeployableMax[DeployedCamera];
      %depSoFar = $TeamDeployedCount[%client.player.team, DeployedCamera];
      if(Game.numTeams > 1)
         %msTxt = "Your team has "@%depSoFar@" of "@%maxDep@" Deployable Cameras placed.";
      else
         %msTxt = "You have placed "@%depSoFar@" of "@%maxDep@" Deployable Cameras.";
      messageClient(%client, 'MsgTeamDepObjCount', %msTxt);
   }

   for ( %i = 0; %i < getFieldCount( %client.mineIndex ); %i++ )
   {
      %MInv = $NameToInv[%client.favorites[getField( %client.mineIndex, %i )]];
      if ( !($InvBanList[DeployInv, %MInv]) )
         %player.setInventory( %MInv, 30 );
   }
   if ( !($InvBanList[DeployInv, Beacon]) && !($InvBanList[%cmt, Beacon]) )
      %player.setInventory( Beacon, 400 );
   if ( !($InvBanList[DeployInv, RepairKit]) && !($InvBanList[%cmt, RepairKit]) )
      %player.setInventory( RepairKit, 1 );
   if ( !($InvBanList[DeployInv, TargetingLaser]) && !($InvBanList[%cmt, TargetingLaser]) )
      %player.setInventory( TargetingLaser, 1 );

   // players cannot buy deployable station packs from a deployable inventory station
   %packChoice = $NameToInv[%client.favorites[%client.packIndex]];
   if ( !($InvBanList[DeployInv, %packChoice]) )
      %player.setInventory( %packChoice, 1 );

   // if this pack is a deployable that has a team limit, warn the purchaser
	// if it's a deployable turret, the limit depends on the number of players (deployables.cs)
	if(%packChoice $= "TurretIndoorDeployable" || %packChoice $= "TurretOutdoorDeployable")
		%maxDep = countTurretsAllowed(%packChoice);
	else
	   %maxDep = $TeamDeployableMax[%packChoice];
   if((%maxDep !$= "") && (%packChoice !$= "InventoryDeployable"))
   {
      %depSoFar = $TeamDeployedCount[%client.player.team, %packChoice];
      %packName = %client.favorites[%client.packIndex];

      if(Game.numTeams > 1)
         %msTxt = "Your team has "@%depSoFar@" of "@%maxDep SPC %packName@"s deployed.";
      else
         %msTxt = "You have deployed "@%depSoFar@" of "@%maxDep SPC %packName@"s.";

      messageClient(%client, 'MsgTeamDepObjCount', %msTxt);
   }

	if(%prevPack > 0)
	{
		// if player had a "forbidden" pack (such as a deployable inventory station)
		// BEFORE visiting a deployed inventory station AND still has that pack chosen
		// as a favorite, give it back
		if((%packChoice $= %prevPack.item) && ($InvBanList[DeployInv, %packChoice]))
	      %player.setInventory( %prevPack.item, 1 );
	}

   if(%packChoice $= "AmmoPack")
      invAmmoPackPass(%client);
}

function invAmmoPackPass(%client)
{
   // "normal" ammo stuff (everything but mines and grenades)
   for ( %idx = 0; %idx < $numAmmoItems; %idx++ ) 
   {
      %ammo = $AmmoItem[%idx];
      %client.player.incInventory(%ammo, AmmoPack.max[%ammo]);
   }

   // first find out what type of grenade the player has selected
   %grenFav = %client.favorites[getField(%client.grenadeIndex, 0)];
   if((%grenFav !$= "EMPTY") && (%grenFav !$= "INVALID"))
      %client.player.incInventory($NameToInv[%grenFav], AmmoPack.max[$NameToInv[%grenFav]]);

   // now the same check for mines
   %mineFav = %client.favorites[getField(%client.mineIndex, 0)];
   if((%mineFav !$= "EMPTY") && (%mineFav !$= "INVALID") && !($InvBanList[%cmt, Mine]))
      %client.player.incInventory($NameToInv[%mineFav], AmmoPack.max[$NameToInv[%mineFav]]);
}

//------------------------------------------------------------------------------
function loadFavorite( %index, %echo )
{
   $pref::FavCurrentSelect = %index;
   %list = mFloor( %index / 10 );

   if ( isObject( $Hud['inventoryScreen'] ) )
   {
      // Deselect the old tab:
      if ( InventoryScreen.selId !$= "" )
         $Hud['inventoryScreen'].staticData[0, InventoryScreen.selId].setValue( false );

      // Make sure we are looking at the same list:
      if ( $pref::FavCurrentList != %list )
      {
         %favListStart = %list * 10;
         %text = "Favorites " @ %favListStart + 1 SPC "-" SPC %favListStart + 10;
         $Hud['inventoryScreen'].staticData[0, 0].onSelect( %list, %text, true );
      }

      // Select the new tab:
      %tab = $pref::FavCurrentSelect - ( $pref::FavCurrentList * 10 ) + 1;
      InventoryScreen.selId = %tab;
      $Hud['inventoryScreen'].staticData[0, %tab].setValue( true );

      // Update the Edit Name field:
      $Hud['inventoryScreen'].staticData[1, 1].setValue( $pref::FavNames[%index] );
   }

   if ( %echo )
      addMessageHudLine( "Inventory set \"" @ $pref::FavNames[%index] @ "\" selected." );

   commandToServer( 'setClientFav', $pref::Favorite[%index] );   
}

//------------------------------------------------------------------------------
function saveFavorite()
{
   if ( $pref::FavCurrentSelect !$= "" )
   {
      %favName = $Hud['inventoryScreen'].staticData[1, 1].getValue();
      $pref::FavNames[$pref::FavCurrentSelect] = %favName;
      $Hud['inventoryScreen'].staticData[0, $pref::FavCurrentSelect - ($pref::FavCurrentList * 10) + 1].setText( strupr( %favName ) );
      //$Hud[%tag].staticData[1, 1].setValue( %favName );
      %favList = $Hud['inventoryScreen'].data[0, 1].type TAB $Hud['inventoryScreen'].data[0, 1].getValue();
      for ( %i = 1; %i < $Hud['inventoryScreen'].count; %i++ )
      {
         %name = $Hud['inventoryScreen'].data[%i, 1].getValue();
         if ( %name $= invalid )
            %name = "EMPTY";
         %favList = %favList TAB $Hud['inventoryScreen'].data[%i, 1].type TAB %name;
      }
      $pref::Favorite[$pref::FavCurrentSelect] = %favList;
      echo("exporting pref::* to ClientPrefs.cs");
      export("$pref::*", "prefs/ClientPrefs.cs", False);
   }
//   else
//      addMessageHudLine("Must First Select A Favorite Button.");
}

//------------------------------------------------------------------------------
function addQuickPackFavorite( %pack, %item )
{
	// this has been such a success it has been changed to handle grenades 
	// and other equipment as well as packs so everything seems to be called 'pack' 
	// including the function itself. The default IS pack

	if(%item $= "")
		%item = "Pack";
	%packFailMsg = "You cannot use that equipment with your selected loadout.";
	if ( !isObject($Hud['inventoryScreen'].staticData[1, 1]) || $Hud['inventoryScreen'].staticData[1, 1].getValue() $= ""  ) 
	{
		//if the player hasnt brought up the inv screen we use his current fav
		%currentFav = $pref::Favorite[$pref::FavCurrentSelect];
		//echo(%currentFav);

		for ( %i = 0; %i < getFieldCount( %currentFav ); %i++ ) 
		{
			%type = getField( %currentFav, %i );
			%equipment = getField( %currentFav, %i++ );
			
			%invalidPack = checkPackValidity(%pack, %equipment, %item );
			if(%invalidPack)
			{
				addMessageHudLine( %packFailMsg );
				return;
			
			}
		// Success--------------------------------------------------
			if ( %type $= %item )
				%favList = %favList @ %type TAB %pack @ "\t";
			else 
				%favList = %favList  @ %type TAB %equipment @ "\t";  
		}
		//echo(%favList);
	}
	else 
	{
		//otherwise we go with whats on the invScreen (even if its asleep)
		%armor =  $Hud['inventoryScreen'].data[0, 1].getValue();
		
		// check pack validity with armor
		%invalidPack = checkPackValidity(%pack, %armor, %item );
		if(%invalidPack)
		{
			addMessageHudLine( %packFailMsg );
			return;
		
		}
	   %favList = $Hud['inventoryScreen'].data[0, 1].type TAB %armor;
		for ( %i = 1; %i < $Hud['inventoryScreen'].count; %i++ ) 
		{
			//echo( $Hud['inventoryScreen'].Data[%i, 1].type);
			%type = $Hud['inventoryScreen'].data[%i, 1].type;
			%equipment = $Hud['inventoryScreen'].data[%i, 1].getValue();

			if(%type $= %item)
				%equipment = %pack;
			
		// Special Cases again------------------------------------------------
			%invalidPack = checkPackValidity(%pack, %equipment, %item );
			if(%invalidPack)
			{
				addMessageHudLine( %packFailMsg );
				return;
			
			}

			%favList = %favList TAB %type TAB %equipment;
		}
		//echo(%favList);
	}
	commandToServer( 'setClientFav', %favList );

	//we message the player real nice like
	addMessageHudLine( "Inventory updated to " @ %pack @ "." );
}

function checkPackValidity(%pack, %equipment, %item)
{
	//echo("validityChecking:" SPC %pack SPC %equipment);
	
	// this is mostly for ease of mod makers
	// this is the base restrictions stuff
	// for your mod just overwrite this function and 
	// change the restrictions and onlyUses

	// you must have #1 to use #2
	//%restrict[#1, #2] = true;
	
	%restrict["Scout", "Inventory Station"] = true;
	%restrict["Scout", "Landspike Turret"] = true;
	%restrict["Scout", "Spider Clamp Turret"] = true;
	%restrict["Scout", "ELF Turret Barrel"] = true;
	%restrict["Scout", "Mortar Turret Barrel"] = true;
	%restrict["Scout", "AA Turret Barrel"] = true;
	%restrict["Scout", "Plasma Turret Barrel"] = true;
	%restrict["Scout", "Missile Turret Barrel"] = true;
	%restrict["Assault", "Cloak Pack"] = true;
	%restrict["Juggernaut", "Cloak Pack"] = true;

	// you can only use #1 if you have a #2 of type #3
	//%require[#1] = #2 TAB #3;

	%require["Laser Rifle"] = "Pack" TAB "Energy Pack";
	

 	if(%restrict[%equipment, %pack] )
 		return true;
	
	else if(%require[%equipment] !$="" )
	{
		if(%item $= getField(%require[%equipment], 0) )
		{
			if(%pack !$= getField(%require[%equipment], 1) )
				return true;
		}
	}
}


//------------------------------------------------------------------------------
function setDefaultInventory(%client)
{
   commandToClient(%client,'InitLoadClientFavorites');
}

//------------------------------------------------------------------------------
function checkInventory( %client, %text )
{
   %armor = getArmorDatablock( %client, $NameToInv[getField( %text, 1 )] );
   %list = getField( %text, 0 ) TAB getField( %text, 1 );
   %cmt = $CurrentMissionType;
   for( %i = 3; %i < getFieldCount( %text ); %i = %i + 2 )
   {
      %inv = $NameToInv[getField(%text,%i)];
      if ( (( %armor.max[%inv] && !($InvBanList[%cmt, %inv]) ) || 
          getField( %text, %i ) $= Empty || getField( %text, %i ) $= Invalid) 
          && (($InvTotalCount[getField( %text, %i - 1 )] - $BanCount[getField( %text, %i - 1 )]) > 0))
         %list = %list TAB getField( %text, %i - 1 ) TAB getField( %text, %i );
      else if( $InvBanList[%cmt, %inv] || %inv $= empty || %inv $= "")
         %list = %list TAB getField( %text, %i - 1 ) TAB "INVALID";         
   }
   return %list;
}

//------------------------------------------------------------------------------
function getArmorDatablock(%client, %size)
{
   if ( %client.race $= "Bioderm" )
      %armor = %size @ "Male" @ %client.race @ Armor;
   else
      %armor = %size @ %client.sex @ %client.race @ Armor;
   return %armor;
}

//------------------------------------------------------------------------------
function InventoryScreen::onWake(%this)
{
   if ( $HudHandle['inventoryScreen'] !$= "" )
      alxStop( $HudHandle['inventoryScreen'] );
   alxPlay(HudInventoryActivateSound, 0, 0, 0);
   $HudHandle['inventoryScreen'] = alxPlay(HudInventoryHumSound, 0, 0, 0);

   if ( isObject( hudMap ) )
   {
      hudMap.pop();
      hudMap.delete();
   }
   new ActionMap( hudMap );
   hudMap.blockBind( moveMap, toggleScoreScreen );
   hudMap.blockBind( moveMap, toggleCommanderMap );
   hudMap.bindCmd( keyboard, escape, "", "InventoryScreen.onDone();" );
   hudMap.push();
}

//------------------------------------------------------------------------------
function InventoryScreen::onSleep()
{
   hudMap.pop();
   hudMap.delete();   
   alxStop($HudHandle['inventoryScreen']);
   alxPlay(HudInventoryDeactivateSound, 0, 0, 0);
   $HudHandle['inventoryScreen'] = "";
}

//------------------------------------------------------------------------------
function InventoryScreen::onDone( %this )
{
   toggleCursorHuds( 'inventoryScreen' );
}

//------------------------------------------------------------------------------
function InventoryScreen::onTabSelect( %this, %favId )
{
   loadFavorite( %favId, 0 );
}

function createInvBanCount()
{
   $BanCount["Armor"] = 0;
   $BanCount["Weapon"] = 0;
   $BanCount["Pack"] = 0;
   $BanCount["Grenade"] = 0;
   $BanCount["Mine"] = 0;

   for(%i = 0; $InvArmor[%i] !$= ""; %i++)
      if($InvBanList[$CurrentMissionType, $NameToInv[$InvArmor[%i]]])
         $BanCount["Armor"]++;
   $InvTotalCount["Armor"] = %i;
   
   for(%i = 0; $InvWeapon[%i] !$= ""; %i++)
      if($InvBanList[$CurrentMissionType, $NameToInv[$InvWeapon[%i]]])
         $BanCount["Weapon"]++;
   $InvTotalCount["Weapon"] = %i;

   for(%i = 0; $InvPack[%i] !$= ""; %i++)
      if($InvBanList[$CurrentMissionType, $NameToInv[$InvPack[%i]]])
         $BanCount["Pack"]++;
   $InvTotalCount["Pack"] = %i;

   for(%i = 0; $InvGrenade[%i] !$= ""; %i++)
      if($InvBanList[$CurrentMissionType, $NameToInv[$InvGrenade[%i]]])
         $BanCount["Grenade"]++;
   $InvTotalCount["Grenade"] = %i;

   for(%i = 0; $InvMine[%i] !$= ""; %i++)
      if($InvBanList[$CurrentMissionType, $NameToInv[$InvMine[%i]]])
         $BanCount["Mine"]++;
   $InvTotalCount["Mine"] = %i;
}

exec("scripts/InventoryFix.cs");