code:
//=============================================================================
// Yanfly Engine Plugins - Target Core
// YEP_TargetCore.js
//=============================================================================

var Imported = Imported || {};
Imported.YEP_TargetCore = true;

var Yanfly = Yanfly || {};
Yanfly.Target = Yanfly.Target || {};
Yanfly.Target.version = 1.05;

//=============================================================================
 /*:
 * @plugindesc v1.05 Expand the target scope from RPG Maker's default
 * limitations for better target control.
 * @author Yanfly Engine Plugins
 *
 * @param ---Battle Engine---
 * @default
 *
 * @param Everybody Text
 * @parent ---Battle Engine---
 * @desc The help text for Everybody scope.
 * @default All Allies and Enemies
 *
 * @param All But User Text
 * @parent ---Battle Engine---
 * @desc The help text for all All But User scope.
 * %1 - Allies     %2 - User
 * @default All %1 But %2
 *
 * @param Random Any Text
 * @parent ---Battle Engine---
 * @desc The help text used for the Random Any scope.
 * %1 - Number
 * @default %1 Random
 *
 * @param ---Multiple Of---
 * @default
 *
 * @param Multiple Text
 * @parent ---Multiple Of---
 * @desc The help text used for Multiple of x scope.
 * %1 - Targets   %2 - Parameters   %3 - Number
 * @default %1 with %2 as a Multiple of %3
 *
 * @param Multiple Everybody
 * @parent ---Multiple Of---
 * @desc The text to use for Everybody in this format.
 * @default Anyone
 *
 * @param Multiple Allies
 * @parent ---Multiple Of---
 * @desc The text to use for Allies in this format.
 * @default Any Ally
 *
 * @param Multiple Foes
 * @parent ---Multiple Of---
 * @desc The text to use for Foes in this format.
 * @default Any Foe
 *
 * @param ---Row Formation---
 * @default
 *
 * @param Target Row Text
 * @parent ---Row Formation---
 * @desc The help text used to target the target's row.
 * %1 - Target Name
 * @default %1's Row
 *
 * @param Front Row Text
 * @parent ---Row Formation---
 * @desc The help text used to target the front row.
 * %1 - Target Type
 * @default %1 Front Row
 *
 * @param Back Row Text
 * @parent ---Row Formation---
 * @desc The help text used to target the back row.
 * %1 - Target Type
 * @default %1 Back Row
 *
 * @param Specific Row Text
 * @parent ---Row Formation---
 * @desc The help text used to target specific rows.
 * %1 - Target Type
 * @default Specific %1 Row
 *
 * @param Row Enemies
 * @parent ---Row Formation---
 * @desc The help text used for enemies for Row Targets.
 * @default Enemy
 *
 * @param Row Allies
 * @parent ---Row Formation---
 * @desc The help text used for enemies for Row Targets.
 * @default Allied
 *
 * @help
 * ============================================================================
 * Introduction
 * ============================================================================
 *
 * While this plugin works independent of YEP_BattleEngineCore.js, if you want
 * to utilize extra effects, place this plugin beneath YEP_BattleEngineCore.js
 * in the Plugin Manager list.
 *
 * The Target Core plugin is made to expand upon the existing target scopes
 * provided by RPG Maker MV. This plugin enables you to use more target scopes,
 * with a larger variety of ways to target actors and enemies with bonus ways
 * to choose targets combined with the Row Formation plugin.
 *
 * ============================================================================
 * Notetags
 * ============================================================================
 *
 * If you would like to utilize custom target scopes for your skills and items,
 * you can use these notetags:
 *
 * Skill and Item Notetags:
 *
 *   <Repeat: x>
 *   This determines the number of times an action is repeatedly used on each
 *   target. This can go beyond the default editor's limit of 9.
 *
 *   <Target: Everybody>
 *   This targets all alive opponent and friendly members with the user being
 *   the very last target.
 *
 *   <Target: x Random Any>
 *   This adds x random alive opponents and/or allies.
 *
 *   <Target: Target All Foes>
 *   This targets a single foe and then adds all alive opponent members.
 *
 *   <Target: Target x Random Foes>
 *   This targets a single foe and then adds x random alive opponent members.
 *
 *   <Target: x Random Foes>
 *   This adds x random alive opponent members. This can go beyond the editor's
 *   default limit of 4 randomf oes.
 *
 *   <Target: All Allies But User>
 *   This will target all friendly alive members except for the user.
 *
 *   <Target: Target All Allies>
 *   This will target a single ally and then adds all alive friendly members.
 *
 *   <Target: Target x Random Allies>
 *   This will target a single ally and then adds x random alive allies.
 *
 *   <Target: x Random Allies>
 *   This adds x random alive allied members.
 *
 *   <Target: Everybody param Multiple Of x>
 *   Replace 'param' with 'level', 'maxhp', 'maxmp', 'atk', 'def', 'mat',
 *   'mdf', 'agi', 'luk', 'hp', 'mp', or 'tp'. This will make the skill or item
 *   indiscriminately target any living battler on the battlefield whose
 *   parameter value is a multiple of x.
 *   *NOTE: If you are using 'level', make sure you have YEP_EnemyLevels.js.
 *
 *   <Target: Allies param Multiple Of x>
 *   Replace 'param' with 'level', 'maxhp', 'maxmp', 'atk', 'def', 'mat',
 *   'mdf', 'agi', 'luk', 'hp', 'mp', or 'tp'. This will make the skill or item
 *   target any living allied party member on the battlefield whose parameter
 *   value is a multiple of x.
 *   *NOTE: If you are using 'level', make sure you have YEP_EnemyLevels.js.
 *
 *   <Target: Foes param Multiple Of x>
 *   Replace 'param' with 'level', 'maxhp', 'maxmp', 'atk', 'def', 'mat',
 *   'mdf', 'agi', 'luk', 'hp', 'mp', or 'tp'. This will make the skill or item
 *   target any living enemy battler on the battlefield whose parameter value
 *   is a multiple of x.
 *   *NOTE: If you are using 'level', make sure you have YEP_EnemyLevels.js.
 *
 *   --- YEP_RowFormation.js and YEP_BattleEngineCore.js Required ---
 *
 *   <Target: Enemy Row>
 *   This will target the enemy row equal to that of the currently selected
 *   target enemy. The entire row will be selected as a whole.
 *
 *   <Target: Enemy Row x>
 *   This will target specifically the enemy row x for the enemy unit. The
 *   entire row will be selected as a whole.
 *
 *   <Target: Front Enemy Row>
 *   This will target the front-most enemy row with alive members. If there is
 *   a row without any alive members, this will target the next row with an
 *   alive member.
 *
 *   <Target: Back Enemy Row>
 *   This will target the back-most enemy row with alive members. If there is
 *   a row without any alive members, this will target the next row with an
 *   alive member.
 *
 *   <Target: Ally Row>
 *   This will target the enemy row equal to that of the currently selected
 *   target enemy. The entire row will be selected as a whole.
 *
 *   <Target: Ally Row x>
 *   This will target specifically the allied row x for the allied unit. The
 *   entire row will be selected as a whole.
 *
 *   <Target: Front Ally Row>
 *   This will target the front-most ally row with alive members. If there is
 *   a row without any alive members, this will target the next row with an
 *   alive member.
 *
 *   <Target: Back Ally Row>
 *   This will target the back-most ally row with alive members. If there is
 *   a row without any alive members, this will target the next row with an
 *   alive member.
 *
 * ============================================================================
 * Lunatic Mode - Custom Target Help Text
 * ============================================================================
 *
 * For users that are proficient with JavaScript, these notetags can be used to
 * provide custom help window text if you are also the Battle Engine Core.
 *
 * Skill and Item Notetags:
 *
 *   <Custom Target Text>
 *    text = $gameActors.actor(1).name();
 *    text += ' and ' + $gameActors.actor(2).name();
 *   </Custom Target Text>
 *   The 'text' variable is the text that will appear in the help window. Any
 *   changes made to it will be what is visibly displayed.
 *
 * ============================================================================
 * Lunatic Mode - Custom Target Eval
 * ============================================================================
 *
 * For users that are proficient with JavaScript, these notetags can be used to
 * make custom target selections. For the targeting aspect, this will refer to
 * the skill/item's current scope and the targets made here will be made
 * independent of the scope with the exception of the target, where if a target
 * is selected, it will become the 'target' value.
 *
 *   <Custom Target Eval>
 *   for (var i = 0; i < foes.aliveMembers().length; ++i) {
 *     var member = foes.aliveMembers()[i];
 *     if (member.level % 3 === 0) targets.push(member);
 *   }
 *   </Custom Target Eval>
 *   The 'targets' variable is an array that determines which are the targets
 *   to be used during the selection process. Push the desired targets into
 *   the 'targets' array.
 *
 * ============================================================================
 * Changelog
 * ============================================================================
 *
 * Version 1.05:
 * - Bypass the isDevToolsOpen() error when bad code is inserted into a script
 * call or custom Lunatic Mode code segment due to updating to MV 1.6.1.
 *
 * Version 1.04:
 * - Updated for RPG Maker MV version 1.5.0.
 *
 * Version 1.03:
 * - Lunatic Mode fail safes added.
 *
 * Version 1.02a:
 * - <Target: Everybody> will now have allies highlighted as well.
 * - <Target: Enemy Row> and <Target: Ally Row> will no longer highlight edead
 * enemies causing them to reappear.
 *
 * Version 1.01:
 * - Updated for RPG Maker MV version 1.1.0.
 *
 * Version 1.00:
 * - Finished Plugin!
 */
//=============================================================================

//=============================================================================
// Parameter Variables
//=============================================================================

Yanfly.Parameters = PluginManager.parameters('YEP_TargetCore');
Yanfly.Param = Yanfly.Param || {};

Yanfly.Param.BECHlpEverybodyTx = String(Yanfly.Parameters['Everybody Text']);
Yanfly.Param.BECHlpAllBTx = String(Yanfly.Parameters['All But User Text']);
Yanfly.Param.BECHlpRandomAnyTx = String(Yanfly.Parameters['Random Any Text']);

Yanfly.Param.TargetMultipleTx = String(Yanfly.Parameters['Multiple Text']);
Yanfly.Param.TargetMultiEvery = String(Yanfly.Parameters['Multiple Everybody']);
Yanfly.Param.TargetMultiAllies = String(Yanfly.Parameters['Multiple Allies']);
Yanfly.Param.TargetMultiFoes = String(Yanfly.Parameters['Multiple Foes']);

Yanfly.Param.TargetHlpRowTx = String(Yanfly.Parameters['Target Row Text']);
Yanfly.Param.TargetFrontRow = String(Yanfly.Parameters['Front Row Text']);
Yanfly.Param.TargetBackRow = String(Yanfly.Parameters['Back Row Text']);
Yanfly.Param.TargetSpcRow = String(Yanfly.Parameters['Specific Row Text']);
Yanfly.Param.TargetRowEnemies = String(Yanfly.Parameters['Row Enemies']);
Yanfly.Param.TargetRowAllies = String(Yanfly.Parameters['Row Allies']);

//=============================================================================
// DataManager
//=============================================================================

Yanfly.Target.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded;
DataManager.isDatabaseLoaded = function() {
  if (!Yanfly.Target.DataManager_isDatabaseLoaded.call(this)) return false;
  if (!Imported.YEP_BattleEngineCore) {
    this.processTargetNotetags1($dataSkills);
    this.processTargetNotetags1($dataItems);
  }
  return true;
};

if (Imported.YEP_BattleEngineCore) {

Yanfly.Target.DataManager_processMELODYNotetags =
    DataManager.processMELODYNotetags;
DataManager.processMELODYNotetags = function(group) {
    this.processTargetNotetags1(group);
    Yanfly.Target.DataManager_processMELODYNotetags.call(this, group);
};

Yanfly.Target.DataManager_addActionEffects = DataManager.addActionEffects;
DataManager.addActionEffects = function(obj, array) {
  this.processTargetRepeatNotetags(obj);
  Yanfly.Target.DataManager_addActionEffects.call(this, obj, array);
};

Yanfly.Target.DataManager_isWholeAction = DataManager.isWholeAction;
DataManager.isWholeAction = function(obj) {
  if (obj.scope === 'MULTIPLE') return true;
  if (obj.scope === 'EVERYBODY') return true;
  if (obj.scope === 'RANDOM ANY') return false;
  if (obj.scope === 'TARGET ALL FOES') return false;
  if (obj.scope === 'TARGET RANDOM FOES') return false;
  if (obj.scope === 'ALL BUT USER') return true;
  if (obj.scope === 'TARGET ALL ALLIES') return false;
  if (obj.scope === 'TARGET RANDOM ALLIES') return false;
  if (obj.scope === 'RANDOM ALLIES') return false;
  if (obj.scope === 'ENEMY ROW') return true;
  if (obj.scope === 'ALLY ROW') return true;
  if (obj.scope === 'FRONT ENEMY ROW') return true;
  if (obj.scope === 'FRONT ALLY ROW') return true;
  if (obj.scope === 'BACK ENEMY ROW') return true;
  if (obj.scope === 'BACK ALLY ROW') return true;
  if (obj.scope === 'SPECIFIC ENEMY ROW') return true;
  if (obj.scope === 'SPECIFIC ALLY ROW') return true;
  return Yanfly.Target.DataManager_isWholeAction.call(this, obj);
};

}; // Imported.YEP_BattleEngineCore

DataManager.processTargetRepeatNotetags = function(obj) {
  var notedata = obj.note.split(/[\r\n]+/);
  for (var i = 0; i < notedata.length; i++) {
    var line = notedata[i];
    if (line.match(/<(?:REPEAT|REPEATS|REPEAT TIMES):[ ](\d+)>/i)) {
      obj.repeats = parseInt(RegExp.$1);
    }
  }
};

DataManager.processTargetNotetags1 = function(group) {
  for (var n = 1; n < group.length; n++) {
    var obj = group[n];
    var notedata = obj.note.split(/[\r\n]+/);

    this.makeRandomTargets(obj);
    var evalMode = 'none';
    obj.customTargetText = '';
    obj.customTargetEval = '';

    if (!Imported.YEP_BattleEngineCore) this.processTargetRepeatNotetags(obj);
    for (var i = 0; i < notedata.length; i++) {
      var line = notedata[i];
      if (line.match(/<(?:TARGET|targets):[ ](.*)>/i)) {
        var type = String(RegExp.$1).toUpperCase();
        this.makeTargetTypes(obj, type);
      } else if (line.match(/<CUSTOM TARGET TEXT>/i)) {
        evalMode = 'custom target text';
      } else if (line.match(/<\/CUSTOM TARGET TEXT>/i)) {
        evalMode = 'none';
      } else if (evalMode === 'custom target text') {
        obj.customTargetText = obj.customTargetText + line + '\n';
      } else if (line.match(/<CUSTOM TARGET EVAL>/i)) {
        evalMode = 'custom target eval';
      } else if (line.match(/<\/CUSTOM TARGET EVAL>/i)) {
        evalMode = 'none';
      } else if (evalMode === 'custom target eval') {
        obj.customTargetEval = obj.customTargetEval + line + '\n';
      }
    }
  }
};

DataManager.makeRandomTargets = function(obj) {
  obj.randomTargets = 0;
  if ([3, 4, 5, 6].contains(obj.scope)) {
    obj.randomTargets = obj.scope - 2;
  }
};

DataManager.makeTargetTypes = function(obj, type) {
    if (type.match(/(.*?)[ ](.*?)[ ]MULTIPLE OF[ ](\d+)/i)) {
      var targets = String(RegExp.$1).toUpperCase();
      var stat = String(RegExp.$2).toUpperCase();
      var number = Math.max(0, parseInt(RegExp.$3));
      this.makeTargetMultipleOfType(obj, targets, stat, number);
	} else if (type.match(/REM_EVERYONE_ELSE/i)) {
      obj.scope = 'REM_EVERYONE_ELSE';
	} else if (type.match(/REM_EVERYONE/i)) {
      obj.scope = 'REM_EVERYONE';
    } else if (type.match(/EVERYBODY/i)) {
      obj.scope = 'EVERYBODY';
    } else if (type.match(/(\d+)[ ]RANDOM ANY/i)) {
      obj.randomTargets = parseInt(RegExp.$1);
      obj.scope = 'RANDOM ANY';
    } else if (type.match(/TARGET ALL FOE/i)) {
      obj.scope = 'TARGET ALL FOES';
    } else if (type.match(/TARGET[ ](\d+)[ ]RANDOM FOE/i)) {
      obj.randomTargets = parseInt(RegExp.$1);
      obj.scope = 'TARGET RANDOM FOES';
    } else if (type.match(/(\d+)[ ]RANDOM FOE/i)) {
      obj.randomTargets = parseInt(RegExp.$1);
      obj.scope = 3;
    } else if (type.match(/ALL BUT USER/i)) {
      obj.scope = 'ALL BUT USER';
    } else if (type.match(/ALL ALLIES BUT USER/i)) {
      obj.scope = 'ALL BUT USER';
    } else if (type.match(/TARGET ALL ALL/i)) {
      obj.scope = 'TARGET ALL ALLIES';
    } else if (type.match(/TARGET[ ](\d+)[ ]RANDOM ALL/i)) {
      obj.randomTargets = parseInt(RegExp.$1);
      obj.scope = 'TARGET RANDOM ALLIES';
    } else if (type.match(/(\d+)[ ]RANDOM ALL/i)) {
      obj.randomTargets = parseInt(RegExp.$1);
      obj.scope = 'RANDOM ALLIES';
    } else if (type.match(/FRONT ENEMY ROW/i)) {
      if (!Imported.YEP_RowFormation) return;
      obj.scope = 'FRONT ENEMY ROW';
    } else if (type.match(/FRONT ALLY ROW/i)) {
      if (!Imported.YEP_RowFormation) return;
      obj.scope = 'FRONT ALLY ROW';
    } else if (type.match(/BACK ENEMY ROW/i)) {
      if (!Imported.YEP_RowFormation) return;
      obj.scope = 'BACK ENEMY ROW';
    } else if (type.match(/BACK ALLY ROW/i)) {
      if (!Imported.YEP_RowFormation) return;
      obj.scope = 'BACK ALLY ROW';
    }  else if (type.match(/ENEMY ROW[ ](\d+)/i)) {
      if (!Imported.YEP_RowFormation) return;
      obj.scope = 'SPECIFIC ENEMY ROW';
      obj.rowTarget = parseInt(RegExp.$1).clamp(1, 10);
    } else if (type.match(/ALLY ROW[ ](\d+)/i)) {
      if (!Imported.YEP_RowFormation) return;
      obj.scope = 'SPECIFIC ALLY ROW';
      obj.rowTarget = parseInt(RegExp.$1).clamp(1, 10);
    } else if (type.match(/ENEMY ROW/i)) {
      if (!Imported.YEP_RowFormation) return;
      obj.scope = 'ENEMY ROW';
    } else if (type.match(/ALLY ROW/i)) {
      if (!Imported.YEP_RowFormation) return;
      obj.scope = 'ALLY ROW';
    }
};

DataManager.makeTargetMultipleOfType = function(obj, targets, stat, number) {
  obj.multipleOf = [];
  if (['ALL', 'ANY', 'ANYBODY', 'EVERYBODY'].contains(targets)) {
    obj.multipleOf.push('EVERYBODY');
  } else if (['ALLY', 'ALLIES', 'FRIENDS'].contains(targets)) {
    obj.multipleOf.push('FRIENDS');
  } else if (['FOE', 'FOES', 'ENEMIES', 'OPPONENTS'].contains(targets)) {
    obj.multipleOf.push('OPPONENTS');
  } else {
    return;
  }
  if (['MAXHP', 'MAX HP'].contains(stat)) {
    obj.multipleOf.push(0);
  } else if (['MAXMP', 'MAX MP', 'MAXSP', 'MAX SP'].contains(stat)) {
    obj.multipleOf.push(1);
  } else if (['ATK', 'STR'].contains(stat)) {
    obj.multipleOf.push(2);
  } else if (['DEF'].contains(stat)) {
    obj.multipleOf.push(3);
  } else if (['MAT', 'INT'].contains(stat)) {
    obj.multipleOf.push(4);
  } else if (['MDF', 'RES'].contains(stat)) {
    obj.multipleOf.push(5);
  } else if (['AGI', 'SPD'].contains(stat)) {
    obj.multipleOf.push(6);
  } else if (['LUK'].contains(stat)) {
    obj.multipleOf.push(7);
  } else if (['LEVEL', 'LV', 'LVL'].contains(stat)) {
    obj.multipleOf.push('LEVEL');
  } else if (['HP'].contains(stat)) {
    obj.multipleOf.push('HP');
  } else if (['MP'].contains(stat)) {
    obj.multipleOf.push('MP');
  } else if (['TP'].contains(stat)) {
    obj.multipleOf.push('TP');
  } else {
    return;
  }
  obj.multipleOf.push(number);
  obj.scope = 'MULTIPLE';
};

//=============================================================================
// BattleManager
//=============================================================================

if (Imported.YEP_BattleEngineCore) {

Yanfly.Target.BattleManager_startAllSelection = BattleManager.startAllSelection;
BattleManager.startAllSelection = function() {
  if (this.inputtingAction().isForMultiple()) {
    var targets = this.inputtingAction().makeMultipleOfTargets();
    this._customTargetSelectGroup = targets;
  } else if (this.inputtingAction().isForRow()) {
    var targets = this.inputtingAction().makeRowTypeTargets();
    this._customTargetSelectGroup = targets;
  } else {
    Yanfly.Target.BattleManager_startAllSelection.call(this);
  }
};

}; // Imported.YEP_BattleEngineCore

BattleManager.customTargetSelectGroup = function() {
  this._customTargetSelectGroup = this._customTargetSelectGroup || [];
  return this._customTargetSelectGroup;
};

BattleManager.clearCustomTargetSelectGroup = function() {
  this._customTargetSelectGroup = [];
};

//=============================================================================
// Game_System
//=============================================================================

Yanfly.Target.Game_System_onBattleStart = Game_System.prototype.onBattleStart;
Game_System.prototype.onBattleStart = function() {
    BattleManager.clearCustomTargetSelectGroup();
    Yanfly.Target.Game_System_onBattleStart.call(this);
};

//=============================================================================
// Game_Battler
//=============================================================================

Yanfly.Target.Game_Battler_isSelected = Game_Battler.prototype.isSelected;
Game_Battler.prototype.isSelected = function() {
    if (BattleManager.customTargetSelectGroup().length > 0) {
      return BattleManager.customTargetSelectGroup().contains(this);
    }
    return Yanfly.Target.Game_Battler_isSelected.call(this);
};

//=============================================================================
// Game_Action
//=============================================================================

Yanfly.Target.Game_Action_isForOpponent = Game_Action.prototype.isForOpponent;
Game_Action.prototype.isForOpponent = function() {
    if (this.item().scope === 'EVERYBODY') return true;
	if (this.item().scope === 'REM_EVERYONE_ELSE') return true;
	if (this.item().scope === 'REM_EVERYONE') return true;
	if (this.item().scope === 'REM_FEMALE_ENEMY') return true;
    if (this.item().scope === 'RANDOM ANY') return true;
    if (this.item().scope === 'TARGET ALL FOES') return true;
    if (this.item().scope === 'TARGET RANDOM FOES') return true;
    if (this.item().scope === 'MULTIPLE') {
      if (this.item().multipleOf.contains('EVERYBODY')) return true;
      if (this.item().multipleOf.contains('OPPONENTS')) return true;
    }
    if (this.item().scope === 'ENEMY ROW') return true;
    if (this.item().scope === 'FRONT ENEMY ROW') return true;
    if (this.item().scope === 'BACK ENEMY ROW') return true;
    if (this.item().scope === 'SPECIFIC ENEMY ROW') return true;
    return Yanfly.Target.Game_Action_isForOpponent.call(this);
};

Yanfly.Target.Game_Action_isForFriend = Game_Action.prototype.isForFriend;
Game_Action.prototype.isForFriend = function() {
    if (this.item().scope === 'EVERYBODY') return true;
	if (this.item().scope === 'REM_EVERYONE_ELSE') return true;
	if (this.item().scope === 'REM_EVERYONE') return true;
    if (this.item().scope === 'ALL BUT USER') return true;
    if (this.item().scope === 'TARGET ALL ALLIES') return true;
    if (this.item().scope === 'TARGET RANDOM ALLIES') return true;
    if (this.item().scope === 'RANDOM ALLIES') return true;
    if (this.item().scope === 'MULTIPLE') {
      if (this.item().multipleOf.contains('FRIENDS')) return true;
    }
    if (this.item().scope === 'ALLY ROW') return true;
    if (this.item().scope === 'FRONT ALLY ROW') return true;
    if (this.item().scope === 'BACK ALLY ROW') return true;
    if (this.item().scope === 'SPECIFIC ALLY ROW') return true;
    return Yanfly.Target.Game_Action_isForFriend.call(this);
};

Game_Action.prototype.isForCustom = function() {
    if (this.isForEval()) return true;
    return typeof this.item().scope === 'string';
};

Game_Action.prototype.isForEval = function() {
    return this.item().customTargetEval !== '';
};

Game_Action.prototype.isForEverybody = function() {
    if (this.item().scope === 'MULTIPLE') {
      if (this.item().multipleOf.contains('EVERYBODY')) return true;
    }
	if (this.item().scope === 'REM_EVERYONE_ELSE' || this.item().scope === 'REM_EVERYONE') {
		return true;
	}
    return this.item().scope === 'EVERYBODY';
};

Game_Action.prototype.isForRandomAny = function() {
    return this.item().scope === 'RANDOM ANY';
};

Game_Action.prototype.isForTargetAllFoes = function() {
    return this.item().scope === 'TARGET ALL FOES';
};

Game_Action.prototype.isForTargetRandomFoes = function() {
    return this.item().scope === 'TARGET RANDOM FOES';
};

Game_Action.prototype.isForAllButUser = function() {
    return this.item().scope === 'ALL BUT USER';
};

Game_Action.prototype.isForTargetAllAllies = function() {
    return this.item().scope === 'TARGET ALL ALLIES';
};

Game_Action.prototype.isForTargetRandomAllies = function() {
    return this.item().scope === 'TARGET RANDOM ALLIES';
};

Game_Action.prototype.isForRandomAllies = function() {
    return this.item().scope === 'RANDOM ALLIES';
};

Yanfly.Target.Game_Action_isForRandom = Game_Action.prototype.isForRandom;
Game_Action.prototype.isForRandom = function() {
    if (this.item().randomTargets > 0) return true;
    return Yanfly.Target.Game_Action_isForRandom.call(this);
};

Game_Action.prototype.isForMultiple = function() {
    return this.item().scope === 'MULTIPLE';
};

Game_Action.prototype.isForRow = function() {
    if (this.item().scope === 'ENEMY ROW') return true;
    if (this.item().scope === 'ALLY ROW') return true;
    if (this.item().scope === 'FRONT ENEMY ROW') return true;
    if (this.item().scope === 'FRONT ALLY ROW') return true;
    if (this.item().scope === 'BACK ENEMY ROW') return true;
    if (this.item().scope === 'BACK ALLY ROW') return true;
    if (this.item().scope === 'SPECIFIC ENEMY ROW') return true;
    if (this.item().scope === 'SPECIFIC ALLY ROW') return true;
    return false;
};

Yanfly.Target.Game_Action_needsSelection = Game_Action.prototype.needsSelection;
Game_Action.prototype.needsSelection = function() {
    if (this.item().scope === 'TARGET ALL FOES') return true;
    if (this.item().scope === 'TARGET RANDOM FOES') return true;
    if (this.item().scope === 'TARGET ALL ALLIES') return true;
    if (this.item().scope === 'TARGET RANDOM ALLIES') return true;
    if (this.item().scope === 'ENEMY ROW') return true;
    if (this.item().scope === 'ALLY ROW') return true;
	if (this.item().scope === 'REM_FEMALE_ALLY') return true;
	if (this.item().scope === 'REM_FEMALE_ENEMY') return true;
    return Yanfly.Target.Game_Action_needsSelection.call(this);
};

Yanfly.Target.Game_Action_numTargets = Game_Action.prototype.numTargets;
Game_Action.prototype.numTargets = function() {
    if (this.isForRandom()) return this.item().randomTargets;
    return Yanfly.Target.Game_Action_numTargets.call(this);
};

Yanfly.Target.Game_Action_makeTargets = Game_Action.prototype.makeTargets;
Game_Action.prototype.makeTargets = function() {
  var targets = [];
  if (!this._forcing && this.subject().isConfused()) {
    targets = Yanfly.Target.Game_Action_makeTargets.call(this);
  } else if (this.isForCustom()) {
    targets = this.makeCustomTargets();
  } else {
    targets = Yanfly.Target.Game_Action_makeTargets.call(this);
  }
  return targets;
};

Game_Action.prototype.makeCustomTargets = function() {
  var targets = [];
  if (this.isForEval()) {
    targets = this.makeEvalTargets();
  } else if (this.isForMultiple()) {
    targets = this.makeMultipleOfTargets();
  } else if (this.isForRow()) {
    targets = this.makeRowTypeTargets();
  } else if (this.isForRandomAny()) {
    var number = this.numTargets();
    var group = $gameParty.aliveMembers().concat($gameTroop.aliveMembers());
    for (var i = 0; i < number; ++i) {
      var member = group[Math.floor(Math.random() * group.length)];
      targets.push(member);
    }
  } else if (this.isForEverybody()) {
    //targets = this.opponentsUnit().aliveMembers();
	if(this.item().scope === 'REM_EVERYONE_ELSE' || this.item().scope === 'REM_EVERYONE') {
		if(this.item().scope === 'REM_EVERYONE') targets.push(this.subject());

		var length = this.opponentsUnit().aliveMembers().length;
		for (var i = 0; i < length; ++i) {
			var member = this.opponentsUnit().aliveMembers()[i];
			targets.push(member);
		}

		length = this.friendsUnit().members().length;
		for (var i = 0; i < length; ++i) {
			var member = this.friendsUnit().members()[i];
			if (member && member !== this.subject()) targets.push(member);
		}
	}
	else {
		targets = this.opponentsUnit().aliveMembers();
		var length = this.friendsUnit().aliveMembers().length;
		for (var i = 0; i < length; ++i) {
		  var member = this.friendsUnit().aliveMembers()[i];
		  if (member && member !== this.subject()) targets.push(member);
		}
		targets.push(this.subject());
	}
  } else if (this.isForTargetAllFoes()) {
    var unit = this.opponentsUnit();
    targets.push(unit.smoothTarget(this._targetIndex));
    targets = targets.concat(unit.aliveMembers());
  } else if (this.isForTargetRandomFoes()) {
    var unit = this.opponentsUnit();
    var number = this.numTargets();
    targets.push(unit.smoothTarget(this._targetIndex));
    targets = targets.concat(this.getRandomTargets(number, unit))
  } else if (this.isForAllButUser()) {
    var length = this.friendsUnit().aliveMembers().length;
    for (var i = 0; i < length; ++i) {
      var member = this.friendsUnit().aliveMembers()[i];
      if (member && member !== this.subject()) targets.push(member);
    }
  } else if (this.isForTargetAllAllies()) {
    var unit = this.friendsUnit();
    targets.push(unit.smoothTarget(this._targetIndex));
    targets = targets.concat(unit.aliveMembers());
  } else if (this.isForTargetRandomAllies()) {
    var unit = this.friendsUnit();
    var number = this.numTargets();
    targets.push(unit.smoothTarget(this._targetIndex));
    targets = targets.concat(this.getRandomTargets(number, unit))
  } else if (this.isForRandomAllies()) {
    var unit = this.friendsUnit();
    var number = this.numTargets();
    targets = targets.concat(this.getRandomTargets(number, unit))
  }
  return targets;
};

Game_Action.prototype.makeEvalTargets = function() {
  var targets = [];
  var a = this.subject();
  var user = this.subject();
  var subject = this.subject();
  if (this.isForOpponent()) {
    var targetUnit = this.opponentsUnit();
  } else {
    var targetUnit = this.friendsUnit();
  }
  var b = targetUnit.smoothTarget(this._targetIndex);
  var target = targetUnit.smoothTarget(this._targetIndex);
  var s = $gameSwitches._data;
  var v = $gameVariables._data;
  var allies = this.friendsUnit();
  var friends = allies;
  var foes = this.opponentsUnit();
  var opponents = foes;
  var code = this.item().customTargetEval;
  try {
    eval(code);
  } catch (e) {
    Yanfly.Util.displayError(e, code, 'MAKE CUSTOM TARGETS ERROR');
  }
  return targets;
};

Game_Action.prototype.getRandomTargets = function(number, unit) {
  var targets = [];
  for (var i = 0; i < number; ++i) {
    targets.push(unit.randomTarget());
  }
  return targets;
};

Game_Action.prototype.makeMultipleOfTargets = function() {
    var targets = [];
    var unit = [];
    var type = this.item().multipleOf[0];
    var param = this.item().multipleOf[1];
    var number = this.item().multipleOf[2];
    if (['EVERYBODY', 'OPPONENTS'].contains(type)) {
      unit = unit.concat(this.opponentsUnit().aliveMembers());
    }
    if (['EVERYBODY', 'FRIENDS'].contains(type)) {
      unit = unit.concat(this.friendsUnit().aliveMembers());
    }
    var length = unit.length;
    for (var i = 0; i < length; ++i) {
      var member = unit[i];
      if (param === 'LEVEL') {
        if (member.level % number === 0) targets.push(member);
      } else if (param === 'HP') {
        if (member.hp % number === 0) targets.push(member);
      } else if (param === 'MP') {
        if (member.mp % number === 0) targets.push(member);
      } else if (param === 'TP') {
        if (member.tp % number === 0) targets.push(member);
      } else {
        if (member.param(param) % number === 0) targets.push(member);
      }
    }
    return targets;
};

Game_Action.prototype.makeRowTypeTargets = function() {
    var targets = [];
    var scope = this.item().scope;
    if (scope === 'ENEMY ROW') {
      var unit = this.opponentsUnit();
      var target = unit.smoothTarget(this._targetIndex);
      var row = target.row();
      targets = unit.rowAliveMembers(row);
    } else if (scope === 'ALLY ROW') {
      var unit = this.friendsUnit();
      var target = unit.smoothTarget(this._targetIndex);
      var row = target.row();
      targets = unit.rowAliveMembers(row);
    } else if (scope === 'FRONT ENEMY ROW') {
      var unit = this.opponentsUnit();
      for (var i = 1; i < Yanfly.Param.RowMaximum + 1; ++i) {
        if (unit.rowAliveSize(i) > 0) return unit.rowAliveMembers(i);
      }
    } else if (scope === 'FRONT ALLY ROW') {
      var unit = this.friendsUnit();
      for (var i = 1; i < Yanfly.Param.RowMaximum + 1; ++i) {
        if (unit.rowAliveSize(i) > 0) return unit.rowAliveMembers(i);
      }
    } else if (scope === 'BACK ENEMY ROW') {
      var unit = this.opponentsUnit();
      for (var i = 10; i > 0; --i) {
        if (unit.rowAliveSize(i) > 0) return unit.rowAliveMembers(i);
      }
    } else if (scope === 'BACK ALLY ROW') {
      var unit = this.friendsUnit();
      for (var i = 10; i > 0; --i) {
        if (unit.rowAliveSize(i) > 0) return unit.rowAliveMembers(i);
      }
    } else if (scope === 'SPECIFIC ENEMY ROW') {
      var unit = this.opponentsUnit();
      var i = this.item().rowTarget;
      return unit.rowAliveMembers(i);
    } else if (scope === 'SPECIFIC ALLY ROW') {
      var unit = this.friendsUnit();
      var i = this.item().rowTarget;
      return unit.rowAliveMembers(i);
    }
    return targets;
};

//=============================================================================
// Window_Help
//=============================================================================

if (Imported.YEP_BattleEngineCore) {

Yanfly.Target.Window_Help_setBattler = Window_Help.prototype.setBattler;
Window_Help.prototype.setBattler = function(battler) {
    this._battler = battler;
    Yanfly.Target.Window_Help_setBattler.call(this, battler);
};

Yanfly.Target.Window_Help_specialSelectionText =
    Window_Help.prototype.specialSelectionText;
Window_Help.prototype.specialSelectionText = function(action) {
    BattleManager.resetSelection();
    if (!action) return false;
    if (action.item().customTargetText !== '') return true;
    if (action.isForRow()) return true;
    return Yanfly.Target.Window_Help_specialSelectionText.call(this, action);
};

Yanfly.Target.Window_Help_drawSpecialSelectionText =
    Window_Help.prototype.drawSpecialSelectionText;
Window_Help.prototype.drawSpecialSelectionText = function(action) {
  if (action.item().customTargetText !== '') {
    BattleManager.startAllSelection();
    var wx = 0;
    var wy = (this.contents.height - this.lineHeight()) / 2;
    var text = this.makeCustomTargetText(action);
    this.drawText(text, wx, wy, this.contents.width, 'center');
  } else if (action.isForMultiple()) {
    BattleManager.startAllSelection();
    var wx = 0;
    var wy = (this.contents.height - this.lineHeight()) / 2;
    var text = this.makeTargetMultipleOfText(action);
    this.drawText(text, wx, wy, this.contents.width, 'center');
  } else if (action.isForRow()) {
    this.makeTargetRowText(action);
  } else if (action.isForRandomAny()) {
    var wx = 0;
    var wy = (this.contents.height - this.lineHeight()) / 2;
    var fmt = Yanfly.Param.BECHlpRandomAnyTx;
    var number = action.item().randomTargets;
    var text = fmt.format(Yanfly.Util.toGroup(number));
    this.drawText(text, wx, wy, this.contents.width, 'center');
  } else if (action.isForEverybody()) {
    BattleManager.startAllSelection();
    var wx = 0;
    var wy = (this.contents.height - this.lineHeight()) / 2;
    var text = TextManager.yanflyTargetEverybody;
    this.drawText(text, wx, wy, this.contents.width, 'center');
  } else if (action.isForAllButUser()) {
    BattleManager.startAllSelection();
    var wx = 0;
    var wy = (this.contents.height - this.lineHeight()) / 2;
    var fmt = Yanfly.Param.BECHlpAllBTx;
    var allies = Yanfly.Param.BECHelpAlliesTx;
    var user = Yanfly.Param.BECHelpUserTx
    var text = fmt.format(allies, user);
    this.drawText(text, wx, wy, this.contents.width, 'center');
  } else {
    Yanfly.Target.Window_Help_drawSpecialSelectionText.call(this, action);
  }
};

}; // Imported.YEP_BattleEngineCore

Window_Help.prototype.makeCustomTargetText = function(action) {
    var text = ''
    var s = $gameSwitches._data;
    var v = $gameVariables._data;
    var user = BattleManager._subject;
    var a = user;
    var subject = user;
    var b = user;
    var target = user;
    var code = action.item().customTargetText;
    try {
      eval(code);
    } catch (e) {
      Yanfly.Util.displayError(e, code, 'MAKE CUSTOM TARGET TEXT ERROR');
    }
    return text;
};

Window_Help.prototype.makeTargetMultipleOfText = function(action) {
    var fmt = Yanfly.Param.TargetMultipleTx;
    if (action.isForEverybody()) {
      var targets = TextManager.yanflyTargetMultiEverybody;
    } else if (action.isForFriend()) {
      var targets = TextManager.yanflyTargetMultiAllies;
    } else {
      var targets = TextManager.yanflyTargetMultiFoes;
    }
    var param = action.item().multipleOf[1];
    if (param === 'LEVEL') {
      param = TextManager.level;
    } else if (param === 'HP') {
      param = TextManager.hp;
    } else if (param === 'MP') {
      param = Textmanager.mp;
    } else if (param === 'TP') {
      param = Textmanager.tp;
    } else {
      param = TextManager.param(param);
    }
    var number = action.item().multipleOf[2];
    var text = fmt.format(targets, param, Yanfly.Util.toGroup(number));
    return text;
};

Window_Help.prototype.makeTargetRowText = function(action) {
    action.setTarget(this._battler.index());
    BattleManager.startAllSelection();
    var wx = 0;
    var wy = (this.contents.height - this.lineHeight()) / 2;
    var scope = action.item().scope;
    if (scope === 'ENEMY ROW' || scope === 'ALLY ROW') {
      var fmt = Yanfly.Param.TargetHlpRowTx;
      var text = fmt.format(this._battler.name());
    } else if (scope === 'FRONT ENEMY ROW') {
      var fmt = Yanfly.Param.TargetFrontRow;
      var text = fmt.format(Yanfly.Param.TargetRowEnemies);
    } else if (scope === 'BACK ENEMY ROW') {
      var fmt = Yanfly.Param.TargetBackRow;
      var text = fmt.format(Yanfly.Param.TargetRowEnemies);
    } else if (scope === 'SPECIFIC ENEMY ROW') {
      var fmt = Yanfly.Param.TargetSpcRow;
      var text = fmt.format(Yanfly.Param.TargetRowEnemies);
    } else if (scope === 'FRONT ALLY ROW') {
      var fmt = Yanfly.Param.TargetFrontRow;
      var text = fmt.format(Yanfly.Param.TargetRowAllies);
    } else if (scope === 'BACK ALLY ROW') {
      var fmt = Yanfly.Param.TargetBackRow;
      var text = fmt.format(Yanfly.Param.TargetRowAllies);
    } else if (scope === 'SPECIFIC ALLY ROW') {
      var fmt = Yanfly.Param.TargetSpcRow;
      var text = fmt.format(Yanfly.Param.TargetRowAllies);
    }
    this.drawText(text, wx, wy, this.contents.width, 'center');
};

//=============================================================================
// Window_EnemyVisualSelect
//=============================================================================

if (Imported.YEP_BattleEngineCore) {

Yanfly.Target.Window_EnemyVisualSelect_isShowWindow =
    Window_EnemyVisualSelect.prototype.isShowWindow;
Window_EnemyVisualSelect.prototype.isShowWindow = function() {
    if (BattleManager.customTargetSelectGroup().length > 0) {
      return BattleManager.customTargetSelectGroup().contains(this._battler);
    }
    return Yanfly.Target.Window_EnemyVisualSelect_isShowWindow.call(this);
};

}; // Imported.YEP_BattleEngineCore

//=============================================================================
// Scene_Battle
//=============================================================================

Yanfly.Target.Scene_Battle_onEnemyOk = Scene_Battle.prototype.onEnemyOk;
Scene_Battle.prototype.onEnemyOk = function() {
    BattleManager.clearCustomTargetSelectGroup();
    Yanfly.Target.Scene_Battle_onEnemyOk.call(this);
};

Yanfly.Target.Scene_Battle_onEnemyCancel = Scene_Battle.prototype.onEnemyCancel;
Scene_Battle.prototype.onEnemyCancel = function() {
    BattleManager.clearCustomTargetSelectGroup();
    Yanfly.Target.Scene_Battle_onEnemyCancel.call(this);
};

Yanfly.Target.Scene_Battle_onActorOk = Scene_Battle.prototype.onActorOk;
Scene_Battle.prototype.onActorOk = function() {
    BattleManager.clearCustomTargetSelectGroup();
    Yanfly.Target.Scene_Battle_onActorOk.call(this);
};

Yanfly.Target.Scene_Battle_onActorCancel = Scene_Battle.prototype.onActorCancel;
Scene_Battle.prototype.onActorCancel = function() {
    BattleManager.clearCustomTargetSelectGroup();
    Yanfly.Target.Scene_Battle_onActorCancel.call(this);
};

//=============================================================================
// Utilities
//=============================================================================

Yanfly.Util = Yanfly.Util || {};

if (!Yanfly.Util.toGroup) {
    Yanfly.Util.toGroup = function(inVal) {
        return inVal;
    }
};

Yanfly.Util.displayError = function(e, code, message) {
  console.log(message);
  console.log(code || 'NON-EXISTENT');
  console.error(e);
  if (Utils.RPGMAKER_VERSION && Utils.RPGMAKER_VERSION >= "1.6.0") return;
  if (Utils.isNwjs() && Utils.isOptionValid('test')) {
    if (!require('nw.gui').Window.get().isDevToolsOpen()) {
      require('nw.gui').Window.get().showDevTools();
    }
  }
};

//=============================================================================
// End of File
//=============================================================================


code:
//=============================================================================
// Yanfly Engine Plugins - Utility Common Events
// YEP_UtilityCommonEvents.js
//=============================================================================

var Imported = Imported || {};
Imported.YEP_UtilityCommonEvents = true;

var Yanfly = Yanfly || {};
Yanfly.UCE = Yanfly.UCE || {};
Yanfly.UCE.version = 1.00;

//=============================================================================
 /*:
 * @plugindesc v1.00 Make common events occur at specific gameplay points
 * such as on loading, after battles, etc.
 * @author Yanfly Engine Plugins
 *
 * @param ---General---
 * @default
 *
 * @param Load Game Event
 * @desc Run this common event each time the player loads a game.
 * Set as 0 if you do not wish to run a common event.
 * @default 0
 *
 * @param Battle Won Event
 * @desc Run this common event each time the player wins a battle.
 * Set as 0 if you do not wish to run a common event.
 * @default 0
 *
 * @param Escape Battle Event
 * @desc Run this common event each time the player wins a battle.
 * Set as 0 if you do not wish to run a common event.
 * @default 0
 *
 * @param Close Menu Event
 * @desc Run this common event each time the player closes main menu.
 * Set as 0 if you do not wish to run a common event.
 * @default 0

 * @param ---Vehicles---
 * @default
 *
 * @param Boat Enter Event
 * @desc Run this common event each time the player enters a boat.
 * Set as 0 if you do not wish to run a common event.
 * @default 0
 *
 * @param Boat Exit Event
 * @desc Run this common event each time the player exits a boat.
 * Set as 0 if you do not wish to run a common event.
 * @default 0
 *
 * @param Ship Enter Event
 * @desc Run this common event each time the player enters a ship.
 * Set as 0 if you do not wish to run a common event.
 * @default 0
 *
 * @param Ship Exit Event
 * @desc Run this common event each time the player exits a ship.
 * Set as 0 if you do not wish to run a common event.
 * @default 0
 *
 * @param Airship Enter Event
 * @desc Run this common event each time the player enters airship.
 * Set as 0 if you do not wish to run a common event.
 * @default 0
 *
 * @param Airship Exit Event
 * @desc Run this common event each time the player exits airship.
 * Set as 0 if you do not wish to run a common event.
 * @default 0
 *
 * @help
 * ============================================================================
 * Introduction
 * ============================================================================
 *
 * Sometimes, we'd like a little bit more control over the kinds of things that
 * occur during certain aspects of our RPG Maker projects. What could have been
 * easily done through common events is made more difficult because there are
 * no proper triggers to activate those common events. This plugin enables
 * certain triggers to occur from loading a game, winning a battle, escaping a
 * battle, and more.
 *
 * ============================================================================
 * Instructions
 * ============================================================================
 *
 * Change the plugin parameters for each of the triggers you want tied to a
 * common event to reflect the ID of that common event. The triggers will be
 * the following along with some examples of how they can be used:
 *
 * - Load Game -
 * Will occur whenever the game is loaded. This can be used for things like
 * story recaps, adjusting in-game timers, or checking for updates.
 *
 * - Battle Won -
 * Will proc whenever a battle is won and the player returns to the map. Can be
 * used for things like updating certain variables or statistics after battle.
 *
 * - Escape Battle -
 * Like the previous but will occur whenever the player escapes battle instead.
 * This can be used for things such as events where the player would have to be
 * on a stealth mission or whatever and escaping can bring them back into a
 * certain spot.
 *
 * - Close Menu -
 * Occurs when the player exits the main menu and returns to the map scene. Can
 * be used for recalibrating equipment, making checks, custom events, and more.
 *
 * - Vehicle Enter -
 * - Vehicle Exit -
 * These events will occur whenever the player will enter/exit the specific
 * vehicle. This can be used to enable/disable certain HUD's while in specific
 * vehicles to give a more immersive feeling.
 */
//=============================================================================

//=============================================================================
// Parameter Variables
//=============================================================================

Yanfly.Parameters = PluginManager.parameters('YEP_UtilityCommonEvents');
Yanfly.Param = Yanfly.Param || {};

Yanfly.Param.UtilCommonEvents = {
  load: Number(Yanfly.Parameters['Load Game Event']) || 0,
  battleWon: Number(Yanfly.Parameters['Battle Won Event']) || 0,
  battleEscape: Number(Yanfly.Parameters['Battle Escape Event']) || 0,
  closeMenu: Number(Yanfly.Parameters['Close Menu Event']) || 0,

  boatEnter: Number(Yanfly.Parameters['Boat Enter Event']) || 0,
  boatExit: Number(Yanfly.Parameters['Boat Exit Event']) || 0,
  shipEnter: Number(Yanfly.Parameters['Ship Enter Event']) || 0,
  shipExit: Number(Yanfly.Parameters['Ship Exit Event']) || 0,
  airshipEnter: Number(Yanfly.Parameters['Airship Enter Event']) || 0,
  airshipExit: Number(Yanfly.Parameters['Airship Exit Event']) || 0,
};

//=============================================================================
// DataManager
//=============================================================================

Yanfly.UCE.DataManager_loadGame = DataManager.loadGame;
DataManager.loadGame = function(savefileId) {
  var flag = Yanfly.UCE.DataManager_loadGame.call(this, savefileId);
  if (flag && Yanfly.Param.UtilCommonEvents['load'] > 0) {
		$gameParty.emergencyGameVersionFix();
		$gameTemp.reserveCommonEvent(Yanfly.Param.UtilCommonEvents['load']);
  }
  return flag;
};

//=============================================================================
// Game_System
//=============================================================================

Yanfly.UCE.Game_System_onBattleWin = Game_System.prototype.onBattleWin;
Game_System.prototype.onBattleWin = function() {
  Yanfly.UCE.Game_System_onBattleWin.call(this);
  if (Yanfly.Param.UtilCommonEvents['battleWon'] > 0) {
    $gameTemp.reserveCommonEvent(Yanfly.Param.UtilCommonEvents['battleWon']);
  }
};

Yanfly.UCE.Game_System_onBattleEscape = Game_System.prototype.onBattleEscape;
Game_System.prototype.onBattleEscape = function() {
  Yanfly.UCE.Game_System_onBattleEscape.call(this);
  if (Yanfly.Param.UtilCommonEvents['battleEscape'] > 0) {
    $gameTemp.reserveCommonEvent(Yanfly.Param.UtilCommonEvents['battleEscape']);
  }
};

//=============================================================================
// Game_Player
//=============================================================================

Yanfly.UCE.Game_Player_getOnVehicle = Game_Player.prototype.getOnVehicle;
Game_Player.prototype.getOnVehicle = function() {
  var success = Yanfly.UCE.Game_Player_getOnVehicle.call(this);
  if (success) {
    var events = Yanfly.Param.UtilCommonEvents;
    if (this._vehicleType === 'airship' && events.airshipEnter > 0) {
      $gameTemp.reserveCommonEvent(events.airshipEnter);
    } else if (this._vehicleType === 'ship' && events.shipEnter > 0) {
      $gameTemp.reserveCommonEvent(events.shipEnter);
    } else if (this._vehicleType === 'boat' && events.boatEnter > 0) {
      $gameTemp.reserveCommonEvent(events.boatEnter);
    }
  }
  return success;
};

Yanfly.UCE.Game_Player_getOffVehicle = Game_Player.prototype.getOffVehicle;
Game_Player.prototype.getOffVehicle = function() {
  var success = Yanfly.UCE.Game_Player_getOffVehicle.call(this);
  if (success) {
    var events = Yanfly.Param.UtilCommonEvents;
    if (this._vehicleType === 'airship' && events.airshipExit > 0) {
      $gameTemp.reserveCommonEvent(events.airshipExit);
    } else if (this._vehicleType === 'ship' && events.shipExit > 0) {
      $gameTemp.reserveCommonEvent(events.shipExit);
    } else if (this._vehicleType === 'boat' && events.boatExit > 0) {
      $gameTemp.reserveCommonEvent(events.boatExit);
    }
  }
  return success;
};

//=============================================================================
// Scene_Menu
//=============================================================================

Yanfly.UCE.Scene_Menu_createCommandWindow =
  Scene_Menu.prototype.createCommandWindow;
Scene_Menu.prototype.createCommandWindow = function() {
  Yanfly.UCE.Scene_Menu_createCommandWindow.call(this);
  this._commandWindow.setHandler('cancel', this.closeMainMenu.bind(this));
};

Scene_Menu.prototype.closeMainMenu = function() {
  this.popScene();
  if (Yanfly.Param.UtilCommonEvents['closeMenu'] > 0) {
    $gameTemp.reserveCommonEvent(Yanfly.Param.UtilCommonEvents['closeMenu']);
  }
};

//=============================================================================
// End of File
//=============================================================================

repo_name: voidljb/karryn

license: unknown


code:
//=============================================================================
// Yanfly Engine Plugins - Victory Aftermath
// YEP_VictoryAftermath.js
//=============================================================================

var Imported = Imported || {};
Imported.YEP_VictoryAftermath = true;

var Yanfly = Yanfly || {};
Yanfly.VA = Yanfly.VA || {};
Yanfly.VA.version = 1.07

//=============================================================================
 /*:
 * @plugindesc v1.07 Display an informative window after a battle is over
 * instead of message box text stating what the party earned.
 * @author Yanfly Engine Plugins
 *
 * @param ---General---
 * @default
 *
 * @param Victory Order
 * @parent ---General---
 * @desc This is the order the victory sequence will play out.
 * Separate each part with a space.
 * @default exp custom drops
 *
 * @param ---BGM---
 * @default
 *
 * @param Victory BGM
 * @parent ---BGM---
 * @type file
 * @dir audio/bgm/
 * @require 1
 * @desc This will be the BGM used when the battle is over.
 * @default Ship3
 *
 * @param BGM Volume
 * @parent ---BGM---
 * @desc This will be the volume of the BGM played.
 * @default 90
 *
 * @param BGM Pitch
 * @parent ---BGM---
 * @desc This will be the pitch of the BGM played.
 * @default 100
 *
 * @param BGM Pan
 * @parent ---BGM---
 * @desc This will be the pan of the BGM played.
 * @default 0
 *
 * @param ---Battle Results---
 * @default
 *
 * @param Cheer Wait
 * @parent ---Battle Results---
 * @type number
 * @min 0
 * @desc This will be how many frames the actors will cheer for
 * before the Victory Aftermath windows appear.
 * @default 90
 *
 * @param Battle Results Text
 * @parent ---Battle Results---
 * @desc This is the text used for the battle results text.
 * @default Battle Results
 *
 * @param Battle Drops Text
 * @parent ---Battle Results---
 * @desc This is the text used for the drops gained in battle.
 * @default Battle Spoils
 *
 * @param ---EXP Window---
 * @default
 *
 * @param Font Size
 * @parent ---EXP Window---
 * @type number
 * @min 1
 * @desc This is the font size used for the EXP Window.
 * Default: 28
 * @default 28
 *
 * @param Level Up Text
 * @parent ---EXP Window---
 * @desc The text to be used when leveling up.
 * @default LEVEL UP!
 *
 * @param Max Level Text
 * @parent ---EXP Window---
 * @desc The text to be used when the actor is Max Level.
 * @default MAX LEVEL
 *
 * @param Show Skills Learned
 * @parent ---EXP Window---
 * @type boolean
 * @on Display Skills
 * @off Don't Display
 * @desc Display skills learned at level up?
 * NO - false     YES - true
 * @default false
 *
 * @param Gained EXP Text
 * @parent ---EXP Window---
 * @desc The text to label how much EXP was gained in battle.
 * @default Gained EXP
 *
 * @param Gained EXP Format
 * @parent ---EXP Window---
 * @desc The text to display how much EXP was gained in battle.
 * @default +%1
 *
 * @param EXP Gauge Color 1
 * @parent ---EXP Window---
 * @type number
 * @min 0
 * @max 31
 * @desc The skin color used in EXP Gauge Color 1 shown in the
 * Victory Aftermath Window.
 * @default 30
 *
 * @param EXP Gauge Color 2
 * @parent ---EXP Window---
 * @type number
 * @min 0
 * @max 31
 * @desc The skin color used in EXP Gauge Color 2 shown in the
 * Victory Aftermath Window.
 * @default 31
 *
 * @param Level Gauge Color 1
 * @parent ---EXP Window---
 * @type number
 * @min 0
 * @max 31
 * @desc The skin color used for the EXP Gauge Color 1 if the actor
 * has leveled up.
 * @default 14
 *
 * @param Level Gauge Color 2
 * @parent ---EXP Window---
 * @type number
 * @min 0
 * @max 31
 * @desc The skin color used for the EXP Gauge Color 2 if the actor
 * has leveled up.
 * @default 6
 *
 * @param Gauge Ticks
 * @parent ---EXP Window---
 * @type number
 * @min 0
 * @desc This is how many ticks will occur before the gained EXP
 * gauge is full. Each tick is 4 frames.
 * @default 15
 *
 * @param Tick SE
 * @parent ---EXP Window---
 * @type file
 * @dir audio/se/
 * @require 1
 * @desc This will be the sound used while the EXP gauge fills up.
 * @default Absorb2
 *
 * @param Tick Volume
 * @parent ---EXP Window---
 * @desc This will be the volume of the BGM played.
 * @default 90
 *
 * @param Tick Pitch
 * @parent ---EXP Window---
 * @desc This will be the pitch of the BGM played.
 * @default 150
 *
 * @param Tick Pan
 * @parent ---EXP Window---
 * @desc This will be the pan of the BGM played.
 * @default 0
 *
 * @help
 * ============================================================================
 * Introduction
 * ============================================================================
 *
 * This plugin swaps out the victory messages from the default battle system in
 * favor of more informative windows to display. Adjust the parameters to
 * change the settings to fit your game.
 *
 * ============================================================================
 * Victory Aftermath
 * ============================================================================
 *
 * In the parameters, there's a 'Victory Order' parameter. This parameter lets
 * you choose the order of the steps in the Victory Aftermath.
 *
 * The default order is as follows:
 *           exp         Displays the EXP window.
 *           custom      Displays any custom plugin extensions.
 *           drops       Displays the drops window.
 *
 * If you switch the order of these steps, add steps, or remove steps from the
 * 'Victory Order' plugin, the Victory Aftermath will correspond to any changes
 * you have made.
 *
 * ============================================================================
 * Plugin Commands
 * ============================================================================
 *
 * If you wish to alter the Victory Aftermath sequence a bit, you can use the
 * following Plugin Commands.
 *
 * Plugin Commands:
 *   DisableVictoryAftermath   - Disables the Victory Aftermath sequence and
 *                               bypasses the Victory Aftermath music, too.
 *   EnableVictoryAftermath    - Enables the Victory Aftermath sequence if
 *                               it has been previously disabled.
 *   DisableVictoryMusic       - Disables the Victory Aftermath music to just
 *                               continue playing whatever was playing.
 *   EnableVictoryMusic        - Enables the Victory Aftermath music if it has
 *                               been previously disabled.
 *
 * ============================================================================
 * Changelog
 * ============================================================================
 *
 * Version 1.07:
 * - Updated for RPG Maker MV version 1.5.0.
 *
 * Version 1.06:
 * - Updated for RPG Maker MV version 1.3.2.
 *
 * Version 1.05a:
 * - Added 'Font Size' plugin parameter to alter the font size for the battle
 * results page.
 * - Fixed a graphical issue where an actor in crisis would display its level
 * in the crisis color.
 * - Changed the Victory Aftermath sequence so that the player can hold down a
 * button to quickly go through all the Victory Sequence menus.
 *
 * Version 1.04:
 * - Updated the plugin so it doesn't break visually when party sizes are too
 * large. That said, if the party size is beyond a certain amount, this plugin
 * will not support that many faces for it and will fit just the bare minimum.
 *
 * Version 1.03:
 * - Added parameter 'Show Skills Learned'.
 *
 * Version 1.02:
 * - If the Battle HUD has been hidden for whatever reason during the victory
 * sequence, it will be returned.
 *
 * Version 1.01:
 * - Fixed a bug plugin commands that would cause some victory sequences to
 * loop forever.
 *
 * Version 1.00:
 * - Finished plugin!
 */
//=============================================================================

//=============================================================================
// Parameter Variables
//=============================================================================

Yanfly.Parameters = PluginManager.parameters('YEP_VictoryAftermath');
Yanfly.Param = Yanfly.Param || {};

Yanfly.Param.VAOrder = String(Yanfly.Parameters['Victory Order']);

Yanfly.Param.VACheerWait = Number(Yanfly.Parameters['Cheer Wait']);
Yanfly.Param.VABattleResults = String(Yanfly.Parameters['Battle Results Text']);
Yanfly.Param.VABattleDrops = String(Yanfly.Parameters['Battle Drops Text']);

Yanfly.Param.VABgmName = String(Yanfly.Parameters['Victory BGM']);
Yanfly.Param.VABgmVol = Number(Yanfly.Parameters['BGM Volume']);
Yanfly.Param.VABgmPitch = Number(Yanfly.Parameters['BGM Pitch']);
Yanfly.Param.VABgmPan = Number(Yanfly.Parameters['BGM Pan']);

Yanfly.Param.VAFontSize = Number(Yanfly.Parameters['Font Size']);
Yanfly.Param.VALevelUp = String(Yanfly.Parameters['Level Up Text']);
Yanfly.Param.VAMaxLv = String(Yanfly.Parameters['Max Level Text']);
Yanfly.Param.VAShowSkills = String(Yanfly.Parameters['Show Skills Learned']);
Yanfly.Param.VAGainedExp = String(Yanfly.Parameters['Gained EXP Text']);
Yanfly.Param.VAGainedExpfmt = String(Yanfly.Parameters['Gained EXP Format']);
Yanfly.Param.ColorExp1 = Number(Yanfly.Parameters['EXP Gauge Color 1']);
Yanfly.Param.ColorExp2 = Number(Yanfly.Parameters['EXP Gauge Color 2']);
Yanfly.Param.ColorLv1 = Number(Yanfly.Parameters['Level Gauge Color 1']);
Yanfly.Param.ColorLv2 = Number(Yanfly.Parameters['Level Gauge Color 2']);
Yanfly.Param.VAGaugeTicks = Number(Yanfly.Parameters['Gauge Ticks']);
Yanfly.Param.VATickName = String(Yanfly.Parameters['Tick SE']);
Yanfly.Param.VATickVol = Number(Yanfly.Parameters['Tick Volume']);
Yanfly.Param.VATickPitch = Number(Yanfly.Parameters['Tick Pitch']);
Yanfly.Param.VATickPan = Number(Yanfly.Parameters['Tick Pan']);

//=============================================================================
// BattleManager
//=============================================================================

Yanfly.VA.BattleManager_initMembers = BattleManager.initMembers;
BattleManager.initMembers = function() {
    Yanfly.VA.BattleManager_initMembers.call(this);
    this.initVictoryData();
};

BattleManager.initVictoryData = function() {
    this._victoryPhase = false;
    this._victoryCheerWait = 0;
    this._victoryStep = 0;
};

BattleManager.processVictory = function() {
    $gameParty.performVictory();
    if (this.isVictoryPhase()) return;
    if (this._windowLayer) this._windowLayer.x = 0;
    $gameParty.removeBattleStates();
    this._victoryPhase = true;
    if ($gameSystem.skipVictoryAftermath()) {
      this.processSkipVictory();
    } else {
      this.processNormalVictory();
    }
};

BattleManager.isVictoryPhase = function() {
    return this._victoryPhase;
};

BattleManager.isFinishedVictoryCheer = function() {
    return ++this._victoryCheerWait >= Yanfly.Param.VACheerWait;
};

BattleManager.processSkipVictory = function() {
    this.makeRewards();
    this.gainRewards();
    this.replayBgmAndBgs();
    this.endBattle(0);
};

BattleManager.processNormalVictory = function() {
    if (!$gameSystem.skipVictoryMusic()) this.playVictoryMe();
    this.makeRewards();
    this.startVictoryPhase();
};

Yanfly.VA.BattleManager_playVictoryMe = BattleManager.playVictoryMe;
BattleManager.playVictoryMe = function() {
    Yanfly.VA.BattleManager_playVictoryMe.call(this);
    this.playVictoryBGM();
};

BattleManager.playVictoryBGM = function() {
    var victoryBgm = {
      name:   Yanfly.Param.VABgmName,
      volume: Yanfly.Param.VABgmVol,
      pitch:  Yanfly.Param.VABgmPitch,
      pan:    Yanfly.Param.VABgmPan
    };
    AudioManager.playBgm(victoryBgm);
};

BattleManager.startVictoryPhase = function() {
    this._victoryCheerWait = 0;
    this._victoryStep = 0;
    this.prepareVictoryInfo();
};

BattleManager.prepareVictoryInfo = function() {
    $gameParty.allMembers().forEach(function(actor) {
        ImageManager.loadFace(actor.faceName());
        actor._preVictoryExp = actor.currentExp();
        actor._preVictoryLv = actor._level;
        actor._victoryPhase = true;
        actor._victorySkills = [];
    }, this);
    this.gainRewards();
    $gameParty.allMembers().forEach(function(actor) {
        actor._expGained = actor.currentExp() - actor._preVictoryExp;
        actor._postVictoryLv = actor._level;
    }, this);
};

BattleManager.processVictoryFinish = function() {
    $gameParty.clearVictoryData();
    this.endBattle(0);
    this.replayBgmAndBgs();
    this._victoryPhase = false;
};

//=============================================================================
// Game_System
//=============================================================================

Yanfly.VA.Game_System_initialize = Game_System.prototype.initialize;
Game_System.prototype.initialize = function() {
    Yanfly.VA.Game_System_initialize.call(this);
    this._skipVictoryAftermath = false;
    this._skipVictoryMusic = false;
};

Game_System.prototype.skipVictoryAftermath = function() {
    return this._skipVictoryAftermath;
};

Game_System.prototype.skipVictoryMusic = function() {
    return this._skipVictoryMusic;
};

//=============================================================================
// Game_Actor
//=============================================================================

Yanfly.VA.Game_Actor_shouldDisplayLevelUp =
    Game_Actor.prototype.shouldDisplayLevelUp;
Game_Actor.prototype.shouldDisplayLevelUp = function() {
    if ($gameParty.inBattle()) return false;
    return Yanfly.VA.Game_Actor_shouldDisplayLevelUp.call(this);
};

Game_Actor.prototype.clearVictoryData = function() {
    this._preVictoryExp = undefined;
    this._preVictoryLv = undefined;
    this._expGained = undefined;
    this._postVictoryLv = undefined;
    this._victoryPhase = undefined;
    this._victorySkills = undefined;
};

Game_Actor.prototype.isLearnedSkillRaw = function(skillId) {
  return this._skills.contains(skillId);
};

Yanfly.VA.Game_Actor_learnSkill = Game_Actor.prototype.learnSkill;
Game_Actor.prototype.learnSkill = function(skillId) {
    if (!this.isLearnedSkillRaw(skillId) && this._victoryPhase) {
      this._victorySkills.push(skillId);
    }
    Yanfly.VA.Game_Actor_learnSkill.call(this, skillId);
};

//=============================================================================
// Game_Party
//=============================================================================

Game_Party.prototype.clearVictoryData = function() {
    for (var i = 0; i < this.members().length; ++i) {
      var actor = this.members()[i];
      if (!actor) continue;
      actor.clearVictoryData();
    }
};

//=============================================================================
// Game_Interpreter
//=============================================================================

/*
Yanfly.VA.Game_Interpreter_pluginCommand =
    Game_Interpreter.prototype.pluginCommand;
Game_Interpreter.prototype.pluginCommand = function(command, args) {
    Yanfly.VA.Game_Interpreter_pluginCommand.call(this, command, args)
    if (command === 'DisableVictoryAftermath') {
      $gameSystem._skipVictoryAftermath = true;
    }
    if (command === 'EnableVictoryAftermath') {
      $gameSystem._skipVictoryAftermath = false;
    }
    if (command === 'DisableVictoryMusic') {
      $gameSystem._skipVictoryMusic = true;
    }
    if (command === 'EnableVictoryMusic') {
      $gameSystem._skipVictoryMusic = false;
    }
};
*/

Game_Interpreter.prototype.gotoSceneParty = function() {
    if (!$gameParty.inBattle()) SceneManager.push(Scene_Party);
    return true;
};

Game_Interpreter.prototype.lockActor = function(args, value) {
    for (i = 0; i < args.length; i++) {
      var actorId = Number(args[i]);
      if ($gameActors.actor(actorId)) {
        $gameActors.actor(actorId)._locked = value;
      }
    }
};

Game_Interpreter.prototype.requireActor = function(args, value) {
    for (i = 0; i < args.length; i++) {
      var actorId = Number(args[i]);
      if ($gameActors.actor(actorId)) {
        $gameActors.actor(actorId)._required = value;
      }
    }
};

//=============================================================================
// Window_VictoryTitle
//=============================================================================

function Window_VictoryTitle() {
    this.initialize.apply(this, arguments);
}

Window_VictoryTitle.prototype = Object.create(Window_Base.prototype);
Window_VictoryTitle.prototype.constructor = Window_VictoryTitle;

Window_VictoryTitle.prototype.initialize = function() {
    var width = this.windowWidth();
    var height = this.windowHeight();
    Window_Base.prototype.initialize.call(this, 0, 0, width, height);
    this.refresh(Yanfly.Param.VABattleResults);
    this.openness = 0;
};

Window_VictoryTitle.prototype.windowWidth = function() {
    return Graphics.boxWidth;
};

Window_VictoryTitle.prototype.windowHeight = function() {
    return this.fittingHeight(1);
};

Window_VictoryTitle.prototype.refresh = function(text) {
    this.contents.clear();
    this.drawText(text, 0, 0, this.contents.width, 'center');
};

//=============================================================================
// Window_VictoryExp
//=============================================================================

function Window_VictoryExp() {
    this.initialize.apply(this, arguments);
}

Window_VictoryExp.prototype = Object.create(Window_Selectable.prototype);
Window_VictoryExp.prototype.constructor = Window_VictoryExp;

Window_VictoryExp.prototype.initialize = function() {
    var wy = this.fittingHeight(1);
    var width = this.windowWidth();
    var height = this.windowHeight();
    this._showGainedSkills = eval(Yanfly.Param.VAShowSkills);
    Window_Selectable.prototype.initialize.call(this, 0, wy, width, height);
    this.defineTickSound();
    this.refresh();
    AudioManager.playSe(this._tickSound);
    this._tick = 0;
    this.openness = 0;
};

Window_VictoryExp.prototype.windowWidth = function() {
    return Graphics.boxWidth;
};

Window_VictoryExp.prototype.windowHeight = function() {
    return Graphics.boxHeight - this.fittingHeight(1);
};

Window_VictoryExp.prototype.maxItems = function() {
    return $gameParty.maxBattleMembers();
};

Window_VictoryExp.prototype.standardFontSize = function() {
    return Yanfly.Param.VAFontSize;
};

Window_VictoryExp.prototype.lineHeight = function() {
    return this.standardFontSize() + 8;
};

Window_VictoryExp.prototype.itemHeight = function() {
    var clientHeight = this.height - this.padding * 2;
    var clientHeight = Math.floor(clientHeight / this.maxItems());
    var clientHeight = Math.max(clientHeight, this.lineHeight() * 2);
    return clientHeight;
};

Window_VictoryExp.prototype.textWidthEx = function(text) {
    return this.drawTextEx(text, 0, this.contents.height);
};

Window_VictoryExp.prototype.defineTickSound = function() {
    this._tickSound = {
      name:   Yanfly.Param.VATickName,
      volume: Yanfly.Param.VATickVol,
      pitch:  Yanfly.Param.VATickPitch,
      pan:    Yanfly.Param.VATickPan
    };
};

Window_VictoryExp.prototype.update = function() {
    Window_Selectable.prototype.update.call(this);
    if (this.openness >= 255) this.updateTicks();
};

Window_VictoryExp.prototype.updateTicks = function() {
    if (this._tick >= Yanfly.Param.VAGaugeTicks) return;
    if (Graphics.frameCount % 4 !== 0) return;
    if (Input.isPressed('ok') || TouchInput.isPressed()) {
      this._tick = Yanfly.Param.VAGaugeTicks;
    } else {
      this._tick += 1;
    }
    this.drawAllGauges();
};

Window_VictoryExp.prototype.drawAllGauges = function() {
    var topIndex = this.topIndex();
    for (var i = 0; i < this.maxPageItems(); i++) {
      var index = topIndex + i;
      if (index < this.maxItems()) this.drawItemGauge(index);
    }
};

Window_VictoryExp.prototype.drawItem = function(index) {
    var actor = $gameParty.battleMembers()[index];
    if (!actor) return;
    this.drawActorProfile(actor, index);
};

Window_VictoryExp.prototype.drawActorProfile = function(actor, index) {
    var rect = this.itemRect(index);
    var fw = Window_Base._faceWidth;
    this.drawActorFace(actor, rect.x + 1, rect.y + 1, fw, rect.height - 2);
};

Window_VictoryExp.prototype.drawItemGauge = function(index) {
    var actor = $gameParty.battleMembers()[index];
    if (!actor) return;
    this.drawActorGauge(actor, index);
};

Window_VictoryExp.prototype.gaugeRect = function(index) {
    var rect = this.itemRect(index);
    var fw = Window_Base._faceWidth;
    rect.x += fw + this.standardPadding() * 2;
    rect.width -= fw * 2 + this.standardPadding() * 4;
    return rect;
};

Window_VictoryExp.prototype.clearGaugeRect = function(index) {
    var rect = this.gaugeRect(index);
    this.contents.clearRect(rect.x, rect.y, rect.width, rect.height);
};

Window_VictoryExp.prototype.drawActorGauge = function(actor, index) {
    this.clearGaugeRect(index);
    var rect = this.gaugeRect(index);
    this.changeTextColor(this.normalColor());
    this.drawActorName(actor, rect.x + 2, rect.y);
    this.drawLevel(actor, rect);
    this.drawExpGauge(actor, rect);
    this.drawExpValues(actor, rect);
    this.drawExpGained(actor, rect);
    this.drawGainedSkills(actor, rect);
};

Window_VictoryExp.prototype.drawLevel = function(actor, rect) {
    this.changeTextColor(this.normalColor());
    if (this.actorExpRate(actor) >= 1.0) {
      var text = Yanfly.Util.toGroup(actor._postVictoryLv);
    } else {
      var text = Yanfly.Util.toGroup(actor._preVictoryLv);
    }
    this.drawText(text, rect.x + 2, rect.y, rect.width - 4, 'right');
    var ww = rect.width - 4 - this.textWidth('0' +
      Yanfly.Util.toGroup(actor.maxLevel()));
    this.changeTextColor(this.systemColor());
    this.drawText(TextManager.levelA, rect.x + 2, rect.y, ww, 'right');
};

Window_VictoryExp.prototype.actorExpRate = function(actor) {
    var actorLv = actor._preVictoryLv;
    if (actorLv === actor.maxLevel()) return 1.0;
    var bonusExp = 1.0 * actor._expGained * this._tick /
      Yanfly.Param.VAGaugeTicks;
    var nowExp = actor._preVictoryExp - actor.expForLevel(actorLv) + bonusExp;
    var nextExp = actor.expForLevel(actorLv + 1) - actor.expForLevel(actorLv);
    return (1.0 * nowExp / nextExp).clamp(0.0, 1.0);
};

Window_VictoryExp.prototype.drawExpGauge = function(actor, rect) {
    var rate = this.actorExpRate(actor);
    if (rate >= 1.0) {
      var color1 = this.textColor(Yanfly.Param.ColorLv1);
      var color2 = this.textColor(Yanfly.Param.ColorLv2);
    } else {
      var color1 = this.textColor(Yanfly.Param.ColorExp1);
      var color2 = this.textColor(Yanfly.Param.ColorExp2);
    }
    var wy = rect.y + this.lineHeight();
    this.drawGauge(rect.x, wy, rect.width, rate, color1, color2);
};

Window_VictoryExp.prototype.drawExpValues = function(actor, rect) {
    var wy = rect.y + this.lineHeight();
    var actorLv = actor._preVictoryLv;
    var bonusExp = 1.0 * actor._expGained * this._tick /
      Yanfly.Param.VAGaugeTicks;
    var nowExp = actor._preVictoryExp - actor.expForLevel(actorLv) + bonusExp;
    var nextExp = actor.expForLevel(actorLv + 1) - actor.expForLevel(actorLv);
    if (actorLv === actor.maxLevel()) {
      var text = Yanfly.Param.VAMaxLv;
    } else if (nowExp >= nextExp) {
      var text = Yanfly.Param.VALevelUp;
    } else {
      var text = Yanfly.Util.toGroup(parseInt(nextExp - nowExp));
    }
    this.changeTextColor(this.normalColor());
    this.drawText(text, rect.x + 2, wy, rect.width - 4, 'right');
};

Window_VictoryExp.prototype.drawExpGained = function(actor, rect) {
    var wy = rect.y + this.lineHeight() * 2;
    if (wy >= rect.y + rect.height) return;
    this.changeTextColor(this.systemColor());
    this.drawText(Yanfly.Param.VAGainedExp, rect.x + 2, wy, rect.width - 4,
      'left');
    var bonusExp = 1.0 * actor._expGained * this._tick /
      Yanfly.Param.VAGaugeTicks;
    var expParse = Yanfly.Util.toGroup(parseInt(bonusExp));
    var expText = Yanfly.Param.VAGainedExpfmt.format(expParse);
    this.changeTextColor(this.normalColor());
    this.drawText(expText, rect.x + 2, wy, rect.width - 4, 'right');
};

Window_VictoryExp.prototype.drawGainedSkills = function(actor, rect) {
    if (actor._victorySkills.length <= 0) return;
    if (!this.meetDrawGainedSkillsCondition(actor)) return;
    var wy = rect.y;
    for (var i = 0; i < actor._victorySkills.length; ++i) {
      if (wy + this.lineHeight() > rect.y + rect.height) break;
      var skillId = actor._victorySkills[i];
      var skill = $dataSkills[skillId];
      if (!skill) continue;
      var text = '\\i[' + skill.iconIndex + ']' + skill.name;
      text = TextManager.obtainSkill.format(text);
      var ww = this.textWidthEx(text);
      var wx = rect.x + (rect.width - ww) / 2;
      this.drawTextEx(text, wx, wy);
      wy += this.lineHeight();
    }
};

Window_VictoryExp.prototype.meetDrawGainedSkillsCondition = function(actor) {
    if (!this._showGainedSkills) return;
    var actorLv = actor._preVictoryLv;
    var bonusExp = 1.0 * actor._expGained * this._tick /
      Yanfly.Param.VAGaugeTicks;
    var nowExp = actor._preVictoryExp - actor.expForLevel(actorLv) + bonusExp;
    var nextExp = actor.expForLevel(actorLv + 1) - actor.expForLevel(actorLv);
    if (actorLv === actor.maxLevel()) {
      return false;
    } else if (nowExp >= nextExp) {
      return true;
    } else {
      return false;
    }
};

Window_VictoryExp.prototype.isReady = function() {
    return this._tick >= Yanfly.Param.VAGaugeTicks;
};

//=============================================================================
// Window_VictoryDrop
//=============================================================================

function Window_VictoryDrop() {
    this.initialize.apply(this, arguments);
}

Window_VictoryDrop.prototype = Object.create(Window_ItemList.prototype);
Window_VictoryDrop.prototype.constructor = Window_VictoryDrop;

Window_VictoryDrop.prototype.initialize = function(titleWindow) {
    var wy = titleWindow.height;
    var ww = Graphics.boxWidth;
    var wh = Graphics.boxHeight - wy;
    Window_ItemList.prototype.initialize.call(this, 0, wy, ww, wh);
    this.openness = 0;
    this.refresh();
};

Window_VictoryDrop.prototype.makeItemList = function() {
    if (BattleManager._rewards.gold > 0) {
      this._data = ['gold', null];
    } else {
      this._data = [];
    }
    this._dropItems = [];
    this._dropWeapons = [];
    this._dropArmors = [];
    this.extractDrops();
};

Window_VictoryDrop.prototype.extractDrops = function() {
    BattleManager._rewards.items.forEach(function(item) {
      if (!item) return;
      if (DataManager.isItem(item)) this._dropItems.push(item.id);
      if (DataManager.isWeapon(item)) this._dropWeapons.push(item.id);
      if (DataManager.isArmor(item)) this._dropArmors.push(item.id);
    }, this);
    this._dropItems.sort(function(a, b){return a-b});
    this._dropWeapons.sort(function(a, b){return a-b});
    this._dropArmors.sort(function(a, b){return a-b});
    this._dropItems.forEach(function(id) {
      var item = $dataItems[id];
      if (item && !this._data.contains(item)) this._data.push(item);
    }, this);
    this._dropWeapons.forEach(function(id) {
      var item = $dataWeapons[id];
      if (item && !this._data.contains(item)) this._data.push(item);
    }, this);
    this._dropArmors.forEach(function(id) {
      var item = $dataArmors[id];
      if (item && !this._data.contains(item)) this._data.push(item);
    }, this);
};

Window_VictoryDrop.prototype.drawItem = function(index) {
    var item = this._data[index];
    if (!item) return;
    this.drawGold(item, index);
    this.drawDrop(item, index);
};

Window_VictoryDrop.prototype.drawGold = function(item, index) {
    if (item !== 'gold') return;
    var rect = this.itemRect(index);
    rect.width -= this.textPadding();
    var value = BattleManager._rewards.gold;
    var currency = TextManager.currencyUnit;
    this.drawCurrencyValue(value, currency, rect.x, rect.y, rect.width);
};

Window_VictoryDrop.prototype.drawDrop = function(item, index) {
    if (!DataManager.isItem(item) && !DataManager.isWeapon(item) &&
    !DataManager.isArmor(item)) return;
    var rect = this.itemRect(index);
    rect.width -= this.textPadding();
    this.drawItemName(item, rect.x, rect.y, rect.width);
    this.drawItemNumber(item, rect.x, rect.y, rect.width);
};

Window_VictoryDrop.prototype.drawItemNumber = function(item, x, y, width) {
    if (!this.needsNumber()) return;
    var numItems = Yanfly.Util.toGroup(this.numItems(item));
    var size = Yanfly.Param.ItemQuantitySize || 28;
    this.contents.fontSize = size;
    this.drawText('\u00d7' + numItems, x, y, width, 'right');
    this.resetFontSettings();
};

Window_VictoryDrop.prototype.numItems = function(item) {
    if (DataManager.isItem(item)) {
      return Yanfly.Util.getCount(item.id, this._dropItems);
    }
    if (DataManager.isWeapon(item)) {
      return Yanfly.Util.getCount(item.id, this._dropWeapons);
    }
    if (DataManager.isArmor(item)) {
      return Yanfly.Util.getCount(item.id, this._dropArmors);
    }
  return 0;
};

//=============================================================================
// Scene_Battle
//=============================================================================

Yanfly.VA.Scene_Battle_update = Scene_Battle.prototype.update;
Scene_Battle.prototype.update = function() {
    Yanfly.VA.Scene_Battle_update.call(this);
    this.updateVictoryAftermath();
};

Scene_Battle.prototype.processNextVictoryStep = function() {
    var step = this._victorySteps.shift();
    if (step) {
      this.processVictoryStep(step.toUpperCase());
    } else {
      this.processVictoryFinish();
    }
};

Scene_Battle.prototype.processVictoryStep = function(step) {
    this._victoryStep = step;
};

Scene_Battle.prototype.processVictoryFinish = function() {
    this._victoryTitleWindow.close();
    BattleManager.processVictoryFinish();
};

Scene_Battle.prototype.isVictoryStep = function(value) {
    return this._victoryStep && this._victoryStep === value;
};

Scene_Battle.prototype.updateVictoryAftermath = function() {
    if (!BattleManager.isVictoryPhase()) return;
    if (!BattleManager.isFinishedVictoryCheer()) {
		return;
	}
    this.activateVictoryStep();
    this.updateVictorySteps();
};

Scene_Battle.prototype.activateVictoryStep = function() {
    if (this._activateVictoryStep) return;
    this._activateVictoryStep = true;
    this.createVictoryTitle();
    this._victorySteps = this.createVictorySteps();
    this.createVictorySteps();
    this.processNextVictoryStep();
};

Scene_Battle.prototype.createVictorySteps = function() {
    var steps = Yanfly.Param.VAOrder.split(' ');
    var array = [];
    for (var i = 0; i < steps.length; ++i) {
      var step = steps[i];
      if (step.toUpperCase() === 'CUSTOM') {
        array = this.addCustomVictorySteps(array);
      } else {
        array.push(step.toUpperCase());
      }
    }
    return array;
};

Scene_Battle.prototype.addCustomVictorySteps = function(array) {
    return array;
};

Scene_Battle.prototype.updateVictorySteps = function() {
  if (this.isVictoryStep('EXP')) this.updateVictoryExp();
  if (this.isVictoryStep('DROPS')) this.updateVictoryDrops();
};

Scene_Battle.prototype.updateVictoryExp = function() {
    if (!this._victoryExpWindow) {
      this.createVictoryExp();
    } else if (this._victoryExpWindow.isReady()) {
      if (this.victoryTriggerContinue()) this.finishVictoryExp();
    }
};

Scene_Battle.prototype.createVictoryTitle = function() {
    this._statusWindow.hide();
    this._logWindow.hide();
    this._victoryTitleWindow = new Window_VictoryTitle();
    this.addWindow(this._victoryTitleWindow);
    this._victoryTitleWindow.open();
};

Scene_Battle.prototype.createVictoryExp = function() {
    this._victoryTitleWindow.refresh(Yanfly.Param.VABattleResults);
    this._victoryExpWindow = new Window_VictoryExp();
    this.addWindow(this._victoryExpWindow);
    this._victoryExpWindow.open();
};

Scene_Battle.prototype.finishVictoryExp = function() {
  SoundManager.playOk();
  this._victoryExpWindow.close();
  this.processNextVictoryStep();
};

Scene_Battle.prototype.updateVictoryDrops = function() {
    if (!this._victoryDropWindow) {
      this.createVictoryDrop();
    } else if (this._victoryDropWindow.isOpen()) {
      if (this.victoryTriggerContinue()) this.finishVictoryDrop();
    }
};

Scene_Battle.prototype.createVictoryDrop = function() {
  this._victoryTitleWindow.refresh(Yanfly.Param.VABattleDrops);
  this._victoryDropWindow = new Window_VictoryDrop(this._victoryTitleWindow);
  this.addWindow(this._victoryDropWindow);
  this._victoryDropWindow.open();
  this._victoryDropWindow.activate();
  this._victoryDropWindow.select(0);
};

Scene_Battle.prototype.finishVictoryDrop = function() {
    SoundManager.playOk();
    this._victoryDropWindow.close();
    this.processNextVictoryStep();
};

Scene_Battle.prototype.victoryTriggerContinue = function() {
    if (Input.isRepeated('ok') || TouchInput.isRepeated()) return true;
    if (Input.isRepeated('cancel')) return true;
    return false;
};

//=============================================================================
// Utilities
//=============================================================================

Yanfly.Util = Yanfly.Util || {};

if (!Yanfly.Util.toGroup) {
    Yanfly.Util.toGroup = function(inVal) {
        return inVal;
    }
};

Yanfly.Util.getCount = function(value, arr){
    var occur = 0;
    for(var i = 0; i < arr.length; i++){
        if (arr[i] === value) occur++;
    }
    return occur;
};

//=============================================================================
// End of File
//=============================================================================