// JavaScript Document//=============================================================================
// BaseCustome.js
//=============================================================================

/*:ja
 * @plugindesc ゲームの基本設定
 * @author 
 *
 * @help 
 */

(function() {

	SceneManager._screenWidth  = SceneManager._boxWidth = 1024;
	SceneManager._screenHeight = SceneManager._boxHeight = 576;
	
	
	var black_window_H_mode=false;//コメント背景「暗くする」の表示変更フラグ
	
	//var $sprite_screenStatus = null;//状態画像表示用
	
	var tile_size=32;
	var font_size = 22;//defo 28
	
	Custom_SceneManager_run = SceneManager.run;
	SceneManager.run = function(sceneClass) {
		Custom_SceneManager_run.call(this, sceneClass);
		if (Utils.isMobileDevice()) return;
		if (Utils.isMobileSafari()) return;
		if (Utils.isAndroidChrome()) return;
		var resizeWidth = Graphics.boxWidth - window.innerWidth;
		var resizeHeight = Graphics.boxHeight - window.innerHeight;
		window.moveBy(-1 * resizeWidth / 2, -1 * resizeHeight / 2);
		window.resizeBy(resizeWidth, resizeHeight);
	};


//****システム拡張
	//スイッチタイトルの取得
	Game_Switches.prototype.name = function(dataId) {
		return $dataSystem.switches[dataId] || '';
	};
	//変数タイトルの取得
	Game_Variables.prototype.name = function(dataId) {
		return $dataSystem.variables[dataId] || '';
	};

//***メッセージウインドウの幅
	Window_Message.prototype.windowWidth = function() {
		if(!black_window_H_mode){
			return 695;//←フォントサイズ変更後のデフォルトの入力欄合わせ　Math.round(Graphics.boxWidth*0.8);
		}else{
			return 	Graphics.boxWidth;
		}
	};
	
	//メッセージ ｘ方向配置調整
	var _Window_Message_prototype_updatePlacement = Window_Message.prototype.updatePlacement;
	Window_Message.prototype.updatePlacement = function() {
		_Window_Message_prototype_updatePlacement.call(this);
		
		this.x = (Graphics.boxWidth - this.windowWidth()) / 2;
		this.contents.smooth = true; //smooth追加
		this.contents.resize(this.windowWidth(),this.contents.height);
		
	};
	
	var _Window_Message_prototype_newLineX = Window_Message.prototype.newLineX;
	Window_Message.prototype.newLineX = function() {
		
		if(!black_window_H_mode){
			return _Window_Message_prototype_newLineX.call(this);
		}else{
			//Hシーンでのテキスト位置調整
			var shift_X = _Window_Message_prototype_newLineX.call(this);	
			shift_X += 165;//文字右寄せ
			return shift_X;
		}
	};
	
	//HシーンテキストのY方向 開始位置の調整
	var _Window_Message_prototype_newPage = Window_Message.prototype.newPage
	Window_Message.prototype.newPage = function(textState) {
		_Window_Message_prototype_newPage.call(this,textState);	
		
		if(black_window_H_mode){
			var lines = textState.text.slice(textState.index).split('\n');
			textState.y = (4 - lines.length) *  textState.height;
			//console.log(textState.y);	
		}
	};
	
	Window_Message.prototype.drawIcon = function(iconIndex, x, y) {
		var bitmap = ImageManager.loadSystem('IconSet');
		var pw = Window_Base._iconWidth;
		var ph = Window_Base._iconHeight;
		var sx = iconIndex % 16 * pw;
		var sy = Math.floor(iconIndex / 16) * ph;
		this.contents.blt(bitmap, sx, sy, pw, ph, x+1, y, pw * 0.85 ,ph * 0.85);
	};

//***マップチップのサイズを変更
	Game_Map.prototype.tileWidth = function() {
		return tile_size;
	};
	Game_Map.prototype.tileHeight = function() {
		return tile_size;
	};
	Game_Vehicle.prototype.maxAltitude = function() {
		return tile_size;
	};
	ImageManager.loadTileset = function(filename, hue) {
		return this.loadBitmap("img/tilesets32/", filename, hue, false);
	};
	
//***フォントサイズ変更
	Window_Base.prototype.lineHeight = function() {
		return font_size/4*6;
	};
	Window_Base.prototype.standardFontSize = function() {
		return font_size;
	};
	Window_Base.prototype.standardPadding = function() {
		return Math.round(font_size/4) * 3;
	};
	
	Window_Base.prototype.textPadding = function() {
		return Math.round(font_size/4);
	};
	
	Window_Base.prototype.calcTextHeight = function(textState, all) {
		var lastFontSize = this.contents.fontSize;
		var textHeight = 0;
		var lines = textState.text.slice(textState.index).split('\n');
		var maxLines = all ? lines.length : 1;
	
		for (var i = 0; i < maxLines; i++) {
			var maxFontSize = this.contents.fontSize;
			var regExp = /\x1b[\{\}]/g;
			for (;;) {
				var array = regExp.exec(lines[i]);
				if (array) {
					if (array[0] === '\x1b{') {
						this.makeFontBigger();
					}
					if (array[0] === '\x1b}') {
						this.makeFontSmaller();
					}
					if (maxFontSize < this.contents.fontSize) {
						maxFontSize = this.contents.fontSize;
					}
				} else {
					break;
				}
			}
			
			textHeight += Math.round(maxFontSize/4) * 5.5;
			
		}
	
		this.contents.fontSize = lastFontSize;
		return textHeight;
	};
	
//画面サイズ変更への対応
	//**** タイトル画面
	Custom_Scene_Title_start = Scene_Title.prototype.start;
	Scene_Title.prototype.start = function() {
		Custom_Scene_Title_start.call(this);
		
		this.rescaleTitleSprite(this._backSprite1);
		this.rescaleTitleSprite(this._backSprite2);
	};	
	Scene_Title.prototype.rescaleTitleSprite = function(sprite) {
		if (sprite.bitmap.width <= 0 || sprite.bitmap <= 0) return;
		var width = Graphics.boxWidth;
		var height = Graphics.boxHeight;
		var ratioX = width / sprite.bitmap.width;
		var ratioY = height / sprite.bitmap.height;
		if (ratioX > 1.0) sprite.scale.x = ratioX;
		if (ratioY > 1.0) sprite.scale.y = ratioY;
		this.centerSprite(sprite);
	};

	//**** ゲームオーバー画面
	Custom_Scene_Gameover_start = Scene_Gameover.prototype.start;
	Scene_Gameover.prototype.start = function() {
		Custom_Scene_Gameover_start.call(this);
		
		this.rescaleImageSprite(this._backSprite);
	};

	Scene_Gameover.prototype.rescaleImageSprite = function(sprite) {
		if (sprite.bitmap.width <= 0 || sprite.bitmap <= 0) return;
		var width = Graphics.boxWidth;
		var height = Graphics.boxHeight;
		var ratioX = width / sprite.bitmap.width;
		var ratioY = height / sprite.bitmap.height;
		if (ratioX > 1.0) sprite.scale.x = ratioX;
		if (ratioY > 1.0) sprite.scale.y = ratioY;
		
		sprite.x = Graphics.width / 2;
		sprite.y = Graphics.height / 2;
		sprite.anchor.x = 0.5;
		sprite.anchor.y = 0.5;
	};

//***** コンフィグ
	var _ConfigManagerApplyData = ConfigManager.applyData;
    ConfigManager.applyData     = function(config) {
        _ConfigManagerApplyData.apply(this, arguments);
		
		if (config.alwaysDash == null){
        	this.alwaysDash = true;//常時ダッシュ
			this.commandRemember = false;//コマンド記憶
		}
    };

//*****マップ名描画
	var _Window_MapName_prototype_open = Window_MapName.prototype.open;
	Window_MapName.prototype.open = function() {
		switch($gameMap.mapId()){
		case 1://全体マップではマップ名を表示しない
			break;
		default:
			if(!$gameSwitches.value(3)){//イベント実行中以外なら表示
				_Window_MapName_prototype_open.call(this);
			}
			break;
		};
	};
	//Window_MapName.prototype.close = function() {};
	
//***** レベルアップ時
	var _Game_Actor_prototype_levelUp=Game_Actor.prototype.levelUp;
	Game_Actor.prototype.levelUp = function() {
		_Game_Actor_prototype_levelUp.call(this);
		
		//$gameVariables.setValue(2,this._level);//現在のレベルを変数へ格納する
		
		$gameActors.actor(this._actorId).recoverAll();//全回復
	};

//***** config に共通セーブ commonSaveを追加
	//ConfigManager.commonSave  = null;//共通セーブデータ
	
	var _ConfigManager_makeData_to_common=ConfigManager.makeData;
	ConfigManager.makeData = function() {
		var config=_ConfigManager_makeData_to_common.call(this);
		
		config.openedEven = this.openedEvent.join('_');
		return config;
	};
	var _ConfigManager_applyData_to_common=ConfigManager.applyData;
	ConfigManager.applyData = function(config) {
		_ConfigManager_applyData_to_common.call(this,config);
		
		if(config.openedEven){
			this.openedEvent = config.openedEven.split("_");
		}else{
			this.openedEvent = [];
		}
	};
	
	ConfigManager.isActiveRecollect = function() {
		if(this.openedEvent && this.openedEvent.length > 0){
			return true;	
		}
		return false;
	};
	
		
	ConfigManager.setEventOpenFlg =function (number,flg_bool){
		if (number > 0) {
			var index = this.openedEvent.indexOf(String(number));
			
			if(flg_bool){
				if(index < 0){
					this.openedEvent.push(number);
				}
			}else{
				if(index >= 0){
					this.openedEvent.splice(index, 1); 
				}
			}
        	this.save();
        }
	};
	
	//イベント開放済みフラグをゲームデータのスイッチと同期させる
	ConfigManager.syncOpenedEvent=function(){
		this.openedEvent.forEach(function(val){
			$gameSwitches._data[val] = val;	
		});
	};
	
	
//***** ニューゲーム時の処理
	var _Scene_Title_prototype_commandNewGame=Scene_Title.prototype.commandNewGame;	
	Scene_Title.prototype.commandNewGame=function(){
		_Scene_Title_prototype_commandNewGame.call(this);
		
		ConfigManager.syncOpenedEvent();//イベント既読フラグをスイッチに同期させる
		
		//エッチカウンター系変数の初期化
		//これをやっておかないとゲームを途中再起動しない限りインクリメントが正常動作しない
		//_data ではなく setValueを使わないと変数自体が生成されないっぽい
		$gameVariables.setValue(16,0);
		$gameVariables.setValue(17,0);
		$gameVariables.setValue(18,0);
		$gameVariables.setValue(19,0);
		//$sprite_screenStatus = new Sprite_ScreenStatus;
	};
	
//***** ロード時の処理
	var _Scene_Load_prototype_onSavefileOk=Scene_Load.prototype.onSavefileOk;
	Scene_Load.prototype.onSavefileOk = function() {
		_Scene_Load_prototype_onSavefileOk.call(this);
		
		ConfigManager.syncOpenedEvent();//イベント既読フラグをスイッチに同期させる
		
		//$sprite_screenStatus = new Sprite_ScreenStatus;
	};
	
//*****  ウィンドウ背景の「暗くする」背景描画の調整
	var _Window_Base_prototype_refreshDimmerBitmap=Window_Base.prototype.refreshDimmerBitmap;
	Window_Base.prototype.refreshDimmerBitmap = function() {
		if (this._dimmerSprite) {
			if(black_window_H_mode){
				//上から下のグラデーション
				var bitmap = this._dimmerSprite.bitmap;
				var w = Graphics.boxWidth; //横幅いっぱい
				var h = this.height;
				var c1 = 'rgba(0, 0, 0, 0.8)';//this.dimColor1();
				var c2 = this.dimColor2();

				bitmap.resize(w, h);
				bitmap.gradientFillRect(0, 0, w, h, c2, c1, true);
				
				this._dimmerSprite.setFrame(0, 0, w, h);
			}else{
				//通常の描画
				var bitmap = this._dimmerSprite.bitmap;
				var w = this.width;
				var h = this.height;
				var m = this.padding;
				var c1 = this.dimColor1();
				var c2 = this.dimColor2();
				bitmap.resize(w, h);
				/*
				bitmap.gradientFillRect(0, 0, w, m, c2, c1, true);
				bitmap.fillRect(0, m, w, h - m * 2, c1);
				bitmap.gradientFillRect(0, h - m, w, m, c1, c2, true);
				bitmap.gradientFillRect(0, 0, m, h, c2, c1, false);
				*/
				
				bitmap.gradientFillRect(0, 0, w, m, c2, c1, true);
				bitmap.fillRect(m, m, w - m * 2, h - m * 2, c1);
				bitmap.gradientFillRect(0, h - m, w, m, c1, c2, true);
				bitmap.gradientFillRect(0, 0, m, h, c2, c1, false);
				bitmap.gradientFillRect(w-m, 0, m, h, c1, c2, false);
				this._dimmerSprite.setFrame(0, 0, w, h);
			}
		}
	};


	
//***** アイテムの上限値
	Game_Party.prototype.maxItems = function(item) {
    	return 15;
	};

//***** セーブデータの拡張
	var _DataManager_makeSavefileInfo = DataManager.makeSavefileInfo;
    DataManager.makeSavefileInfo      = function() {
        var info            = _DataManager_makeSavefileInfo.call(this);
		info.globalId       ="prigo";
        info.mapname        = $gameMap.displayName();
        info.gold           = $gameParty._gold;
		info.eroLevel       = $gameVariables.value(14);//ゲーム内でイベント発生時にせっと設定
        return info;
    };
	Game_Party.prototype.charactersForSavefile = function() {
        return this.battleMembers().map(function(actor) {
            return {
                0      : actor.characterName(),
                1      : actor.characterIndex(),
                'name' : actor._name,
                'id'   : actor._actorId,
                'level': actor._level,
                'HP'   : actor._hp,
                'MP'   : actor._mp,
                'MHP'  : actor.param(0),
                'MMP'  : actor.param(1)
            };
        });
    };
	
	//リスト内容描画
	Window_SavefileList.prototype.drawFileId = function(id, x, y) {
		this.drawText(TextManager.file + ' ' + id, x, y + 4, 180);
	};

	Window_SavefileList.prototype.drawContents = function(info, rect, valid) {
		var bottom = rect.y + rect.height;

		if (valid) {
			var line_y = rect.y + 4;
			this.drawGameTitle(info, rect.x + 80, line_y, rect.width - 192);
			
			var char = info.characters[0];
			
			//レベル描画
			this.drawText(' Lv', rect.x + 450, line_y);
			this.drawText(char.level, rect.x + 485, line_y , 25 ,'right');
			//所持金描画
			this.drawText(info.gold+' G' , rect.x + 500,line_y ,170,'right');
			
			//状態描画
			if(info.eroLevel){
				var text="";
				switch(info.eroLevel){
				case 1:
					text = "Sexually Liberal status";
					break;
				case 2:
					text = "Perverted status";
					break;
				case 3:
					text = "Prostitute status";
					break;
				}
				this.drawText(text , rect.x + 690,line_y ,180,'center');
			}
			
			this.drawPlaytime(info, rect.x, line_y, rect.width);
		}

	};
	//セーブファイルのゲームタイトルをマップ名に変更
	Window_SavefileList.prototype.drawGameTitle = function(info, x, y, width) {
		if (info.title) {
			this.drawText(info.mapname, x, y, width);
		}
	};
	Window_SavefileList.prototype.maxVisibleItems = function() {
		return 10;
	};


//武器防具の購入制限
	//アイテム以外は１個しか購入出来ないように制限
	Scene_Shop.prototype.onBuyOk = function() {
		this._item = this._buyWindow.item();
		this._buyWindow.hide();
		if($dataItems.contains(this._item)){
			this._numberWindow.setup(this._item, this.maxBuy(), this.buyingPrice());
		}else{
			//変更箇所
			this._numberWindow.setup(this._item, 1, this.buyingPrice());	
		}
		this._numberWindow.setCurrencyUnit(this.currencyUnit());
		this._numberWindow.show();
		this._numberWindow.activate();
	};
	
	Window_ShopBuy.prototype.isEnabled = function(item) {
		return (item && this.price(item) <= this._money &&
				!$gameParty.hasMaxItems(item) && this.inStock(item));
	};
	//販売アイテムが装備中か所持しているなら無効化
	Window_ShopBuy.prototype.inStock = function(item) {
		if(!$dataItems.contains(item)){
			var actor = $gameActors.actor(1);
			if(actor){
			  if(actor.hasArmor(item) || actor.hasWeapon(item) || $gameParty.hasItem(item)){
				 return false;
			  }
			}
		}
		return true;
		
	};
	
	//装備中表示の追加
	Window_ShopStatus.prototype.drawActorParamChange = function(x, y, actor, item1) {
		var width = this.contents.width - this.textPadding() - x;
		var paramId = this.paramId();
		var change = this._item.params[paramId] - (item1 ? item1.params[paramId] : 0);
		
		this.changeTextColor(this.paramchangeTextColor(change));
		
		if(item1 && this._item.id == item1.id){
			this.drawText("装備中", x, y, width, 'right');
		}else{
			this.drawText((change > 0 ? '+' : '') + change, x, y, width, 'right');
		}
	};


//***** スクリーンステータス表示 娼婦ライセンス
	/*
	var _Spriteset_Base_prototype_createUpperLayer=Spriteset_Base.prototype.createUpperLayer;
	Spriteset_Base.prototype.createUpperLayer = function() {
		_Spriteset_Base_prototype_createUpperLayer.call(this);
		
		if(!$gameSwitches.value(4)){
			this.addChild($sprite_screenStatus);
		}
	};
	
	function Sprite_ScreenStatus() {
		this.initialize.apply(this, arguments);
	}
	
	Sprite_ScreenStatus.prototype = Object.create(Sprite.prototype);
	Sprite_ScreenStatus.prototype.constructor = Sprite_ScreenStatus;
	
	Sprite_ScreenStatus.prototype.initialize = function() {
		Sprite.prototype.initialize.call(this);
		
		this._picID=96;
		this.x=Graphics.width - 80;
		this.y=10;
		
		this._active=false;//表示中フラグ
		this.update();
	};
	
	
	Sprite_ScreenStatus.prototype.update = function() {
		Sprite.prototype.update.call(this);
		
		this.visible = this.isStatusView();
		
		if(this.visible && !this._active){
			this.redraw();
			this._active=true;//表示中フラグ
		}
		
		if(!this.visible && this._active){
			$gameScreen.erasePicture(this._picID);
			this._active = false;
		}	
	};
	
	Sprite_ScreenStatus.prototype.redraw = function() {
		//ベース表示
		$gameScreen.showPicture(this._picID,"syofu_jyotai",0,this.x,this.y,100,100,255,0);
	};
	
	Sprite_ScreenStatus.prototype.isStatusView = function(){
		//イベント実行中
		if($gameSwitches.value(3)){
			return false; 
		}
		
		//ライセンス装備中
		if($gameActors.actor(1).hasArmor($dataArmors[60])){
			return true; 
		}
		return false;
	};
	*/

//***** プラグインコマンド	
	var _Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand;
	Game_Interpreter.prototype.pluginCommand = function(command, args) {
		_Game_Interpreter_pluginCommand.call(this, command, args);
		switch (command) {
		case 'EventOpen':
			if(args[0] > 0){
				var id   = Number(args[0]);
				var bool = true;
				if(args[1] == 'false'){
					bool = false;
				}
				
				$gameSwitches._data[id] = bool;	
				ConfigManager.setEventOpenFlg(id,bool);	
			}
			break;
		case 'WindowMode':
			if(args[0] == 'H'){
				black_window_H_mode = true;
			}else{
				black_window_H_mode = false;
			}
			break;
		}
	};
	
	
})();


