var x;
var y;
var maxLvl=1;
var test=0;
var indexTuto=0;
var skip=false;
var allowUndo=true;

Game_Event.prototype.findProperPageIndex = function() {
	if(this.event()===undefined)return -1;
    var pages = this.event().pages;
    for (var i = pages.length - 1; i >= 0; i--) {
        var page = pages[i];
        if (this.meetsConditions(page)) {
            return i;
        }
    }
    return -1;
};

Window_Options.prototype.processCancel = function() {
    SoundManager.playCancel();
    this.updateInputData();
    SceneManager.goto(Scene_Menu);
    //this.deactivate();
    //this.callCancelHandler();
};

Window_Options.prototype.changeValue = function(symbol, value) {
    var lastValue = this.getConfigValue(symbol);
    test=value;
    if (lastValue !== value) {
        this.setConfigValue(symbol, value);
        this.redrawItem(this.findSymbol(symbol));
        SoundManager.playCursor();
        if(symbol==='window')Graphics._switchFullScreen();
        if(symbol==='skip'&&value===true)skip=true;
        if(symbol==='skip'&&value===false)skip=false;
    }
};

Window_Options.prototype.addGeneralOptions = function() {
    // this.addCommand(TextManager.alwaysDash, 'alwaysDash');
    // this.addCommand(TextManager.commandRemember, 'commandRemember');
    var langue = $gameVariables.value(3);
    this.addCommand((langue===1)?'Window Mode':'Mode Fenêtre', 'window');
    this.addCommand((langue===1)?'Skip scenes':'Passer scenes', 'skip');
};

Window_Options.prototype.addVolumeOptions = function() {
    var langue = $gameVariables.value(3);
    this.addCommand((langue===1)?'Music Volume':'Volume Musique', 'bgmVolume');
    // this.addCommand(TextManager.bgsVolume, 'bgsVolume');
    // this.addCommand(TextManager.meVolume, 'meVolume');
    this.addCommand((langue===1)?'Sound Effect Volume':'Volume Effet Sonore', 'seVolume');
};

Window_Options.prototype.volumeOffset = function() {
    return 10;
};

Window_ScrollText.prototype.isFastForward = function() {
    if ($gameMessage.scrollNoFast()) {
        return false;
    } else {
        // return (Input.isPressed('ok') || Input.isPressed('shift') ||
        //         TouchInput.isPressed());
		return false;
    }
};

Scene_Gameover.prototype.isTriggered = function() {
    // return Input.isTriggered('ok') || TouchInput.isTriggered();
    return false;
};

Window_Message.prototype.updateShowFast = function() {
    if (this.isTriggered()) {
        this._showFast = false;
    }
};

var loadVariables;
Scene_Boot.prototype.start = function() {
    Scene_Base.prototype.start.call(this);
    SoundManager.preloadImportantSounds();
    if (DataManager.isBattleTest()) {
        DataManager.setupBattleTest();
        SceneManager.goto(Scene_Battle);
    } else if (DataManager.isEventTest()) {
        DataManager.setupEventTest();
        SceneManager.goto(Scene_Map);
    } else {
        this.checkPlayerLocation();
        DataManager.setupNewGame();
        SceneManager.goto(Scene_Map);
        if(StorageManager.load(1)==="")DataManager.saveGame(1);
        var loadVariables = JsonEx.parse(StorageManager.load(1)).variables;
        $gameVariables.setValue(2,loadVariables.value(2));
        $gameVariables.setValue(3,loadVariables.value(3));
    }
    this.updateDocumentTitle();
    Scene_Menu=Scene_GameEnd;
    createGameEnd();
    Graphics._switchFullScreen();
};

DataManager.loadMapData = function(mapId) {
    if (mapId > 0) {
        var filename = 'Map%1.json'.format(mapId.padZero(3));
        if($gameMap.mapId()!==mapId){this.loadDataFile('$dataMap', filename);}
    } else {
        this.makeEmptyMap();
    }
};

Game_Player.prototype.isMapPassable = function(x, y, d, l) {
    var new_x = $gameMap.roundXWithDirection(x, d);
     var new_y = $gameMap.roundYWithDirection(y, d);
 if(l===undefined)l=playerChar.lvl;
 return cMyPassibility(new_x,new_y,l,d);};

Scene_GameEnd.prototype.retry = function() {
	SceneManager.pop();
	setRetry();
};

Scene_GameEnd.prototype.changeLanguage = function() {
	SceneManager.pop();
	$gameTemp.reserveCommonEvent(14);
};

Scene_GameEnd.prototype.displaySettings = function() {
    SceneManager.goto(Scene_Options);
};

Scene_GameEnd.prototype.displayControls = function() {
    SceneManager.pop();
    $gameTemp.reserveCommonEvent(33);
};

var testIndex=0;

var createGameTitle=function(){
	var langue = $gameVariables.value(3);
Window_GameEnd.prototype.makeCommandList = function() {
	if($gameVariables.value(2)>1)this.addCommand((langue===1)?'Continue':'Continuer', 'continue');
    this.addCommand((langue===1)?'New Game':'Nouvelle Partie',  'newGame');
    this.addCommand((langue===1)?'Level selection':'Choix du niveau',  'level');
    this.addCommand((langue===1)?'Settings':'Options',  'settings');
    this.addCommand((langue===1)?'Credits':'Credits',  'credits')
    this.addCommand((langue===1)?'Quit':'Quitter',  'quit');
};

Window_GameEnd.prototype.updatePlacement = function() {
    this.x = (Graphics.boxWidth - this.width) / 2;
    this.y = Graphics.boxHeight - this.height - 96;
};

Scene_GameEnd.prototype.createCommandWindow = function() {
    this._commandWindow = new Window_GameEnd();
    this._commandWindow.setHandler('newGame',  this.newGame.bind(this));
    this._commandWindow.setHandler('continue',   this.continuer.bind(this));
    this._commandWindow.setHandler('level',   this.selectLvl.bind(this));
    this._commandWindow.setHandler('settings',   this.displaySettings.bind(this));
    this._commandWindow.setHandler('credits',   this.credits.bind(this));
    this._commandWindow.setHandler('quit',   function(){window.close()}.bind(this));
    this.addWindow(this._commandWindow);
};

Scene_GameEnd.prototype.newGame=function()
{
	this._commandWindow.close();
/*	$gameVariables.setValue(2,0);
	DataManager.saveGame(1);
	wallDown.cActive=false;
	retry=false;
	$gameTemp.reserveCommonEvent(3);
	$gamePlayer.reserveTransfer(mapOrder[1], 0, 0, 0, 0);*/
	SceneManager.goto(Scene_Map);
    $gameTemp.reserveCommonEvent(31);
};

Scene_GameEnd.prototype.credits=function()
{
    this._commandWindow.close();
    SceneManager.goto(Scene_Map);
    $gameTemp.reserveCommonEvent(32);
};


Scene_GameEnd.prototype.continuer=function()
{
	this._commandWindow.close();
	//$gameVariables.setValue(2,0);
	//DataManager.saveGame(1);
	wallDown.cActive=false;
	retry=false;
	$gameTemp.reserveCommonEvent(3);
	$gamePlayer.reserveTransfer(mapOrder[$gameVariables.value(2)], 0, 0, 0, 0);
	SceneManager.goto(Scene_Map);
};

Scene_GameEnd.prototype.selectLvl=function()
{
	this._commandWindow.close();
	//$gameVariables.setValue(2,0);
	//DataManager.saveGame(1);
	wallDown.cActive=false;
	retry=false;
	$gameTemp.reserveCommonEvent(3);
	$gamePlayer.reserveTransfer(6);
	SceneManager.goto(Scene_Map);
};

Window_GameEnd.prototype.maxCols = function() {
    return 1;
};
/*
Window_GameEnd.prototype.processCancel = function() {
    SoundManager.playCancel();
    this.updateInputData();
    this.deactivate();
    this.callCancelHandler();
};
*/
Window_GameEnd.prototype.updateBackOpacity = function() {
    this.backOpacity = this.standardBackOpacity();
};

Window_GameEnd.prototype.windowHeight = function() {
    return this.fittingHeight(this.numVisibleRows());
};

Window_GameEnd.prototype.windowWidth = function() {
    return 240;
};

Window_GameEnd.prototype.itemTextAlign = function() {
    return 'left';
};

Window_GameEnd.prototype.itemWidth = function() {
    return Math.floor((this.width - this.padding * 2 +
                       this.spacing()) / this.maxCols() - this.spacing());
};

Window_GameEnd.prototype.itemHeight = function() {
    return this.lineHeight();
};

Scene_GameEnd.prototype.update = function() {
    this.updateFade();
    this.updateChildren();
    AudioManager.checkErrors();
};
};

var createGameEnd=function(){
	var langue = $gameVariables.value(3);
Window_GameEnd.prototype.makeCommandList = function() {
    this.addCommand((langue===1)?'Undo last move':'Défaire',  'undo');
    this.addCommand((langue===1)?'Retry':TextManager.retry,  'retry');
    this.addCommand((langue===1)?'To Title':TextManager.toTitle, 'toTitle');
    this.addCommand((langue===1)?'Change Language':'Changuer la langue',  'language');
    this.addCommand((langue===1)?'Controls':'Contrôles',  'controls');
    this.addCommand((langue===1)?'Settings':'Réglages',  'settings');
    // this.addCommand((langue===1)?'Cancel':TextManager.cancel,  'cancel');
};

Scene_GameEnd.prototype.createCommandWindow = function() {
    this._commandWindow = new Window_GameEnd();
    this._commandWindow.setHandler('toTitle',  this.commandToTitle.bind(this));
    this._commandWindow.setHandler('cancel',   this.popScene.bind(this));
    this._commandWindow.setHandler('retry',   this.retry.bind(this));
    this._commandWindow.setHandler('language',   this.changeLanguage.bind(this));
    this._commandWindow.setHandler('settings',   this.displaySettings.bind(this));
    this._commandWindow.setHandler('controls',   this.displayControls.bind(this));
    this._commandWindow.setHandler('undo',   localLoad.bind(this));
    this.addWindow(this._commandWindow);
};

Window_GameEnd.prototype.maxCols = function() {
    return 1;
};

Window_GameEnd.prototype.updatePlacement = function() {
    this.x = (Graphics.boxWidth - this.width) / 2;
    this.y = (Graphics.boxHeight - this.height) / 2;
};

Window_GameEnd.prototype.processCancel = function() {
    SoundManager.playCancel();
    this.updateInputData();
    this.deactivate();
    this.callCancelHandler();
};

Window_GameEnd.prototype.updateBackOpacity = function() {
    this.backOpacity = this.standardBackOpacity();
};

Window_GameEnd.prototype.windowHeight = function() {
    return this.fittingHeight(this.numVisibleRows());
};

Window_GameEnd.prototype.windowWidth = function() {
    return 240;
};

Window_GameEnd.prototype.itemTextAlign = function() {
    return 'left';
};

Window_GameEnd.prototype.itemWidth = function() {
    return Math.floor((this.width - this.padding * 2 +
                       this.spacing()) / this.maxCols() - this.spacing());
};

Window_GameEnd.prototype.itemHeight = function() {
    return this.lineHeight();
};

Scene_GameEnd.prototype.update = function() {
    this.updateFade();
    this.updateChildren();
    AudioManager.checkErrors();
};
};

SceneManager.snapForBackground = function() {
    this._backgroundBitmap = this.snap();
//    this._backgroundBitmap.blur();
};

var createLvlSelection = function() {
Window_GameEnd.prototype.updateBackOpacity = function() {
 this.backOpacity = 0;
};

Scene_GameEnd.prototype.update = function() {
    this.updateFade();
    this.updateChildren();
    AudioManager.checkErrors();
    if(Input.isPressed('cancel'))location.reload();
};


Window_GameEnd.prototype.updatePlacement = function() {
    this.x = (Graphics.boxWidth - this.width) / 2;
    this.y = (Graphics.boxHeight - this.height) / 2;
};

Window_GameEnd.prototype.standardPadding = function() {
    return 9;
};

Window_GameEnd.prototype.windowWidth = function() {
    return 1106;
};

Window_GameEnd.prototype.windowHeight = function() {
    return 560;
};

Window_GameEnd.prototype.itemWidth = function() {
    return 206;
};

Window_GameEnd.prototype.itemHeight = function() {
    return 130;
};

Window_Command.prototype.itemTextAlign = function() {
    return 'center';
};

Window_GameEnd.prototype.maxCols = function() {
    return 5;
};

Window_GameEnd.prototype.makeCommandList = function() {
var maxLvl=Math.max($gameVariables.value(2),1);
	for(var i=1;i<21;i++){
    this.addCommand((i<=maxLvl)?String(i):'?',  String(i));
	};
};

Scene_GameEnd.prototype.createCommandWindow = function() {
   var maxLvl=Math.max($gameVariables.value(2),1);
    this._commandWindow = new Window_GameEnd();
    if(maxLvl>=1)this._commandWindow.setHandler('1',  function(){SceneManager.pop();$gamePlayer.reserveTransfer(mapOrder[1], 0, 0, 0, 0)}.bind(this));
    if(maxLvl>=2)this._commandWindow.setHandler('2',  function(){SceneManager.pop();$gamePlayer.reserveTransfer(mapOrder[2], 0, 0, 0, 0);}.bind(this));
    if(maxLvl>=3)this._commandWindow.setHandler('3',  function(){SceneManager.pop();$gamePlayer.reserveTransfer(mapOrder[3], 0, 0, 0, 0);}.bind(this));
    if(maxLvl>=4)this._commandWindow.setHandler('4',  function(){SceneManager.pop();$gamePlayer.reserveTransfer(mapOrder[4], 0, 0, 0, 0);}.bind(this));
    if(maxLvl>=5)this._commandWindow.setHandler('5',  function(){SceneManager.pop();$gamePlayer.reserveTransfer(mapOrder[5], 0, 0, 0, 0);}.bind(this));
    if(maxLvl>=6)this._commandWindow.setHandler('6',  function(){SceneManager.pop();$gamePlayer.reserveTransfer(mapOrder[6], 0, 0, 0, 0);}.bind(this));
    if(maxLvl>=7)this._commandWindow.setHandler('7',  function(){SceneManager.pop();$gamePlayer.reserveTransfer(mapOrder[7], 0, 0, 0, 0);}.bind(this));
    if(maxLvl>=8)this._commandWindow.setHandler('8',  function(){SceneManager.pop();$gamePlayer.reserveTransfer(mapOrder[8], 0, 0, 0, 0);}.bind(this));
    if(maxLvl>=9)this._commandWindow.setHandler('9',  function(){SceneManager.pop();$gamePlayer.reserveTransfer(mapOrder[9], 0, 0, 0, 0);}.bind(this));
    if(maxLvl>=10)this._commandWindow.setHandler('10',  function(){SceneManager.pop();$gamePlayer.reserveTransfer(mapOrder[10], 0, 0, 0, 0);}.bind(this));
    if(maxLvl>=11)this._commandWindow.setHandler('11',  function(){SceneManager.pop();$gamePlayer.reserveTransfer(mapOrder[11], 0, 0, 0, 0);}.bind(this));
    if(maxLvl>=12)this._commandWindow.setHandler('12',  function(){SceneManager.pop();$gamePlayer.reserveTransfer(mapOrder[12], 0, 0, 0, 0);}.bind(this));
    if(maxLvl>=13)this._commandWindow.setHandler('13',  function(){SceneManager.pop();$gamePlayer.reserveTransfer(mapOrder[13], 0, 0, 0, 0);}.bind(this));
    if(maxLvl>=14)this._commandWindow.setHandler('14',  function(){SceneManager.pop();$gamePlayer.reserveTransfer(mapOrder[14], 0, 0, 0, 0);}.bind(this));
    if(maxLvl>=15)this._commandWindow.setHandler('15',  function(){SceneManager.pop();$gamePlayer.reserveTransfer(mapOrder[15], 0, 0, 0, 0);}.bind(this));
    if(maxLvl>=16)this._commandWindow.setHandler('16',  function(){SceneManager.pop();$gamePlayer.reserveTransfer(mapOrder[16], 0, 0, 0, 0);}.bind(this));
    if(maxLvl>=17)this._commandWindow.setHandler('17',  function(){SceneManager.pop();$gamePlayer.reserveTransfer(mapOrder[18], 0, 0, 0, 0);}.bind(this));
    if(maxLvl>=18)this._commandWindow.setHandler('18',  function(){SceneManager.pop();$gamePlayer.reserveTransfer(mapOrder[19], 0, 0, 0, 0);}.bind(this));
    if(maxLvl>=19)this._commandWindow.setHandler('19',  function(){SceneManager.pop();$gamePlayer.reserveTransfer(mapOrder[20], 0, 0, 0, 0);}.bind(this));
    if(maxLvl>=20)this._commandWindow.setHandler('20',  function(){SceneManager.pop();$gamePlayer.reserveTransfer(mapOrder[21], 0, 0, 0, 0);}.bind(this));
	 this.addWindow(this._commandWindow);
};

Window_GameEnd.prototype.processCancel = function() {
location.reload();
};
};


Scene_GameEnd.prototype.commandToTitle = function() {
     this.fadeOutAll();
     DataManager.setupNewGame();
     loadVariables = JsonEx.parse(StorageManager.load(1)).variables;
     $gameVariables.setValue(2,loadVariables.value(2));
     $gameVariables.setValue(3,loadVariables.value(3));
     SceneManager.goto(Scene_Map);
};

var cMap = {height: 13, width: 23};
var cPxl = 48;
var allowMove=true;
var pilarEvents = [];
var switchEvents = [];
var botEvents = [];
var cTileEvents = [];
var blueSwitch={};
var purpleSwitch={};
var greenSwitch={};
var yellowSwitch={};
var cCountFreeSlot = 0;
var allowSwap = true;
var tileSelection = false;
var tileControl = false;
var cacheTile = {};
var mapOrder=[];
var nbOfChar = 4;
var swapMode=false;
var chrono=0;
var retry=false;
var i=0;
var tempChar1;
var tempChar2;
var tempPilar1;
var eyeMode;
var tilesToReveal=[];
var tileMovingExpress;
var indexOfPilars=[8,9,10,16,17,18,24,25,26,32,33,34];
var indexOfSwitches=[20,21,22,23,44,45,46,47,76,77,78,79];
var indexOfTiles=[141,150,159,173,174,175,189,198,207,221,222,223];
var indexOfRayBlockingTiles=indexOfPilars.concat(indexOfSwitches.concat(indexOfTiles.concat([3])))
var nbOfPilars;
var maxIndexTuto=50;


var tutMaxIndex=function(mapN)
{
    switch(true)
{
    case mapN>=12:
    return 55;
    case mapN>=9:
    return 54;
    case mapN>=4:
    return 53;
    case mapN>=2:
    return 51;
    case mapN>=1:
    return 50;   
};
}

Game_CharacterBase.prototype.canPass = function(x, y, d) {
    var x2 = $gameMap.roundXWithDirection(x, d);
    var y2 = $gameMap.roundYWithDirection(y, d);
    if (!$gameMap.isValid(x2, y2)) {
        return false;
    }
    if (this.isThrough() || this.isDebugThrough()) {
        return true;
    }
    if (!this.isMapPassable(x, y, d)) {
        return false;
    }
   /* if (this.isCollidedWithCharacters(x2, y2)) {
        return false;
    }*/
    return true;
};

var cIconSwitch = 
{
	cImage: 'swap',
	cPos: [48,72],
	cActive: true,
	cImageId: 1
};



var cIconBlueChar = 
{
	cImage: 'perso_bleu',
	cPos: [40,168],
	cActive: true,
	cImageId: 2
};

var cIconPurpleChar = 
{
	cImage: 'perso_violet',
	cPos: [40,264],
	cActive: true,
	cImageId: 3
};

var cIconGreenChar = 
{
	cImage: 'perso_vert',
	cPos: [40,360],
	cActive: true,
	cImageId: 4
};

var cIconYellowChar = 
{
	cImage: 'perso_jaune',
	cPos: [40,456],
	cActive: true,
	cImageId: 5
};

var cIconSetTile = 
{
	cImage: 'column',
	cPos: [1064,72],
	cActive: true,
	cImageId: 6
};

var cIconBlueTile = 
{
	cImage: 'dalle_bleu',
	cPos: [1064,168],
	cActive: false,
	cImageId: 7
};

var cIconPurpleTile = 
{
	cImage: 'dalle_violet',
	cPos: [1056,264],
	cActive: false,
	cImageId: 8
};

var cIconGreenTile = 
{
	cImage: 'dalle_vert',
	cPos: [1056,360],
	cActive: false,
	cImageId: 9
};

var cIconYellowTile = 
{
	cImage: 'dalle_jaune',
	cPos: [1056,456],
	cActive: false,
	cImageId: 10
};

var cIconJump = 
{
	cImage: 'jump',
	cPos: [1064,72],
	cActive: false,
	cImageId: 11
};

var cIconCancel = 
{
	cImage: 'cancel',
	cPos: [1056,72],
	cActive: false,
	cImageId: 12
};

var cIconConfirm = 
{
	cImage: 'ok',
	cPos: [1056,264],
	cActive: false,
	cImageId: 13
};

var cIconUp = 
{
	cImage: 'up',
	cPos: [1064,168],
	cActive: false,
	cImageId: 14
};

var cIconEye1 = 
{
	cImage: 'eye1',
	cPos: [1064,552],
	cActive: false,
	cImageId: 15
};

var cIconEye2 = 
{
    cImage: 'eye2',
    cPos: [1064,552],
    cActive: false,
    cImageId: 16
};

var cIconExchange = 
{
	cImage: 'exchange',
	cPos: [1064,460],
	cActive: true,
	cImageId: 17
};

var cIconSkip = 
{
	cImage: 'skip',
	cPos: [1056,552],
	cActive: false,
	cImageId: 17
};

var wallDown = 
{
	cImage: 'wallDown',
	cPos: [0,0],
	cActive: false,
	cImageId: 18
};

var cIconBlueTile0 = 
{
	cImage: 'dalle_bleu',
	cPos: [1064,168],
	cActive: false,
	cImageId: 19
};

var cIconPurpleTile0 = 
{
	cImage: 'dalle_violet',
	cPos: [1056,264],
	cActive: false,
	cImageId: 20
};

var cIconGreenTile0 = 
{
	cImage: 'dalle_vert',
	cPos: [1056,360],
	cActive: false,
	cImageId: 21
};

var cIconYellowTile0 = 
{
	cImage: 'dalle_jaune',
	cPos: [1056,456],
	cActive: false,
	cImageId: 22
};

var cIconBlueChar0 = 
{
	cImage: 'perso_bleu',
	cPos: [40,168],
	cActive: true,
	cImageId: 23
};

var cIconPurpleChar0 = 
{
	cImage: 'perso_violet',
	cPos: [40,264],
	cActive: true,
	cImageId: 24
};

var cIconGreenChar0 = 
{
	cImage: 'perso_vert',
	cPos: [40,360],
	cActive: true,
	cImageId: 25
};

var cIconYellowChar0 = 
{
	cImage: 'perso_jaune',
	cPos: [40,456],
	cActive: true,
	cImageId: 26
};

var cIconBlueD = 
{
    cImage: 'blueD',
    cPos: [60,128],
    cActive: true,
    cImageId: 27
};

var cIconPurpleD = 
{
    cImage: 'purpleD',
    cPos: [60,224],
    cActive: true,
    cImageId: 28
};

var cIconGreenD = 
{
    cImage: 'greenD',
    cPos: [60,320],
    cActive: true,
    cImageId: 29
};

var cIconYellowD = 
{
    cImage: 'yellowD',
    cPos: [60,416],
    cActive: true,
    cImageId: 30
};



var countElements = function()
{
	nbOfPilars=0;
	for (var i=0;i<cMap.width;i++)
	{
		for(var j=0;j<cMap.height;j++)
		{
			if(indexOfPilars.indexOf($gameMap.tileId(i,j,3))>=0)nbOfPilars++;
		}

	}	
};

var blockEvents=[];
var test_comptage=0;
var localSaveInfos=[];

var localSave=function(exiting)
{
    var i=localSaveInfos.length
    localSaveInfos[i]=[];
    var t=localSaveInfos[i];
    var team=[(tileControl)?playerChar:$gamePlayer,blueChar,purpleChar,greenChar,yellowChar];
    var tiles=[blueTile,purpleTile,greenTile,yellowTile];
    t[0]=[playerChar.name,$gameSwitches.value(6),$gameSwitches.value(7),tileControl,door.open,exiting];
    for(var k=0;k<team.length;k++)
    {
    t.push([team[k].x,team[k].y,team[k].direction(),team[k].lvl,team[k].exit,team[k].isTransparent()]);    
    }
    for(var k=0;k<tiles.length;k++)
    {
    t.push([tiles[k].isSet,tiles[k].lvl,tiles[k].direction(),tiles[k]._priorityType]);    
    }
    for(var k=0; k<allPilars.length; k++)
    {
    var pilar=allPilars[k];
    if(pilar.express)t.push([pilar.direction(),JSON.stringify(pilar._moveRoute),pilar.lvl,pilar._priorityType]);
    if(pilar.trainRight||pilar.trainLeft)t.push([pilar.direction(),JSON.stringify(pilar._moveRoute),pilar.x,pilar.y]);

    }    
};

var localLoad=function()
{
    SceneManager.goto(Scene_Map);
    var i=localSaveInfos.length-1;
    if(i<0||!allowUndo)return;
    var ls = localSaveInfos[i];
    var team=[$gamePlayer,blueChar,purpleChar,greenChar,yellowChar];
    var tiles=[blueTile,purpleTile,greenTile,yellowTile];
    if(nameToChar(ls[0][0]).exit)nameToChar(ls[0][0]).exit=false;
    if(ls[0][5]!==undefined)nameToChar(ls[0][5]).setPosition(11,3);
    swapChar(nameToChar(ls[0][0]));
    $gameSwitches.setValue(6,ls[0][1]);
    $gameSwitches.setValue(7,ls[0][2]);
    door.open=ls[0][4];

    for(var k=0;k<team.length;k++)
    {
    if((k===0&&ls[0][5]!==undefined)||(k>0&&team[k].name===ls[0][5]))
    {
        team[k].setPosition(ls[k+1][0],ls[k+1][1]+1);    
    }else{
        team[k].setPosition(ls[k+1][0],ls[k+1][1]);    
    };
    team[k].setDirection(ls[k+1][2]);
    team[k].lvl=ls[k+1][3];
    team[k].exit=ls[k+1][4];
    team[k].setTransparent(ls[k+1][4]);
    }

    for(var k=0;k<tiles.length;k++)
    {
    if(!ls[k+6][0]&&tiles[k].isSet)
    {
        tiles[k].isSet=false;
        tiles[k].lvl=0;
        cCountFreeSlot++;
        tiles[k].set_frame(tiles[k].image[0],2,3,2);
        tiles[k].setPriorityType(0);
        $dataMap.data[(3*$dataMap.height+tiles[k].y)*$dataMap.width+tiles[k].x]=11;
    }else if(tiles[k].isSet){
        tiles[k].setDirectionFix(false);
        tiles[k].lvl=ls[k+6][1];
        tiles[k].setDirection(ls[k+6][2]);
        tiles[k].setPriorityType(ls[k+6][3]);
        tiles[k].setDirectionFix(true);
    }  
    }
    var j=0;
    for(var k=0;k<allPilars.length;k++)
    {
        var pilar=allPilars[k];
        if(pilar.express)
        {
            pilar.setDirectionFix(false);
            pilar.setDirection(ls[10+j][0]);
            pilar.forceMoveRoute(JSON.parse(ls[10+j][1]));
            pilar.lvl=ls[10+j][2];
            pilar.setPriorityType(ls[10+j][3]);
            j++;
            pilar.setDirectionFix(true);
        }
        if(pilar.trainRight||pilar.trainLeft)
        {
            pilar.setPosition(ls[10+j][2],ls[10+j][3]);
            pilar.forceMoveRoute(JSON.parse(ls[10+j][1]));
            j++;         
        }

    }
    localSaveInfos.splice(i,1);
};

var createEvents=function()
{
	test_comptage++;
	var pilarId = cGetId('pilier');
	var blockId = cGetId('block');
	var cacheId = cGetId('cache');
	var blueCharId = cGetId('blue');
	var purpleCharId = cGetId('purple');
	var greenCharId = cGetId('green');
	var yellowCharId = cGetId('yellow');
	var switchId = cGetId('switch');
	var j=0;
	$gameMap.event(pilarId).blocking=false;
	var copyEv = function(id)
	{
		for(var k=0; k<id.length; k++)
		{
		if(id[k]===undefined)continue;
		$dataMap.events.push(JSON.parse(JSON.stringify($dataMap.events[id[k]])));
		$dataMap.events[$dataMap.events.length-1].id=$dataMap.events.length-1;
		$gameMap._events[$dataMap.events.length-1] = new Game_Event($gameMap.mapId(), $dataMap.events.length-1);
		}
	};
	var eraseEv = function(id)
	{
		for(var k=0; k<id.length; k++)
		{
		if(id[k]===undefined)continue;
		$dataMap.events[id[k]]=null;
		$gameMap._events[id[k]]=undefined;
		}
	};
	var l=0;
	while(l<nbOfPilars)
	{
		copyEv([pilarId]);
		pilarEvents.push($gameMap._events[$gameMap._events.length-1]);
		l++;
	};
	if(mapNumber>10)
	{
	l=0;
	while(l<299)
	{
		copyEv([blockId]);
		blockEvents.push($gameMap._events[$gameMap._events.length-1]);
		l++;
	};
	};	
	copyEv([cacheId,/*switchId,switchId,switchId,switchId,*/blueCharId,purpleCharId,greenCharId,yellowCharId]);
	eraseEv([cacheId,/*switchId,*/blueCharId,purpleCharId,greenCharId,yellowCharId]);
	//$gameMap.setupEvents();
};

var i2; 
var j2;
var cGetId = function(name)
{
	// for (var i=0;i<cMap.width;i++)
	// {
	// 	for(var j=0;j<cMap.height;j++)
	// 	{
		for(var i=0; i<$gameMap.events().length;i++)
		{			var evId = $gameMap.events()[i].eventId();
			if(evId>0 && $gameMap.events()[i]!==undefined && $dataMap.events[evId].name === name)
			{
				return evId;
			}	
		};
	// 	}
	// }
};

var cGetPilars = function()
{
	// for (var i=0;i<cMap.width;i++)
	// {
		for(var j=0;j<$dataMap.events.length;j++)
		{
			var evId = ($gameMap.event(j)!==undefined)?j:0;
			// if(evId>0 && $dataMap.events[evId].name === 'pilier')
			// {
			// 	$gameMap.event(evId).express=false;
			// 	pilarEvents.push($gameMap.event(evId));
			// }	
			if(evId && $dataMap.events[evId].name === 'switch')
			{
				$gameMap.event(evId).express=false;
				switchEvents.push($gameMap.event(evId));
			};	
			if(evId>0 && $dataMap.events[evId].name.match(/bot\d/))
			{
				var bot = $gameMap.event(evId);
				var dV = dirVect(bot.direction(),bot);
				bot.lvl = Number($dataMap.events[evId].name.slice(-1));
				bot.running=true;
				botEvents.push(bot);
			//	botRay(bot);
			};
		}

	// }
};

var rayCoord=[];
var initRayCoord=function()
{
	// for(var i=0;i<23;i++)
	// {
	// 	for(var j=0;j<13;j++)
	// 	{
	// 		//rayCoord.push([i,j,0,0]);
	// 		rayCoord[j*$dataMap.width+i]=1;
	// 	}
	// }
};

var initBlockEvents=function()
{
	if(blockEvents.length===0)return;
	var k=0;
	for(var i=0;i<23;i++)
	{
		for(var j=0;j<13;j++)
		{
			blockEvents[k].setPosition(i,j);
			k++;
		}
	}
	// for(var i=2;i<21;i++)
	// {
	// 	for(var j=3;j<13;j++)
	// 	{
	// 		blockEvents[k].setPosition(i,j);
	// 		k++;
	// 	}
	// }
};

// var singleBotRay=function(bot)
// {

//     /*rayCoord=[];
//     for(var i=0;i<allPilars.length;i++)
//     {
//         if(allPilars[i].lvl>0)allPilars[i].blocking=false;
//     };*/
//     //var bot=botEvents[j];
//     //if(!bot.running)continue;
//     var dV = dirVect(bot.direction(),bot);
//     var maxLength = 0;
//     switch(bot.direction())
//     {
//         case 2:
//         maxLength=$gameMap.height()-bot.y-1;
//         break;
//         case 8:
//         maxLength=bot.y-3;
//         break;
//         case 6:
//         maxLength=$gameMap.width()-bot.x-3;
//         break;
//         case 4:
//         maxLength=bot.x-2;
//         break;
//     }

//     var z = bot.lvl;
//     if(z===0)
//     {
//     for(var i=1;i<=maxLength;i++)
//     {
//         var x = bot.x+dV[0]*i;
//         var y = bot.y+dV[1]*i;
//         rayCoord[x*$dataMap.height+y]=(rayCoord[x*$dataMap.height+y]===2)?2:0;
//     };
//     for(var i=1;i<=maxLength;i++)
//     {
//         var x = bot.x+dV[0]*i;
//         var y = bot.y+dV[1]*i;
//         // rayCoord[x*$dataMap.height+y]=(rayCoord[x*$dataMap.height+y]===2)?2:0;
//         var yellowInTheWay=whosThere(x,y,bot.lvl)!==undefined&&whosThere(x,y,bot.lvl).canAvoidBot;
//         //var current = rayCoord.myIndexOfArray([x,y,0]);
//         if(indexOfRayBlockingTiles.indexOf($gameMap.tileId(x,y,3))===-1&&!yellowInTheWay&&bot.running)
//         {
//             var otherBot=botThere(x,y,bot.lvl);
//             if(otherBot!==undefined&&otherBot.running&&bot.direction()+otherBot.direction()===10&&!tileMoving)
//             {
//                 bot.running=false;
//                 otherBot.running=false;
//                 killBots([bot,otherBot]);
//             }
//             if(otherBot!==undefined)break;
//             rayCoord[x*$dataMap.height+y]=Math.max(rayCoord[x*$dataMap.height+y],1);
//         }else
//         {
//         // for(var j=i;j<=maxLength;j++)rayCoord[x*$dataMap.height+y]=(rayCoord[x*$dataMap.height+y]===2)?2:0;
//         break;
//         }
//     };
//     }else
//     {
//     for(var i=1;i<=maxLength;i++)
//     {
//         var x = bot.x+dV[0]*i;
//         var y = bot.y+dV[1]*i;
//         var yellowInTheWay=whosThere(x,y,bot.lvl)!==undefined&&whosThere(x,y,bot.lvl).canAvoidBot;
//         //var current = rayCoord.myIndexOfArray([x,y,0]);
//         var pilar=PilarsXY(x,y)[0];
//         if(lowestPilarXY(x,y)!==undefined&&lowestPilarXY(x,y)===pilar&&!yellowInTheWay&&bot.running)
//         {
//             var otherBot=botThere(x,y,bot.lvl);
//             if(otherBot!==undefined&&otherBot.running&&bot.direction()+otherBot.direction()===10&&!tileMoving)
//             {
//                 bot.running=false;
//                 otherBot.running=false;
//                 killBots([bot,otherBot]);
//             }
//             if(otherBot!==undefined)break;
//             // lowestPilarXY(x,y)._characterName="!dalleBlocked";       
//             lowestPilarXY(x,y).blocking=true;   
//         }else
//         {
//         break;
//         }
//     }
//     }
//     for(var i=1;i<=maxLength;i++)
//         {
//         var x = bot.x+dV[0]*i;
//         var y = bot.y+dV[1]*i;
//         var z=rayCoord[x*$dataMap.height+y];
//         if(z<=0&&!blockEvents[x*$dataMap.height+y].isTransparent())
//         {
//         blockEvents[x*$dataMap.height+y].setTransparent(true);
//         };
//         if(z>=1&&blockEvents[x*$dataMap.height+y].isTransparent())
//         {
//         blockEvents[x*$dataMap.height+y].setTransparent(false);
//         }
//     }
//     // for(var i=1;i<=maxLength;i++)
//     // {
//     //     var x = bot.x+dV[0]*i;
//     //     var y = bot.y+dV[1]*i;
//     //     rayCoord[x*$dataMap.height+y]=rayCoord[x*$dataMap.height+y]+1;
//     // };
// rayCoord[285]=undefined;
// }

var botRay=function(bot)
{

	if(botEvents.length===0)return;
	//for(var i=1;i<rayCoord.length;i++)rayCoord[i][3]=0;
	for(var i=0;i<286;i++)rayCoord[i]=0;
	for(var i=0;i<allPilars.length;i++)
	{
		if(allPilars[i].lvl>0)allPilars[i].blocking=false;
	};
	for(var j = 0;j<botEvents.length;j++)
{
	var bot=botEvents[j];
	if(!bot.running)continue;
	var dV = dirVect(bot.direction(),bot);
	var maxLength = 0;
	switch(bot.direction())
	{
		case 2:
		maxLength=$gameMap.height()-bot.y-1;
		break;
		case 8:
		maxLength=bot.y-3;
		break;
		case 6:
		maxLength=$gameMap.width()-bot.x-3;
		break;
		case 4:
		maxLength=bot.x-2;
		break;
	}

	var z = bot.lvl;
	if(z===0)
	{
	for(var i=1;i<=maxLength;i++)
	{
		var x = bot.x+dV[0]*i;
		var y = bot.y+dV[1]*i;

		var yellowInTheWay=whosThere(x,y,bot.lvl)!==undefined&&whosThere(x,y,bot.lvl).canAvoidBot;
		//var current = rayCoord.myIndexOfArray([x,y,0]);
		if(indexOfRayBlockingTiles.indexOf($gameMap.tileId(x,y,3))===-1&&!yellowInTheWay&&bot.running)
		{
			var otherBot=botThere(x,y,bot.lvl);
			if(otherBot!==undefined&&otherBot.running&&bot.direction()+otherBot.direction()===10&&!tileMoving)
			{
				bot.running=false;
				otherBot.running=false;
				killBots([bot,otherBot]);
			}
			if(otherBot!==undefined)break;
			//rayCoord[current][3]++;
			rayCoord[x*$dataMap.height+y]=(rayCoord[x*$dataMap.height+y]||0)+1;
		}else
		{
		break;
		}
	};
	}else
	{
	for(var i=1;i<=maxLength;i++)
	{
		var x = bot.x+dV[0]*i;
		var y = bot.y+dV[1]*i;
		var yellowInTheWay=whosThere(x,y,bot.lvl)!==undefined&&whosThere(x,y,bot.lvl).canAvoidBot;
		//var current = rayCoord.myIndexOfArray([x,y,0]);
		var pilar=PilarsXY(x,y)[0];
		if(lowestPilarXY(x,y)!==undefined&&lowestPilarXY(x,y)===pilar&&!yellowInTheWay&&bot.running)
		{
			var otherBot=botThere(x,y,bot.lvl);
			if(otherBot!==undefined&&otherBot.running&&bot.direction()+otherBot.direction()===10&&!tileMoving)
			{
				bot.running=false;
				otherBot.running=false;
				killBots([bot,otherBot]);
			}
			if(otherBot!==undefined)break;
			// lowestPilarXY(x,y)._characterName="!dalleBlocked";		
			lowestPilarXY(x,y).blocking=true;	
		}else
		{
		break;
		}
	}
	}
}
rayCoord[285]=undefined;
}

var killBots = function(bots)
{
	for(var i=0; i<bots.length; i++)
	{
			 	bots[i].forceMoveRoute({
				list:[
				{
				code: 15,
				indent: null,
				parameters:[60]
				},{
				code: 45,
				indent: null,
				parameters:["this.setTransparent(true);this.setPosition(0,0);"]
				},{
				code: 0,
				indent: null,
				parameters:[]
				}],
				repeat:false,
				skippable:true,
				wait:false
			});		
	}
}

var drawBlockingTiles = function()
{
	if(botEvents.length===0)return;
	for(var i=0;i<rayCoord.length;i++)
	{
		//var x=rayCoord[i][0];
		//var y=rayCoord[i][1];
		var z=rayCoord[i]/*[3]*/;
	    //var alreadyBlocked=($gameMap.tileId(x,y,3)===24);
	    if(/*alreadyBlocked&&*/z<=0&&!blockEvents[i].isTransparent())
	    {
	   	blockEvents[i].setTransparent(true);
		// $dataMap.data[(3*$dataMap.height+y)*$dataMap.width+x]=$gameMap.tileId(x,y,2);
		//continue;
	    };
		// if(alreadyBlocked)continue;
		if(z>=1&&blockEvents[i].isTransparent())
		{
		blockEvents[i].setTransparent(false);
		// $dataMap.data[(2*$dataMap.height+y)*$dataMap.width+x]=$gameMap.tileId(x,y,3);
		// $dataMap.data[(3*$dataMap.height+y)*$dataMap.width+x]=24;
		}
	}
	for(var i=0;i<allPilars.length;i++)
	{
		if(allPilars[i].lvl===0||tileMoving)continue;
		// allPilars[i]._characterName=(allPilars[i].blocking===true)?"!dalleBlocked":"!dalle";
		if(allPilars[i]._characterName==="!dalleBlocked"&&!allPilars[i].blocking)allPilars[i]._characterName="!dalle";
		if(allPilars[i]._characterName==="!dalle"&&allPilars[i].blocking)allPilars[i]._characterName="!dalleBlocked";
	};
}

Array.prototype.myIndexOfArray = function(myArray)
{
	for(var i=0;i<this.length;i++)
	{
		if((this[i].slice(0,3)).equals(myArray))return i;
	}
	return -1;
};

var cGetMapElements = function()
{
	var k=0;
	var s=0;
	for (var i=0;i<cMap.width;i++)
	{
		for(var j=0;j<cMap.height;j++)
		{

			var TileId = $gameMap.tileId(i,j,3);
			if($gameMap.tileId(i,j,3)===11)
				{
					cCountFreeSlot++;
				}

			switch(TileId)
			{
				case 4:
				switchEvents[s].setPosition(i,j);
				switchEvents[s].set_frame("!dalle",5,1,2);
				switchEvents[s].setPriorityType(j);
				switchEvents[s].lvl = 0;
				blueSwitch = switchEvents[s];
				s++;
				break;			
				case 5:
				switchEvents[s].setPosition(i,j);
				switchEvents[s].set_frame("!dalle",5,2,2);
				switchEvents[s].setPriorityType(j);
				switchEvents[s].lvl = 0;
				purpleSwitch = switchEvents[s];
				s++;
				break;			
				case 6:
				switchEvents[s].setPosition(i,j);
				switchEvents[s].set_frame("!dalle",5,3,2);
				switchEvents[s].setPriorityType(j);
				switchEvents[s].lvl = 0;
				greenSwitch = switchEvents[s];
				s++;
				break;			
				case 7:
				switchEvents[s].setPosition(i,j);
				switchEvents[s].set_frame("!dalle",6,1,2);
				switchEvents[s].setPriorityType(j);
				switchEvents[s].lvl = 0;
				yellowSwitch = switchEvents[s];
				s++;
				break;
				case 20:
				switchEvents[s].setPosition(i,j);
				switchEvents[s].set_frame("!dalle",5,1,4);
				switchEvents[s].setPriorityType(j);
				switchEvents[s].lvl = 1;
				blueSwitch = switchEvents[s];
				s++;
				break;			
				case 21:
				switchEvents[s].setPosition(i,j);
				switchEvents[s].set_frame("!dalle",5,2,4);
				switchEvents[s].setPriorityType(j);
				switchEvents[s].lvl = 1;
				purpleSwitch = switchEvents[s];
				s++;
				break;			
				case 22:
				switchEvents[s].setPosition(i,j);
				switchEvents[s].set_frame("!dalle",5,3,4);
				switchEvents[s].setPriorityType(j);
				switchEvents[s].lvl = 1;
				greenSwitch = switchEvents[s];
				s++;
				break;			
				case 23:
				switchEvents[s].setPosition(i,j);
				switchEvents[s].set_frame("!dalle",6,1,4);
				switchEvents[s].setPriorityType(j);
				switchEvents[s].lvl = 1;
				yellowSwitch = switchEvents[s];
				s++;
				break;
				case 44:
				switchEvents[s].setPosition(i,j);
				switchEvents[s].set_frame("!dalle",5,1,6);
				switchEvents[s].setPriorityType(j);
				switchEvents[s].lvl = 2;
				blueSwitch = switchEvents[s];
				s++;
				break;			
				case 45:
				switchEvents[s].setPosition(i,j);
				switchEvents[s].set_frame("!dalle",5,2,6);
				switchEvents[s].setPriorityType(j);
				switchEvents[s].lvl = 2;
				purpleSwitch = switchEvents[s];
				s++;
				break;			
				case 46:
				switchEvents[s].setPosition(i,j);
				switchEvents[s].set_frame("!dalle",5,3,6);
				switchEvents[s].setPriorityType(j);
				switchEvents[s].lvl = 2;
				greenSwitch = switchEvents[s];
				s++;
				break;			
				case 47:
				switchEvents[s].setPosition(i,j);
				switchEvents[s].set_frame("!dalle",6,1,6);
				switchEvents[s].setPriorityType(j);
				switchEvents[s].lvl = 2;
				yellowSwitch = switchEvents[s];
				s++;
				break;
				case 76:
				switchEvents[s].setPosition(i,j);
				switchEvents[s].set_frame("!dalle",5,1,8);
				switchEvents[s].setPriorityType(j);
				switchEvents[s].lvl = 3;
				blueSwitch = switchEvents[s];
				s++;
				break;			
				case 77:
				switchEvents[s].setPosition(i,j);
				switchEvents[s].set_frame("!dalle",5,2,8);
				switchEvents[s].setPriorityType(j);
				switchEvents[s].lvl = 3;
				purpleSwitch = switchEvents[s];
				s++;
				break;			
				case 78:
				switchEvents[s].setPosition(i,j);
				switchEvents[s].set_frame("!dalle",5,3,8);
				switchEvents[s].setPriorityType(j);
				switchEvents[s].lvl = 3;
				greenSwitch = switchEvents[s];
				s++;
				break;			
				case 79:
				switchEvents[s].setPosition(i,j);
				switchEvents[s].set_frame("!dalle",6,1,8);
				switchEvents[s].setPriorityType(j);
				switchEvents[s].lvl = 3;
				yellowSwitch = switchEvents[s];
				s++;
				break;			
				case 8:
				pilarEvents[k].setPosition(i,j);
				pilarEvents[k].set_frame("!dalle",6,2,4);
				pilarEvents[k].lvl = 1;
				k++;
				break;				
				case 9:
				pilarEvents[k].setPosition(i,j);
				pilarEvents[k].set_frame("!dalle",6,2,6);
				pilarEvents[k].lvl = 2;
				k++;
				break;
				case 10:
				pilarEvents[k].setPosition(i,j);
				pilarEvents[k].set_frame("!dalle",6,2,8);
				pilarEvents[k].lvl =3
				k++;
				break;
				case 16:
				pilarEvents[k].setPosition(i,j);
				pilarEvents[k].set_frame("!dalle",6,3,4);
				pilarEvents[k].lvl = 1;
				pilarEvents[k].orig_lvl = 1;
				pilarEvents[k].express = true;
				pilarEvents[k].image=["!dalle",6,3,4]
				k++;
				break;				
				case 17:
				pilarEvents[k].setPosition(i,j);
				pilarEvents[k].set_frame("!dalle",7,1,6);
				pilarEvents[k].lvl = 2;
				pilarEvents[k].orig_lvl = 2;
				pilarEvents[k].express = true;
				pilarEvents[k].image=["!dalle",7,1,6]
				k++;
				break;
				case 18:
				pilarEvents[k].setPosition(i,j);
				pilarEvents[k].set_frame("!dalle",7,2,8);
				pilarEvents[k].lvl =3;
				pilarEvents[k].orig_lvl = 3;
				pilarEvents[k].express = true;
				pilarEvents[k].image=["!dalle",7,2,8]
				k++;
				break;
				case 24:
				pilarEvents[k].setPosition(i,j);
				pilarEvents[k].set_frame("!dalle",7,3,4);
				pilarEvents[k].lvl = 1;
				pilarEvents[k].trainRight = true;
				k++;
				break;				
				case 25:
				pilarEvents[k].setPosition(i,j);
				pilarEvents[k].set_frame("!dalle",7,3,6);
				pilarEvents[k].lvl = 2;
				pilarEvents[k].trainRight = true;
				k++;
				break;
				case 26:
				pilarEvents[k].setPosition(i,j);
				pilarEvents[k].set_frame("!dalle",7,3,8);
				pilarEvents[k].lvl =3;
				pilarEvents[k].trainRight = true;
				k++;
				break;
				case 32:
				pilarEvents[k].setPosition(i,j);
				pilarEvents[k].set_frame("!dalle",8,1,4);
				pilarEvents[k].lvl = 1;
				pilarEvents[k].trainLeft = true;
				k++;
				break;				
				case 33:
				pilarEvents[k].setPosition(i,j);
				pilarEvents[k].set_frame("!dalle",8,1,6);
				pilarEvents[k].lvl = 2;
				pilarEvents[k].trainLeft = true;
				k++;
				break;
				case 34:
				pilarEvents[k].setPosition(i,j);
				pilarEvents[k].set_frame("!dalle",8,1,8);
				pilarEvents[k].lvl =3;
				pilarEvents[k].trainLeft = true;
				k++;
				break;
				case 19:
				blueTile.setPosition(i,j);
				blueTile.orig_x=blueTile.x;
				blueTile.orig_y=blueTile.y;
				blueTile.isSet=true;
				blueTile.lvl = 0;
				blueTile.set_frame(blueTile.image[0],blueTile.image[1],blueTile.image[2],2);
				break;
				case 27:
				purpleTile.setPosition(i,j);
				purpleTile.orig_x=purpleTile.x;
				purpleTile.orig_y=purpleTile.y;
				purpleTile.isSet=true;
				purpleTile.lvl = 0;
				purpleTile.set_frame(purpleTile.image[0],purpleTile.image[1],purpleTile.image[2],2);
				break;
				case 35:
				greenTile.setPosition(i,j);
				greenTile.orig_x=greenTile.x;
				greenTile.orig_y=greenTile.y;				
				greenTile.isSet=true;
				greenTile.lvl = 0;
				greenTile.set_frame(greenTile.image[0],greenTile.image[1],greenTile.image[2],2);
				break;
				case 43:
				yellowTile.setPosition(i,j);
				yellowTile.orig_x=yellowTile.x;
				yellowTile.orig_y=yellowTile.y;				
				yellowTile.isSet=true;
				yellowTile.lvl = 0;
				yellowTile.set_frame(yellowTile.image[0],yellowTile.image[1],yellowTile.image[2],2);
				break;

				case 141:
				blueTile.setPosition(i,j);
				blueTile.orig_x=blueTile.x;
				blueTile.orig_y=blueTile.y;				
				blueTile.isSet=true;
				blueTile.lvl = 1;
				blueTile.set_frame(blueTile.image[0],blueTile.image[1],blueTile.image[2],4);
				break;
				case 175:
				purpleTile.setPosition(i,j);
				purpleTile.orig_x=purpleTile.x;
				purpleTile.orig_y=purpleTile.y;				
				purpleTile.isSet=true;
				purpleTile.lvl = 1;
				purpleTile.set_frame(purpleTile.image[0],purpleTile.image[1],purpleTile.image[2],4);
				break;
				case 189:
				greenTile.setPosition(i,j);
				greenTile.orig_x=greenTile.x;
				greenTile.orig_y=greenTile.y;				
				greenTile.isSet=true;
				greenTile.lvl = 1;
				greenTile.set_frame(greenTile.image[0],greenTile.image[1],greenTile.image[2],4);
				break;
				case 223:
				yellowTile.setPosition(i,j);
				yellowTile.orig_x=yellowTile.x;
				yellowTile.orig_y=yellowTile.y;				
				yellowTile.isSet=true;
				yellowTile.lvl = 1;
				yellowTile.set_frame(yellowTile.image[0],yellowTile.image[1],yellowTile.image[2],4);
				break;

				case 150:
				blueTile.setPosition(i,j);
				blueTile.orig_x=blueTile.x;
				blueTile.orig_y=blueTile.y;				
				blueTile.isSet=true;
				blueTile.lvl = 2;
				blueTile.set_frame(blueTile.image[0],blueTile.image[1],blueTile.image[2],6)
				break;
				case 174:
				purpleTile.setPosition(i,j);
				purpleTile.orig_x=purpleTile.x;
				purpleTile.orig_y=purpleTile.y;				
				purpleTile.isSet=true;
				purpleTile.lvl = 2;
				purpleTile.set_frame(purpleTile.image[0],purpleTile.image[1],purpleTile.image[2],6)
				break;
				case 198:
				greenTile.setPosition(i,j);
				greenTile.orig_x=greenTile.x;
				greenTile.orig_y=greenTile.y;				
				greenTile.isSet=true;
				greenTile.lvl = 2;
				greenTile.set_frame(greenTile.image[0],greenTile.image[1],greenTile.image[2],6)
				break;
				case 222:
				yellowTile.setPosition(i,j);
				yellowTile.orig_x=yellowTile.x;
				yellowTile.orig_y=yellowTile.y;				
				yellowTile.isSet=true;
				yellowTile.lvl = 2;
				yellowTile.set_frame(yellowTile.image[0],yellowTile.image[1],yellowTile.image[2],6)
				break;

				case 159:
				blueTile.setPosition(i,j);
				blueTile.orig_x=blueTile.x;
				blueTile.orig_y=blueTile.y;				
				blueTile.isSet=true;
				blueTile.lvl = 3;
				blueTile.set_frame(blueTile.image[0],blueTile.image[1],blueTile.image[2],8)
				break;
				case 173:
				purpleTile.setPosition(i,j);
				purpleTile.orig_x=purpleTile.x;
				purpleTile.orig_y=purpleTile.y;				
				purpleTile.isSet=true;
				purpleTile.lvl = 3;
				purpleTile.set_frame(purpleTile.image[0],purpleTile.image[1],purpleTile.image[2],8)
				break;
				case 207:
				greenTile.setPosition(i,j);
				greenTile.orig_x=greenTile.x;
				greenTile.orig_y=greenTile.y;				
				greenTile.isSet=true;
				greenTile.lvl = 3;
				greenTile.set_frame(greenTile.image[0],greenTile.image[1],greenTile.image[2],8)
				break;
				case 221:
				yellowTile.setPosition(i,j);
				yellowTile.orig_x=yellowTile.x;
				yellowTile.orig_y=yellowTile.y;				
				yellowTile.isSet=true;
				yellowTile.lvl = 3;
				yellowTile.set_frame(yellowTile.image[0],yellowTile.image[1],yellowTile.image[2],8)
				break;
			}	
		}

	}
pilarEvents = pilarEvents.slice(0,k);
switchEvents = switchEvents.slice(0,s);
$gameMap.changeTileset(2);
};


var initChar = function(chara,name,canJump,canSetTile,canAvoidBot,cameleon)
{
	chara.name = name;
	chara.active = false;
	chara.lvl = 0;
	chara.canJump = canJump;
	chara.exit = false;
	chara.canExchange=false;
	behindPilar = false;
	cantMove = false;
	fixPriority=false;
	chara.canSetTile = canSetTile;
	chara.canAvoidBot = canAvoidBot;
	chara.cameleon = cameleon;
}

var initTile = function(tile, image, id)
{
	tile.image = image;
	tile.isSet = false;
	tile.lvl = 0;
	tile.active = false;
	this.newDir =0;
	tile.id = id;
}
var door = {};
var blueTile = {};
var purpleTile = {};
var greenTile = {};
var yellowTile = {};

var blueChar = {};
var purpleChar = {};
var greenChar = {};
var yellowChar = {};
var playerChar = Object.create(Game_Event.prototype);
var cArrayTeamMembers = [blueChar, purpleChar, greenChar, yellowChar];
var allPilars = [];
var tileIdKey =[];
var allowPilarTransp;

var cGameInit = function(){
	if(mapOrder.length===0){
	for(var i=0;i<$dataMapInfos.length;i++){
		if($dataMapInfos[i]!==null)mapOrder[Number($dataMapInfos[i].name.slice(-3))]=$dataMapInfos[i].id;};
	};
	mapNumber = mapOrder.indexOf($gameMap.mapId());

$gameMap.setupEvents();
rayCoord=[];
blockEvents=[];
switchEvents=[];
pilarEvents=[];
botEvents=[];
countElements();
createEvents();
initRayCoord();
initBlockEvents();
$gameScreen.startFadeOut(1);
blueChar = $gameMap.event(cGetId("blue"));
purpleChar = $gameMap.event(cGetId("purple"));
greenChar = $gameMap.event(cGetId("green"));
yellowChar = $gameMap.event(cGetId("yellow"));
blueWall = $gameMap.event(cGetId("blueWall"));
purpleWall = $gameMap.event(cGetId("purpleWall"));
greenWall = $gameMap.event(cGetId("greenWall"));
yellowWall = $gameMap.event(cGetId("yellowWall"));
nbOfChar=4;
blueTile = $gameMap.event(cGetId("dalle_bleu"));
purpleTile = $gameMap.event(cGetId("dalle_violet"));
greenTile = $gameMap.event(cGetId("dalle_vert"));
yellowTile = $gameMap.event(cGetId("dalle_jaune"));
blue2=$gameMap.event(cGetId("blue2"));
purple2=$gameMap.event(cGetId("purple2"));
green2=$gameMap.event(cGetId("green2"));
yellow2=$gameMap.event(cGetId("yellow2"));
blue2.setOpacity(0);purple2.setOpacity(0);green2.setOpacity(0);yellow2.setOpacity(0);



cacheTile = $gameMap.event(cGetId("cache"));

	initChar(blueChar,'blue',false,false,false,false);
	initChar(purpleChar,'purple',false,true,false,false);
	initChar(greenChar,'green',true,false,false,false);
	initChar(yellowChar,'yellow',false,false,true,false);
	initChar(playerChar,false);
	cArrayTeamMembers = [blueChar, purpleChar, greenChar, yellowChar];

    initTile(blueTile,["!dalle",1,1,2], [19,141,150,159]);
    initTile(purpleTile,["!dalle",1,2,2], [27,175,174,173]);
    initTile(greenTile,["!dalle",1,3,2],[35,189,198,207]);
    initTile(yellowTile,["!dalle",2,1,2],[43,223,222,221]);

	cGetPilars();
	cGetMapElements();
	blueChar.ownSwitch = blueSwitch;
	purpleChar.ownSwitch = purpleSwitch;
	greenChar.ownSwitch = greenSwitch;
	yellowChar.ownSwitch = yellowSwitch;
	playerChar.ownSwitch = {};

	blueChar.ownTile = blueTile;
	purpleChar.ownTile = purpleTile;
	greenChar.ownTile = greenTile;
	yellowChar.ownTile = yellowTile;
	playerChar.ownTile = {};
	allPilars = pilarEvents.concat(switchEvents.concat([blueTile,purpleTile,greenTile,yellowTile]));
	tileIdKey=[];

	for(var i=0;i<allPilars.length;i++)
	{
		for(j=0; j<=allPilars[i].lvl;j++){
			tileIdKey.push([allPilars[i].x,allPilars[i].y-j])

		};
			tempChar=whosThere(allPilars[i].x,allPilars[i].y-allPilars[i].lvl,0);
			if(tempChar!==undefined)tempChar.lvl=Math.min(1,allPilars[i].lvl);
			allPilars[i].orig_x=allPilars[i].x;
			allPilars[i].orig_y=allPilars[i].y;
			allPilars[i].setPriorityType((allPilars[i].lvl===0)?0:allPilars[i].y);
	}
	door = $gameMap.event(cGetId("door"));
	door.open=false;

	if(mapNumber>=17)blueChar.cameleon=true;
	tilesToReveal=[];
	hideTiles();
	allowSwap=false;
	allowMove=false;
	cUpdatePos();
	playerChar=blueChar;
		$gameScreen.startFadeIn(50);
		if($dataMap.note.length!==mapNumber)Utils();
	stateEye=0;
	blueChar.cameleon = (mapNumber>17)?true:false;
	allowPilarTransp = (mapNumber>8)?true:false;
	};

var setMyCharPriority = function()
{
	for(var i=0; i<cArrayTeamMembers.length; i++)
	{
		chara=cArrayTeamMembers[i];
		charaPilar=onPilar2(chara);
		if(chara.fixPriority)continue;
		switch(chara.lvl)
		{
			case 0:
			chara.setPriorityType(chara.y);
			break;
			case 1:
			if(charaPilar[0]!==undefined)
				{
				if(chara.behindPilar)chara.setPriorityType(charaPilar[charaPilar.length-1].orig_y+1);
				if(!chara.behindPilar)chara.setPriorityType(charaPilar[0].orig_y+5);
				}
			break;
		}
	}
}

var allTilesSet = function()
{
	if(blueTile.isSet&&purpleTile.isSet&&greenTile.isSet&&yellowTile.isSet)return true;
	return false;
}

var canExchange = function()
{
	var charas = cArrayTeamMembers;
	for(var i = 0; i<charas.length;i++){charas[i].canExchange=(onTile(charas[i])===charas[i].ownTile && charas[i].ownTile.lvl===0&&mapNumber>11)?true:false;};
}

var initPictures=function(){};
var blueCounter=0;
var purpleCounter=0;
var greenCounter=0;
var yellowCounter=0;
var updating=false;
var updateBot=0;
var refreshBot = false;
var cUpdatePos = function()
{
	if(updating)return;
	updating=true;
	var testMoveTile=moveTileTest();
	var pConSwitch=onSwitch(playerChar);
	if(onSwitch(blueChar) && onSwitch(purpleChar) && onSwitch(greenChar) && onSwitch(yellowChar))$gameSwitches.setValue(6,true);
	if(updateBot>5&&playerChar.canAvoidBot/*&&((rayCoord!==[]&&rayCoord[playerChar.x*$dataMap.height+playerChar.y]===1)||(onPilar(playerChar)!==undefined&&onPilar(playerChar)._characterName==='!dalleBlocked'))*/)
	 {
	 botRay();
	 drawBlockingTiles();
     updateBot=0;	
	 };
	var charas = cArrayTeamMembers;
	var Pilars=PilarsXY(playerChar.x,playerChar.y);
    cIconExchange.cActive=(testSwapChar()===true&&mapNumber>11)?true:false;
	// for(var i = 0; i<charas.length;i++){charas[i].canExchange=(onTile(charas[i])===charas[i].ownTile && charas[i].ownTile.lvl===0)?true:false;};
	playerChar.behindPilar=((Pilars[0]!==undefined && Pilars[0].y>playerChar.y&&Pilars[0].y-Pilars[0].lvl<playerChar.y)||(playerChar.behindPilar&&playerChar.cantMove))?true:false;
	if(playerChar.x === door.x && playerChar.y === door.y &&!playerChar.exit)exitChar();
	//playerChar.onPilar = (onPilar2(playerChar).length>0)?onPilar2(playerChar)[0]:undefined;
	setMyCharPriority();
	$gamePlayer.setPriorityType(playerChar._priorityType);
	cIconBlueTile.cActive = (tileSelection && playerChar.canSetTile && pConSwitch && cCountFreeSlot>0 /*&& !blueTile.isSet*/);
	cIconJump.cActive=fCanJumpFront()||fCanAssistJumpFront()||canJumpInRay();
	cIconCancel.cActive = tileSelection||tileControl;
	cIconConfirm.cActive = tileControl;
	(pConSwitch&&playerChar.ownTile.isSet&&!tileSelection&&!tileControl)?cIconUp.cActive = true:cIconUp.cActive = false;
    cIconEye1.cActive=(mapNumber>8&&stateEye===1)?true:false;
    cIconEye2.cActive=(mapNumber>8&&stateEye===0)?true:false;
	// (pConSwitch&&playerChar.ownTile.isSet&&!tileSelection&&!tileControl)?cIconDown.cActive = true:cIconDown.cActive = false;
	(testMoveTile)?cIconUp.cActive = true:cIconUp.cActive = false;
	//(testMoveTile)?cIconDown.cActive = true:cIconDown.cActive = false;
	cIconBlueD.cActive=(onSwitch(blueChar))?true:false;
    cIconPurpleD.cActive=(onSwitch(purpleChar))?true:false;
    cIconGreenD.cActive=(onSwitch(greenChar))?true:false;
    cIconYellowD.cActive=(onSwitch(yellowChar))?true:false;
    if(cIconBlueD.cActive)
    {
        blueCounter++;
        $gameSelfSwitches.setValue([$gameMap.mapId(),blueWall.eventId(),'A'],true);
        if(blueCounter===1&&allowMove)
            {
                $gameSwitches.setValue(12,true);
                //blueSwitch.requestAnimation(47);
            }
    }else{
        blueCounter = 0;
        $gameSelfSwitches.setValue([$gameMap.mapId(),blueWall.eventId(),'A'],false);
    }
    if(cIconPurpleD.cActive)
    {
        purpleCounter++;
        $gameSelfSwitches.setValue([$gameMap.mapId(),purpleWall.eventId(),'A'],true);
        if(purpleCounter===1&&allowMove)$gameSwitches.setValue(13,true);
    }else{
        purpleCounter = 0;
        $gameSelfSwitches.setValue([$gameMap.mapId(),purpleWall.eventId(),'A'],false);
    }
    if(cIconGreenD.cActive)
    {
        greenCounter++;
        $gameSelfSwitches.setValue([$gameMap.mapId(),greenWall.eventId(),'A'],true);
        if(greenCounter===1&&allowMove)$gameSwitches.setValue(14,true);
    }else{
        greenCounter = 0;
        $gameSelfSwitches.setValue([$gameMap.mapId(),greenWall.eventId(),'A'],false);
    }
    if(cIconYellowD.cActive)
    {
        yellowCounter++;
        $gameSelfSwitches.setValue([$gameMap.mapId(),yellowWall.eventId(),'A'],true);
        if(yellowCounter===1&&allowMove)$gameSwitches.setValue(15,true);
    }else{
        yellowCounter = 0;
        $gameSelfSwitches.setValue([$gameMap.mapId(),yellowWall.eventId(),'A'],false);
    }

    (cIconBlueD.cActive===true&&allowSwap)?$gameScreen.showPicture(cIconBlueD.cImageId, cIconBlueD.cImage, 1, cIconBlueD.cPos[0], cIconBlueD.cPos[1], 100, 100, (playerChar.eventId()===blueChar.eventId()&&playerChar.active)?255:50, 0):$gameScreen.erasePicture(cIconBlueD.cImageId);
    (cIconPurpleD.cActive===true&&allowSwap)?$gameScreen.showPicture(cIconPurpleD.cImageId, cIconPurpleD.cImage, 1, cIconPurpleD.cPos[0], cIconPurpleD.cPos[1], 100, 100, (playerChar.eventId()===purpleChar.eventId()&&playerChar.active)?255:50, 0):$gameScreen.erasePicture(cIconPurpleD.cImageId);
    (cIconGreenD.cActive===true&&allowSwap)?$gameScreen.showPicture(cIconGreenD.cImageId, cIconGreenD.cImage, 1, cIconGreenD.cPos[0], cIconGreenD.cPos[1], 100, 100, (playerChar.eventId()===greenChar.eventId()&&playerChar.active)?255:50, 0):$gameScreen.erasePicture(cIconGreenD.cImageId);
    (cIconYellowD.cActive===true&&allowSwap)?$gameScreen.showPicture(cIconYellowD.cImageId, cIconYellowD.cImage, 1, cIconYellowD.cPos[0], cIconYellowD.cPos[1], 100, 100, (playerChar.eventId()===yellowChar.eventId()&&playerChar.active)?255:50, 0):$gameScreen.erasePicture(cIconYellowD.cImageId);
    
    (playerChar.canSetTile && pConSwitch &&!tileSelection &&playerChar.active&&cCountFreeSlot>0&&!allTilesSet())?cIconSetTile.cActive=true:cIconSetTile.cActive=false;
	(cIconBlueChar.cActive===true&&allowSwap)?$gameScreen.showPicture(cIconBlueChar.cImageId, cIconBlueChar.cImage, 1, cIconBlueChar.cPos[0], cIconBlueChar.cPos[1], 100, 100, (playerChar.eventId()===blueChar.eventId()&&playerChar.active)?255:50, 0):$gameScreen.erasePicture(cIconBlueChar.cImageId);
	(cIconPurpleChar.cActive===true&&allowSwap)?$gameScreen.showPicture(cIconPurpleChar.cImageId, cIconPurpleChar.cImage, 1, cIconPurpleChar.cPos[0], cIconPurpleChar.cPos[1], 100, 100, (playerChar.eventId()===purpleChar.eventId()&&playerChar.active)?255:50, 0):$gameScreen.erasePicture(cIconPurpleChar.cImageId);
	(cIconGreenChar.cActive===true&&allowSwap)?$gameScreen.showPicture(cIconGreenChar.cImageId, cIconGreenChar.cImage, 1, cIconGreenChar.cPos[0], cIconGreenChar.cPos[1], 100, 100, (playerChar.eventId()===greenChar.eventId()&&playerChar.active)?255:50, 0):$gameScreen.erasePicture(cIconGreenChar.cImageId);
	(cIconYellowChar.cActive===true&&allowSwap)?$gameScreen.showPicture(cIconYellowChar.cImageId, cIconYellowChar.cImage, 1, cIconYellowChar.cPos[0], cIconYellowChar.cPos[1], 100, 100, (playerChar.eventId()===yellowChar.eventId()&&playerChar.active)?255:50, 0):$gameScreen.erasePicture(cIconYellowChar.cImageId);
	(cIconSetTile.cActive===true/*&&!blueTile.isSet*/)?$gameScreen.showPicture(cIconBlueTile0.cImageId, cIconBlueTile0.cImage, 1, cIconSetTile.cPos[0], cIconSetTile.cPos[1], 100, 100, 255, 0):$gameScreen.erasePicture(cIconBlueTile0.cImageId);
	(cIconJump.cActive===true)?$gameScreen.showPicture(cIconJump.cImageId, cIconJump.cImage, 1, cIconJump.cPos[0], cIconJump.cPos[1], 100, 100, 255, 0):$gameScreen.erasePicture(cIconJump.cImageId);
	(cIconCancel.cActive===true)?$gameScreen.showPicture(cIconCancel.cImageId, cIconCancel.cImage, 1, cIconCancel.cPos[0], cIconCancel.cPos[1], 100, 100, 255, 0):$gameScreen.erasePicture(cIconCancel.cImageId);
	(cIconConfirm.cActive===true)?$gameScreen.showPicture(cIconConfirm.cImageId, cIconConfirm.cImage, 1, cIconConfirm.cPos[0], cIconConfirm.cPos[1], 100, 100, 255, 0):$gameScreen.erasePicture(cIconConfirm.cImageId);
	(cIconUp.cActive===true)?$gameScreen.showPicture(cIconUp.cImageId, cIconUp.cImage, 1, cIconUp.cPos[0], cIconUp.cPos[1], 100, 100, 255, 0):$gameScreen.erasePicture(cIconUp.cImageId);
	(cIconEye1.cActive===true&&$gameSwitches.value(3)===true)?$gameScreen.showPicture(cIconEye1.cImageId, cIconEye1.cImage, 1, cIconEye1.cPos[0], cIconEye1.cPos[1], 100, 100, 255, 0):$gameScreen.erasePicture(cIconEye1.cImageId);
    (cIconEye2.cActive===true&&$gameSwitches.value(3)===true)?$gameScreen.showPicture(cIconEye2.cImageId, cIconEye2.cImage, 1, cIconEye2.cPos[0], cIconEye2.cPos[1], 100, 100, 255, 0):$gameScreen.erasePicture(cIconEye2.cImageId);
    (cIconExchange.cActive===true&&$gameSwitches.value(3)===true)?$gameScreen.showPicture(cIconExchange.cImageId, cIconExchange.cImage, 1, cIconExchange.cPos[0], cIconExchange.cPos[1], 100, 100, 255, 0):$gameScreen.erasePicture(cIconExchange.cImageId);
    (wallDown.cActive===true)?$gameScreen.showPicture(wallDown.cImageId, wallDown.cImage, 0, wallDown.cPos[0], wallDown.cPos[1], 100, 100, 255, 0):$gameScreen.erasePicture(wallDown.cImageId);
updateBot++;
updating=false;
};

var fCharNear = function(Char,k,d)
{
	var i = undefined
	var dir = [];
		switch(d)
		{
		case 0:
		dir = [(Char.direction() === 4)?-k:((Char.direction() === 6)?k:0),(Char.direction() === 8)?-k:((Char.direction() === 2)?k:0)];
		break;
		case 2:
		dir = [0,k];
		break;
		case 8:
		dir = [0,-k];
		break;
		case 4:
		dir = [-k,0];
		break;
		case 6:
		dir = [k,0];
		break;
		};
	return whosThere(Char.x+dir[0],Char.y+dir[1],Char.lvl);
}

var dirVect = function(d,Char){
		switch(d)
		{
		case 0:
		return [(Char.direction() === 4)?-1:((Char.direction() === 6)?1:0),(Char.direction() === 8)?-1:((Char.direction() === 2)?1:0)];
		break;
		case 2:
		return [0,1];
		break;
		case 8:
		return [0,-1];
		break;
		case 4:
		return [-1,0];
		break;
		case 6:
		return [1,0];
		break;
		};
	};

var fHoleNear = function(Char,k,d)
{
	var IsHole = [];
	var dir = [];
		switch(d)
		{
		case 0:
		dir = [(Char.direction() === 4)?-k:((Char.direction() === 6)?k:0),(Char.direction() === 8)?-k:((Char.direction() === 2)?k:0)];
		break;
		case 2:
		dir = [0,k];
		break;
		case 8:
		dir = [0,-k];
		break;
		case 4:
		dir = [-k,0];
		break;
		case 6:
		dir = [k,0];
		break;
		};

	return (myTileId(Char.x+dir[0],Char.y+dir[1])===3);
}

var myTileId = function(x,y)
{
for (var i=0; i<tileIdKey.length; i++)
{
	if(x===tileIdKey[i][0]&&y===tileIdKey[i][1])return $gameMap.tileId(x,y,3);
};
return ($gameMap.tileId(x,y,3)===129)?$gameMap.tileId(x,y,2):$gameMap.tileId(x,y,3);

}

var cSwitchPlayer = function()
{
	if(!allowSwap)return true;
	var cTM={};
	$gameTemp.clearDestination();
	charSelected = closestChar(TouchInput.x,TouchInput.y);
		 if(charSelected!==undefined)
			 {
			 	swapChar(charSelected);
			 	return true;
			}
	return false;
};

var nextChar=function(chara)
{
	switch(chara)
	{
		case blueChar:
		return (!purpleChar.exit)?purpleChar:(!greenChar.exit)?greenChar:(!yellowChar.exit)?yellowChar:blueChar;
		break;
		case purpleChar:
		return (!greenChar.exit)?greenChar:(!yellowChar.exit)?yellowChar:(!blueChar.exit)?blueChar:purpleChar;
		break;
		case greenChar:
		return (!yellowChar.exit)?yellowChar:(!blueChar.exit)?blueChar:(!purpleChar.exit)?purpleChar:greenChar;
		break;
		case yellowChar:
		return (!blueChar.exit)?blueChar:(!purpleChar.exit)?purpleChar:(!greenChar.exit)?greenChar:yellowChar;
		break;
	};
	};

var previousChar=function(chara)
{
	switch(chara)
	{
		case blueChar:
		return (!yellowChar.exit)?yellowChar:(!greenChar.exit)?greenChar:(!purpleChar.exit)?purpleChar:blueChar;
		break;
		case purpleChar:
		return (!blueChar.exit)?blueChar:(!yellowChar.exit)?yellowChar:(!greenChar.exit)?greenChar:purpleChar;
		break;
		case greenChar:
		return (!purpleChar.exit)?purpleChar:(!blueChar.exit)?blueChar:(!yellowChar.exit)?yellowChar:greenChar;
		break;
		case yellowChar:
		return (!greenChar.exit)?greenChar:(!purpleChar.exit)?purpleChar:(!blueChar.exit)?blueChar:yellowChar;
		break;
	};
	};

var nextTile=function(tile)
{
	switch(tile)
	{
		case blueTile:
		return (!purpleTile.isSet)?purpleTile:(!greenTile.isSet)?greenTile:(!yellowTile.isSet)?yellowTile:blueTile;
		break;
		case purpleTile:
		return (!greenTile.isSet)?greenTile:(!yellowTile.isSet)?yellowTile:(!blueTile.isSet)?blueTile:purpleTile;
		break;
		case greenTile:
		return (!yellowTile.isSet)?yellowTile:(!blueTile.isSet)?blueTile:(!purpleTile.isSet)?purpleTile:greenTile;
		break;
		case yellowTile:
		return (!blueTile.isSet)?blueTile:(!purpleTile.isSet)?purpleTile:(!greenTile.isSet)?greenTile:yellowTile;
		break;
	};
	};

var previousTile=function(tile)
{
	switch(tile)
	{
		case blueTile:
		return (!yellowTile.isSet)?yellowTile:(!greenTile.isSet)?greenTile:(!purpleTile.isSet)?purpleTile:blueTile;
		break;
		case purpleTile:
		return (!blueTile.isSet)?blueTile:(!yellowTile.isSet)?yellowTile:(!greenTile.isSet)?greenTile:purpleTile;
		break;
		case greenTile:
		return (!purpleTile.isSet)?purpleTile:(!blueTile.isSet)?blueTile:(!yellowTile.isSet)?yellowTile:greenTile;
		break;
		case yellowTile:
		return (!greenTile.isSet)?greenTile:(!purpleTile.isSet)?purpleTile:(!blueTile.isSet)?blueTile:yellowTile;
		break;
	};
	};

var swapChar = function(chara,n)
{

				if(chara===undefined)
				{
					if(n===1)swapChar(nextChar(playerChar));
					if(n===0)swapChar(previousChar(playerChar));
					return;
				};
				if(chara.exit)return;

			 	if(playerChar.active)
				 {
				 	$gameMap.event(playerChar.eventId()).forceMoveRoute({list:[{code: 0}],repeat:false,skippable:true,wait:false});
				 	$gameMap.event(playerChar.eventId()).setMoveSpeed(4);
				 	$gameMap.event(playerChar.eventId()).setDirection($gamePlayer.direction());
				 	$gameMap.event(playerChar.eventId()).setPosition($gamePlayer.x, $gamePlayer.y);
				 	$gameMap.event(playerChar.eventId()).setTransparent(false);
				 	$gameMap.event(playerChar.eventId()).setThrough(false);

				 }
				 $gamePlayer.setTransparent(true);
				$gamePlayer.setPosition(chara.x, chara.y);
			 	$gamePlayer.setDirection(chara.direction());
			 	$gamePlayer.setThrough(false);
			 	$gamePlayer.setMoveSpeed(5);
			 	//$gameActors.actor(1).setCharacterImage(chara.characterName(), chara.characterIndex());
			 	$gamePlayer._characterName=chara.characterName()
				$gamePlayer._characterIndex=chara.characterIndex()
			 	// $gamePlayer.reserveTransfer($gameMap.mapId(), chara.x, chara.y, chara.direction(), 2);

				chara.setDirectionFix(false);
				chara.setWalkAnime(true);
			 	chara.forceMoveRoute({
				list:[
				{
				code: 29,
				indent: null,
				parameters:[6]
				},{
				code: 39,
				indent: null,
				parameters:[]
				},{
				code: 37,
				indent: null,
				parameters:[]
				}/*,
				{				
				code: 10,
				indent: null,
				parameters:[]
				}*/,{
				code: 45,
				indent: null,
				parameters:["this.setPosition($gamePlayer.x,$gamePlayer.y);this.setDirection($gamePlayer.direction());"]
				},{
				code: 0,
				indent: null,
				parameters:[]
				}],
				repeat:true,
				skippable:true,
				wait:false
			});
			 	$gamePlayer.forceMoveRoute({
				list:[
				{
				code: 15,
				indent: null,
				parameters:[1]
				},{
				code: 45,
				indent: null,
				parameters:["this.setTransparent(false);"]
				},{
				code: 0,
				indent: null,
				parameters:[]
				}],
				repeat:false,
				skippable:true,
				wait:false
			});
			 	playerChar = chara;
			 	playerChar.active=true;
			 	swapMode=false;
                botRay();
                drawBlockingTiles();
			 	return;
}

var cMyPassibility = function(x,y,l,d)
{
	var bot = botThere(x,y,l)!==undefined;
	var chara = whosThere(x,y,l);
	var pilar = whatsThere(x,y,l);
	//var testBot = botEvents.length>0;
	if (bot || chara !== undefined||(pilar !==undefined&&l===0)||playerChar.cantMove) return false;
	if(x===door.x && y===door.y && l===0 && door.open) {return true};
	if(x<=1 || (y<=2&&l===0) || x>=21 || y>=13) {return false};
if(l>0){
	var pilar3=lowestPilarXY(playerChar.x,playerChar.y);
	if(pilar3!==undefined&&pilar3._characterName==="!dalleBlocked")return false;
	if(playerChar.behindPilar&&d===8)return false;
	var pilar2=lowestPilarXY(x,y);
	if(pilar2!==undefined&&pilar2._characterName==="!dalleBlocked"&&!playerChar.canAvoidBot)return false;
	var highPilar=PilarsXY(x,y);
	var cond1=(Pilars[0]!==undefined&&Pilars[0].y-Pilars[0].lvl===y);
	var cond2=(d===4||d===6)&&(Pilars[Pilars.length-1]!==undefined&&Pilars[Pilars.length-1].y-Pilars[Pilars.length-1].lvl===y);
	if(cond1||cond2)return true;
}else{
	if(botEvents.length>0)
	{
		// var blockPlayer = rayCoord[rayCoord.myIndexOfArray([playerChar.x,playerChar.y,playerChar.lvl])];
		var blockPlayer = rayCoord[playerChar.x*$dataMap.height+playerChar.y]>=1;
		if(blockPlayer/*[3]%2>0*/&&!playerChar.canAvoidBot)return false;
		if(rayCoord[x*$dataMap.height+y]>=1&&!playerChar.canAvoidBot)return false;	
	};
	if(myTileId(x,y)!==3)return true;
}
return false;
};

var firstTap=false;
Scene_Map.prototype.processMapTouch = function() 
{/*
// 	wait1=false;
// 	wait2=false;
// if(allowMove && !$gameSwitches.value(1)){
//     if ((TouchInput.isTriggered() || this._touchCount > 0)&&(closestChar(TouchInput.x,TouchInput.y)!==undefined&&closestChar(TouchInput.x,TouchInput.y)!==playerChar)) {
//         if (TouchInput.isPressed()) {
//         	if (closestChar(TouchInput.x,TouchInput.y)!==undefined&&closestChar(TouchInput.x,TouchInput.y)!==playerChar)
//         	{	wait1=true;
        	
//         		if(this._touchCount>10)
//         			{cSwitchPlayer();
//         			}
//         	}
//             this._touchCount++;
//         } else {
//         	var x = $gameMap.canvasToMapX(TouchInput.x);
//             var y = $gameMap.canvasToMapY(TouchInput.y);
//         	if((x>1 && (y>2||playerChar.lvl===1) && x<21)||(x===door.x&&y===door.y)) {$gameTemp.setDestination(x, y)};
//             this._touchCount = 0;
//         }
//     }
// }

// if(allowMove&&!wait1&&!wait2){
//     if (TouchInput.isTriggered() || this._touchCount > 0) {
//         if (TouchInput.isPressed()) {
//             if (this._touchCount === 0 || this._touchCount >= 15) {
//                 var x = $gameMap.canvasToMapX(TouchInput.x);
//                 var y = $gameMap.canvasToMapY(TouchInput.y);
//                  if((x>1 && (y>2||playerChar.lvl===1) && x<21)||(x===door.x&&y===door.y)) {$gameTemp.setDestination(x, y)};
//             }
//             this._touchCount++;
//         } else {
//             this._touchCount = 0;
//         }
//     }
// }*/
};

var delaiDT;
Game_Event.prototype.update = function() {
    Game_Character.prototype.update.call(this);
    this.checkEventTriggerAuto();
    this.updateParallel();

};

Game_Player.prototype.moveByInput = function() {
    if (!this.isMoving() && this.canMove()&&allowMove) {
        var direction = this.getInputDirection();
        if (direction > 0) {
            $gameTemp.clearDestination();
        } else if ($gameTemp.isDestinationValid()){
            var x = $gameTemp.destinationX();
            var y = $gameTemp.destinationY();
            direction = this.findDirectionTo(x, y);
        }
        if (direction > 0) {
            this.executeMove(direction);
        	if(playerChar.lvl===1&&playerChar.active)setAllPilarsTransp(0);
        }
    }
};

var fJump = function()
{
	 charAhead = fCharNear(playerChar,1,0);
	$gamePlayer.forceMoveRoute({
			list:[{
			code: 15,
			indent: null,
			parameters:[3]
			},{
			code: 45,
			indent: null,
			parameters:["if(fCanJumpFront()){playerChar.fixPriority=true;if(playerChar.lvl>0)$gameSwitches.setValue(74,false);AudioManager.playSe({name: 'Jump1', volume: 20, pitch: 90, pan: -60});$gamePlayer.jump_forward(2);}"]
			},{
			code: 15,
			indent: null,
			parameters:[0]
			},{
			code: 45,
			indent: null,
			parameters:["playerChar.fixPriority=false;$gameSwitches.setValue(74,true);"]
			},{
			code: 0,
			indent: null,
			parameters:[]
			}],
			repeat:false,
			skippable:true,
			wait:false
			});
	if (fCanAssistJumpFront()){
		AudioManager.playSe({name: 'Jump1', volume: 20, pitch: 90, pan: -60});
		charAhead.jump_forward(2);
		charAhead.forceMoveRoute({
			list:[{
			code: 15,
			indent: null,
			parameters:[5]
			},{
			code: 45,
			indent: null,
			parameters:["botRay();drawBlockingTiles();"]
			},{
			code: 0,
			indent: null,
			parameters:[]
			}],
			repeat:false,
			skippable:true,
			wait:false
			});	
	};
}

var canJumpInRay = function()
{
	var vP = dirVect(0,playerChar);
	if(playerChar.canAvoidBot)return false;
	if(!coordInGame(playerChar.x+vP[0],playerChar.y+vP[1],playerChar.lvl))return;
    if(playerChar.behindPilar&&playerChar.lvl>0)return false;
	// var playerBlocked = playerChar.lvl===0&&rayCoord[rayCoord.myIndexOfArray([playerChar.x,playerChar.y,playerChar.lvl])][3]>0;
	// var nextTileBlocked = playerChar.lvl===0&&rayCoord[rayCoord.myIndexOfArray([playerChar.x+vP[0],playerChar.y+vP[1],playerChar.lvl])][3]>0;
	var playerBlocked = playerChar.lvl===0&&rayCoord[playerChar.x*$dataMap.height+playerChar.y]>=1;
	var nextTileBlocked = playerChar.lvl===0&&rayCoord[(playerChar.x+vP[0])*$dataMap.height+playerChar.y+vP[1]]>=1;
	if(botThere(playerChar.x+vP[0],playerChar.y+vP[1],playerChar.lvl)!==undefined||whosThere(playerChar.x+vP[0],playerChar.y+vP[1],playerChar.lvl)!==undefined)return;
	if(!playerBlocked&&nextTileBlocked)return true;
	var lowestPilar=lowestPilarXY(playerChar.x+vP[0],playerChar.y+vP[1]);
	var playerBlocked = playerChar.lvl===1&&onPilar(playerChar)!==undefined&&onPilar(playerChar)._characterName==="!dalleBlocked";
	var nextTileBlocked = playerChar.lvl===1&&lowestPilar!==undefined&&lowestPilar._characterName==="!dalleBlocked";
	if(botThere(playerChar.x+vP[0],playerChar.y+vP[1],playerChar.lvl)!==undefined||whosThere(playerChar.x+vP[0],playerChar.y+vP[1],playerChar.lvl)!==undefined)return;
	if(!playerBlocked&&nextTileBlocked)return true;
};

var jumpInRay = function()
{
	var vP = dirVect(0,playerChar);
	if(!coordInGame(playerChar.x+vP[0],playerChar.y+vP[1],playerChar.lvl))return;
    if(playerChar.behindPilar&&playerChar.lvl>0)return;
	// var playerBlocked = playerChar.lvl===0&&rayCoord[rayCoord.myIndexOfArray([playerChar.x,playerChar.y,playerChar.lvl])][3]>0;
	// var nextTileBlocked = playerChar.lvl===0&&rayCoord[rayCoord.myIndexOfArray([playerChar.x+vP[0],playerChar.y+vP[1],playerChar.lvl])][3]>0;
	var playerBlocked = playerChar.lvl===0&&rayCoord[playerChar.x*$dataMap.height+playerChar.y]>=1;
	var nextTileBlocked = playerChar.lvl===0&&rayCoord[(playerChar.x+vP[0])*$dataMap.height+playerChar.y+vP[1]]>=1;
	if(botThere(playerChar.x+vP[0],playerChar.y+vP[1],playerChar.lvl)!==undefined||whosThere(playerChar.x+vP[0],playerChar.y+vP[1],playerChar.lvl)!==undefined)return;
	if(!playerBlocked&&nextTileBlocked)$gamePlayer.jump_forward(1);
	var lowestPilar=lowestPilarXY(playerChar.x+vP[0],playerChar.y+vP[1]);
	var playerBlocked = playerChar.lvl===1&&onPilar(playerChar)._characterName==="!dalleBlocked";
	var nextTileBlocked = playerChar.lvl===1&&lowestPilar!==undefined&&lowestPilar._characterName==="!dalleBlocked";
	if(botThere(playerChar.x+vP[0],playerChar.y+vP[1],playerChar.lvl)!==undefined||whosThere(playerChar.x+vP[0],playerChar.y+vP[1],playerChar.lvl)!==undefined)return;
	if(!playerBlocked&&nextTileBlocked)$gamePlayer.jump_forward(1);
};

var myJumpPassibility = function(x,y,l)
{
	var vP = dirVect(0,playerChar);
	var lowestPilar = lowestPilarXY(playerChar.x,playerChar.y);
	var nextPilar = lowestPilarXY(x,y);
	var playerBlocked = (l===0&&rayCoord[playerChar.x*$dataMap.height+playerChar.y]>=1)||(l===1&&lowestPilar!==undefined&&lowestPilar._characterName==="!dalleBlocked");
	if(!coordInGame(x,y,l))return false;
	if(x<2||x>20)return false;
	if(l===1&&nextPilar===undefined)return false;
	if(playerBlocked)return false;
	if((whosThere(x,y,l)||whatsThere(x,y,l)||botThere(x,y,l))!==undefined&&l===0)return false;
	if((whosThere(x,y,l)||botThere(x,y,l))!==undefined&&l===1)return false;
	return true;
};

var fCanJumpFront = function()
{
	var vP = dirVect(0,playerChar);
	if(!playerChar.canJump||(playerChar.behindPilar&&playerChar.lvl>0))return false;
	if(playerChar.lvl === 0 && fHoleNear(playerChar,1,0) && !fHoleNear(playerChar,2,0) && !fCharNear(playerChar,2,0) && myJumpPassibility(playerChar.x+2*vP[0],playerChar.y+2*vP[1],playerChar.lvl))return true;
	if(playerChar.lvl === 1 && !fCharNear(playerChar,1,0)&& !cMyPassibility(playerChar.x+vP[0],playerChar.y+vP[1],playerChar.lvl) && myJumpPassibility(playerChar.x+2*vP[0],playerChar.y+2*vP[1],playerChar.lvl))return true;
	return false;
}

var fCanAssistJumpFront = function()
{
		if(!playerChar.canJump)return false;
		var charAhead;
		charAhead = fCharNear(playerChar,1,0);
		if(charAhead===undefined||(charAhead.behindPilar&&charAhead.lvl>0))return false;
		var playerBlocked = charAhead!==undefined&&charAhead.lvl===0&&rayCoord[charAhead.x*$dataMap.height+charAhead.y]>=1;
		playerBlocked = playerBlocked||(charAhead.lvl===1&&onPilar(charAhead)._characterName==="!dalleBlocked");
		var vC = (charAhead !== undefined)?dirVect(0,charAhead):undefined;
		if(playerChar.lvl === 0 && charAhead!==undefined && !playerBlocked && fHoleNear(charAhead,1,0) && !fHoleNear(charAhead,2,0) && !fCharNear(charAhead,2,0) && myJumpPassibility(charAhead.x+2*vC[0],charAhead.y+2*vC[1],playerChar.lvl))return true;
		if(playerChar.lvl === 1 && charAhead !== undefined && !playerBlocked && !cMyPassibility(charAhead.x+vC[0],charAhead.y+vC[1],playerChar.lvl) && !fCharNear(charAhead,1,0) && myJumpPassibility(charAhead.x+2*vC[0],charAhead.y+2*vC[1],playerChar.lvl,charAhead))return true;
		return false;
}

var fSetTile = function(tile,x,y)
{
if(tile.isSet)
{
	fSetTile(nextTile(tile));
	return;
}
var id;
switch(tile){
case blueTile: id=0;
case purpleTile: id=1;
case greenTile: id=2;
case yellowTile: id=3;
};
	var image = tile.image;
	allowSwap=false;
	if(playerChar.active)
	{
		$gameMap.event(playerChar.eventId()).forceMoveRoute({list:[{code: 0}],repeat:false,skippable:true,wait:false});
		$gameMap.event(playerChar.eventId()).setMoveSpeed(4);
		$gameMap.event(playerChar.eventId()).setDirection($gamePlayer.direction());
		$gameMap.event(playerChar.eventId()).setPosition($gamePlayer.x, $gamePlayer.y);
		$gameMap.event(playerChar.eventId()).setTransparent(false);
		$gameMap.event(playerChar.eventId()).setThrough(false);
	 }
	blueChar.active = false;
	purpleChar.active = false;
	greenChar.active = false;
	yellowChar.active = false;
 	playerChar.active = false;
 	tile.set_frame(image[0],image[1],image[2],image[3]);
 	//$gameActors.actor(1).setCharacterImage("", 0);
 	//$gamePlayer.reserveTransfer($gameMap.mapId(), 11, 3, 0, 2);
 	$gamePlayer.setPosition(11,3);
	$gamePlayer._characterName="";
	//$gamePlayer._characterIndex=chara.characterIndex()
 	tile.setThrough(true);
 	tile.setMoveSpeed(6);
 	(!tileControl||x===undefined)?tile.setPosition(11,3):tile.setPosition(x,y);
 	$gamePlayer.setMoveSpeed(6);
 	$gamePlayer.setThrough(true);
 	tile.forceMoveRoute({
			list:[{
			code: 35,
			indent: null,
			parameters:[]
			},{
			code: 45,
			indent: null,
			parameters:["if(TouchInput.isPressed() && touchInGame(TouchInput.x,TouchInput.y))this.setPosition(Math.floor(TouchInput.x/48),Math.floor(TouchInput.y/48));"]
			},{
			code: 45,
			indent: null,
			parameters:["if(allowMove){if(Input.isPressed('up')){this.moveStraight(8)}else if(Input.isPressed('left')){this.moveStraight(4)}else if(Input.isPressed('right')){this.moveStraight(6)}else if(Input.isPressed('down')){this.moveStraight(2)}}"]
			},{				
			code: 0,
			indent: null,
			parameters:[]
			}],
			repeat:true,
			skippable:true,
			wait:false
			});
 	tile.active=true;
}

var touchInGame=function(x,y)
{
	var x1=Math.floor(x/48);
	var y1=Math.floor(y/48);
	if(x1<21&&x1>1&&y1>2&&myTileId(x1,y1)===11)return true;
	return false;
}

var coordInGame=function(x,y,l)
{
	if(x<23&&x>=0&&y>=3&&y<13&&l===0)return true;
	if(x<23&&x>=0&&y>=0&&y<13&&l===1)return true;
	return false;
}

var fSetNextTile = function()
{
var tile = (blueTile.active)?blueTile:(purpleTile.active)?purpleTile:(greenTile.active)?greenTile:(yellowTile.active)?yellowTile:undefined;
if(tile===nextTile(tile))return;
tile.set_frame(tile.image[0],4,2,2);
tile.forceMoveRoute({list:[{code: 0}],repeat:false,skippable:true,wait:false});
fSetTile(nextTile(tile),tile.x,tile.y);
tile.setPosition(0,0);
tile.active=false;
}

var fSetPreviousTile = function()
{
var tile = (blueTile.active)?blueTile:(purpleTile.active)?purpleTile:(greenTile.active)?greenTile:(yellowTile.active)?yellowTile:undefined;
if(tile===previousTile(tile))return;
tile.set_frame(tile.image[0],4,2,2);
tile.forceMoveRoute({list:[{code: 0}],repeat:false,skippable:true,wait:false});
fSetTile(previousTile(tile),tile.x,tile.y);
tile.setPosition(0,0);
tile.active=false;
}
var settingChar;
var fCancelSetTile = function()
{
var tile = (blueTile.active)?blueTile:(purpleTile.active)?purpleTile:(greenTile.active)?greenTile:(yellowTile.active)?yellowTile:undefined;
tile.set_frame(tile.image[0],4,2,2);
tile.forceMoveRoute({list:[{code: 0}],repeat:false,skippable:true,wait:false});
tile.setPosition(0,0);
tileControl=false;
tile.active=false;
allowSwap=true;
var charSwapping = (purpleChar.exit)?blueChar:purpleChar;
swapChar(charSwapping);
$gameTemp.reserveCommonEvent(13);
}

var fConfirmSetTile = function()
{
var tile = (blueTile.active)?blueTile:(purpleTile.active)?purpleTile:(greenTile.active)?greenTile:(yellowTile.active)?yellowTile:undefined;
if (myTileId(tile.x,tile.y) !== 11)return;
localSave();
if(fCheckSlot(blueTile,tile.x,tile.y)||fCheckSlot(purpleTile,tile.x,tile.y)||fCheckSlot(greenTile,tile.x,tile.y)||fCheckSlot(yellowTile,tile.x,tile.y))return;
tile.forceMoveRoute({list:[{code: 0}],repeat:false,skippable:true,wait:false});
tile.active=false;
tile.isSet = true;
tile.setThrough(false);
tile.orig_x=tile.x;
tile.orig_y=tile.y;
cCountFreeSlot--;
switch(tile){
case blueTile: 
$dataMap.data[(2*$dataMap.height+tile.y)*$dataMap.width+tile.x]=1;
$dataMap.data[(3*$dataMap.height+tile.y)*$dataMap.width+tile.x]=19;
break;
case purpleTile:
$dataMap.data[(2*$dataMap.height+tile.y)*$dataMap.width+tile.x]=1;
$dataMap.data[(3*$dataMap.height+tile.y)*$dataMap.width+tile.x]=27;
break;
case greenTile: 
$dataMap.data[(2*$dataMap.height+tile.y)*$dataMap.width+tile.x]=1;
$dataMap.data[(3*$dataMap.height+tile.y)*$dataMap.width+tile.x]=35;

break;
case yellowTile: 
$dataMap.data[(2*$dataMap.height+tile.y)*$dataMap.width+tile.x]=1;
$dataMap.data[(3*$dataMap.height+tile.y)*$dataMap.width+tile.x]=43;
break;
};
if(!allTilesSet()&&cCountFreeSlot>0)
{
fSetTile(nextTile(tile));
}else
{
tileControl=false;
$gameSystem.enableMenu();
allowSwap=true;
var charSwapping = (purpleChar.exit)?blueChar:purpleChar;
swapChar(charSwapping);
}
}

var fCheckSlot=function(tile,x,y)
{
	if(tile.isSet && tile.x === x && tile.y === y)return true;
	return false;
}

var testSwapChar = function()
{
    if(playerChar.lvl===0&&onTile(playerChar)===playerChar.ownTile)
    {
        if(playerChar!==blueChar&&blueChar.lvl===0&&onTile(blueChar)===blueTile)return true;
        if(playerChar!==purpleChar&&purpleChar.lvl===0&&onTile(purpleChar)===purpleTile)return true;
        if(playerChar!==greenChar&&greenChar.lvl===0&&onTile(greenChar)===greenTile)return true;
        if(playerChar!==yellowChar&&yellowChar.lvl===0&&onTile(yellowChar)===yellowTile)return true;
    };
    return false;
}

var onTile = function(chara)
{
	var tiles = [blueTile,purpleTile,greenTile,yellowTile];
	var tile;
	for(var i=0; i<tiles.length;i++)
	{
		if(tiles[i].x===chara.x && tiles[i].y-tiles[i].lvl===chara.y && (tiles[i].lvl === chara.lvl || tiles[i].lvl*chara.lvl!==0))
		{if((chara.behindPilar&&tiles[i]!==PilarsXY(chara.x,chara.y)[0])||(!chara.behindPilar&&tiles[i]===PilarsXY(chara.x,chara.y)[0])||tiles[i].lvl===0)
			{tile=tiles[i];
				break;}
		}
	}
	return tile;
};

var onPilar = function(chara)
{
	var tiles = allPilars;
	var tile;
	for(var i=0; i<tiles.length;i++)
	{
		if(tiles[i].x===chara.x && tiles[i].y-tiles[i].lvl===chara.y && (tiles[i].lvl === chara.lvl || tiles[i].lvl*chara.lvl!==0))
		{if((chara.behindPilar&&tiles[i]!==PilarsXY(chara.x,chara.y)[0])||(!chara.behindPilar&&tiles[i]===PilarsXY(chara.x,chara.y)[0])||tiles[i].lvl===0)
			{tile=tiles[i];
				break;}
		}
	}
	return tile;
};

var tileToChar = function(tile)
{
	switch(tile)
	{
		case blueTile:
		return blueChar;
		break;
		case purpleTile:
		return purpleChar;
		break;
		case greenTile:
		return greenChar;
		break;
		case yellowTile:
		return yellowChar;
		break;
	}
};

var nameToChar = function(name)
{
	switch(name)
	{
		case 'blue':
		return blueChar;
		break;
		case 'purple':
		return purpleChar;
		break;
		case 'green':
		return greenChar;
		break;
		case "yellow":
		return yellowChar;
		break;
	}
};

var moveTileTest = function()
{
	var tile = onTile(playerChar);
	var pilar = onPilar(playerChar);
	if(tileSelection||tileControl)return false;
	if(pilar!==undefined && pilar.express &&pilar.lvl>0)return true;
	if(tile!==undefined && onSwitch(tileToChar(tile)))return true;
	if(onSwitch(playerChar)&&playerChar.ownTile.isSet)return true;
	return false;
};

var onSwitch = function(chara)
{
	if(/*playerChar.active &&*/ chara.x === chara.ownSwitch.x && chara.y === (chara.ownSwitch.y-chara.ownSwitch.lvl) && ((chara.lvl===0&&chara.ownSwitch.lvl===0)||(chara.lvl>0 &&chara.ownSwitch.lvl>0)))return true;
	return false;
};

var whosThere = function(x,y,l)
{
	for(var i=0; i<cArrayTeamMembers.length ;i++){
		if(cArrayTeamMembers[i].x===x&&cArrayTeamMembers[i].y===y&&cArrayTeamMembers[i].lvl===l)return cArrayTeamMembers[i];}
}

var botThere = function(x,y,l)
{
	var evId = $gameMap.eventIdXy(x,y);
	if(evId>0 && $dataMap.events[evId]!==undefined&&$dataMap.events[evId].name.match(/bot/) && $gameMap.event(evId).lvl===l)return $gameMap.event(evId);
};

var whatsThere = function(x,y,l)
{
	var pilarId = $gameMap.eventIdXy(x,y);
	if(pilarId===0)return;
	var pilar = (allPilars.indexOf($gameMap.event(pilarId))>-1)?$gameMap.event(pilarId):undefined;
	if(pilar!==undefined&&pilar.lvl>l)return pilar;
	for(var i=0; i<allPilars.length; i++){
	if(allPilars[i].x===x&&allPilars[i].y===y&&allPilars[i].lvl>l)return allPilars[i];}
}

var moveTileUp = function(v,paramPilar)
{
	pilar = paramPilar||(onPilar(playerChar).express)?onPilar(playerChar):undefined;
	tile=paramPilar||onTile(playerChar)||pilar||playerChar.ownTile;
	if(onPilar(playerChar)!==undefined && onPilar(playerChar).express)return;
	if(tileMoving||$gamePlayer.isMoving())return;
	var bot = botThere(tile.x,tile.y-tile.lvl,Math.min(tile.lvl,1));
	var testBot = bot!==undefined && tile===onPilar(bot);
	charOn = whosThere(tile.x,tile.y-tile.lvl,(tile.lvl===0)?0:1);
	if(charOn!==undefined&&(whosThere(tile.x,tile.y-tile.lvl-1,1)!==undefined||botThere(tile.x,tile.y-tile.lvl-1,1)!==undefined))return;
	charOn = (charOn!==undefined && (charOn._priorityType===tile._priorityType+((charOn.behindPilar)?1:5)||tile.lvl===0))?charOn:undefined;
	charOn = charOn||((testBot)?bot:undefined);
	switch(tile.direction()){
	case 2:
	tile.newDir = 4;
	break;
	case 4:
	tile.newDir = 6;
	break;
	case 6:
	tile.newDir = 8;
	break;
	case 8:
	return;
	break;
}
setAllPilarsTransp(0);
tile.setOpacity(255);
	tileMoving=true;
	cacheFunction(tile.x,tile.y+1);
	cacheTile.setPosition(tile.x,tile.y+1);
	cacheTile.setTransparent(false);
	tile.setMoveSpeed((tile.express)?7:v);
	tile.setThrough(true);
	cUpdatePos();
	tile.setPriorityType(tile.y);
	tile.setDirectionFix(true);
	cacheTile.setPriorityType(tile._priorityType);
	if(charOn !== undefined&&charOn!==bot)	
	{		
		charOn.cantMove=false;
		charOn._priorityType=tile._priorityType+1;
		charOn.fixPriority=true;
		if(PilarsXY(charOn.x,charOn.y-1).length>0)
			{
				highPilar=PilarsXY(charOn.x,charOn.y-1)[0];
				lowPilar=PilarsXY(charOn.x,charOn.y-1)[PilarsXY(charOn.x,charOn.y-1).length-1];
				charOn.behindPilar = (highPilar.y-highPilar.lvl<charOn.y&&highPilar.y>tile.y)?true:false;
				charOn.cantMove = (highPilar.y-highPilar.lvl===charOn.y-1&&highPilar.y>tile.y)?true:false;
			}
			charOn.fixPriority=true;
			charOn.lvl=1;

	};
	tile.lvl++;
	tile.setPosition(tile.x,tile.y+1);
	tile.set_frame(tile.image[0],tile.image[1],tile.image[2],tile.newDir);
	//charOn=(testBot)?bot:charOn;
	//if(charOn!==undefined&&charOn===bot)charOn.setPriorityType(charOn.y+5);
	if(charOn !== undefined)
		{
			charOn.setThrough(true);
			charOn.setMoveSpeed(tile.moveSpeed());
			charOn.setDirectionFix(true);
			charOn.setWalkAnime(false);
			charOn.lvl=1;
			if(tile.express)
			{
				charOn.setTransparent(false);
				playerChar.active=false;
				$gamePlayer.setTransparent(true);
			};
			charOn.forceMoveRoute({
			list:[{
			code: 4,
			indent: null,
			parameters:[]
			},{
			code: 45,
			indent: null,
			parameters:["charOn.fixPriority=false;"]
			},{
			code: 38,
			indent: null,
			parameters:[]
			},{
			code: 0,
			indent: null,
			parameters:[]
			}],
			repeat:false,
			skippable:true,
			wait:false
			});
		};

	tile.forceMoveRoute({
			list:[{
			code: 45,
			indent: null,
			parameters:["if(!tile.express)AudioManager.playSe({name: 'Earth4', volume: 30, pitch: 100, pan: 0});"]
			},{
			code: 4,
			indent: null,
			parameters:[]
			},{
			code: 38,
			indent: null,
			parameters:[]
			},{
			code: 15,
			indent: null,
			parameters:[5]
			},{
			code: 45,
			indent: null,
			parameters:["tileMoving=false;cacheTile.setTransparent(true);if(tile.express)tile.down=false;botRay();drawBlockingTiles();"]
			},{
			code: 0,
			indent: null,
			parameters:[]
			}],
			repeat:false,
			skippable:true,
			wait:false
			});

	if(tile.express)return;
	switch(tile.newDir){
	case 2:
	$dataMap.data[(3*$dataMap.height+tile.orig_y)*$dataMap.width+tile.orig_x]=tile.id[0];
	break;
	case 4:
	$dataMap.data[(3*$dataMap.height+tile.orig_y)*$dataMap.width+tile.orig_x]=tile.id[1];
	break;
	case 6:
	$dataMap.data[(3*$dataMap.height+tile.orig_y)*$dataMap.width+tile.orig_x]=tile.id[2];
	break;
	case 8:
	$dataMap.data[(3*$dataMap.height+tile.orig_y)*$dataMap.width+tile.orig_x]=tile.id[3];
	break;
	}
};

var kk;
var stateEye;
setAllPilarsTransp = function(param)
{
	if(!allowPilarTransp)return;
	stateEye = (param!==undefined)?param:((stateEye===0)?3:(stateEye-1)%4);
	kk = (stateEye===0)?255:(0);
	for(var i=0; i<allPilars.length;i++)
	{
		if(/*allPilars[i].lvl>0&&*/(allPilars[i].lvl>=stateEye||stateEye===0)&&!allPilars[i].down)
		{	
			allPilars[i].setOpacity(kk);
			// allPilars[i].forceMoveRoute({
			// list:[{
			// code: 45,
			// indent: null,
			// parameters:["if(this.opacity()+ (" + String(kk) + ")>=0 && this.opacity()+ (" + String(kk) + ")<=255){this.setOpacity(this.opacity() + (" + String(kk) + "));}else{$gameSwitches.setValue(4,true);}"]
			// },{
			// code: 15,
			// indent: null,
			// parameters:[1]
			// },{
			// code: 0,
			// indent: null,
			// parameters:[]
			// }],
			// repeat:true,
			// skippable:true,
			// wait:true
			// });
		};
	};
// var tM = [blueChar,purpleChar,greenChar,yellowChar];
// var tM2 = [blue2,purple2,green2,yellow2]
// var pilar;
// 	for(var i=0; i<tM.length;i++)
// 	{
// 		if(tM[i].lvl>0)
// 			{
// 				pilar = onPilar2(tM[i])[0];
// 				// tM2[i].set_frame();
// 				if(pilar!==undefined)tM2[i].setPosition(pilar.x,pilar.y);
// 				tM2[i].setOpacity(255-o);
// 				tM[i].setOpacity(o);
// 			};
// 	};
// if(playerChar.lvl>0)$gamePlayer.setOpacity(o);
}

var tileMoving = false;
var charMoving = false;
var moveTileDown = function(v,paramPilar)
{
	if(onPilar(playerChar)===undefined && !onSwitch(playerChar))return;
	pilar = (onPilar(playerChar).express)?onPilar(playerChar):undefined;
	tile=paramPilar||onTile(playerChar)||pilar||playerChar.ownTile;
	var bot = botThere(tile.x,tile.y-tile.lvl,Math.min(tile.lvl,1));
	var testBot = bot!==undefined && tile===onPilar(bot);
	if(tile.express&&!tileMovingExpress&&tile.lvl>0)tileMovingExpress=true;
	if(tileMoving||$gamePlayer.isMoving())return;
	charOn = whosThere(tile.x,tile.y-tile.lvl,(tile.lvl===0)?0:1);
	if(whosThere(tile.x,tile.y-tile.lvl+1,1)!==undefined&&whosThere(tile.x,tile.y-tile.lvl+1,1).behindPilar)return;

	charOn = (charOn!==undefined && charOn._priorityType===tile._priorityType+((charOn.behindPilar)?1:5))?charOn:undefined;
	switch(tile.direction()){
	case 2:
	return;
	break;
	case 4:
	tile.newDir = 2;
	break;
	case 6:
	tile.newDir = 4;
	break;
	case 8:
	tile.newDir = 6;
	break;
}
setAllPilarsTransp(0);
tile.setOpacity(255);
	tileMoving=true;
	cacheFunction(tile.x,tile.y+1);
	cacheTile.setPosition(tile.x,tile.y+1);
	cacheTile.setTransparent(false);
	cacheTile.setPriorityType(tile._priorityType);
	tile.setMoveSpeed((tile.express)?7:v);
	tile.setThrough(true);
	tile.setDirectionFix(true);
	if(charOn !== undefined)
	{		
		charOn._priorityType=tile._priorityType+1;
		charOn.fixPriority=true;
		if(PilarsXY(charOn.x,charOn.y+1).length>0)
			{

				highPilar=PilarsXY(charOn.x,charOn.y+1)[0];
				lowPilar=PilarsXY(charOn.x,charOn.y+1)[PilarsXY(charOn.x,charOn.y+1).length-1];
				charOn.behindPilar = (highPilar.y-highPilar.lvl<=charOn.y+1&&highPilar.y>tile.y)?true:false;
				charOn.cantMove = (highPilar.y-highPilar.lvl===charOn.y+1&&tile.newDir!==2)?true:false;
				cUpdatePos();
				charOn.fixPriority=true;

			}
	};
	charBelow =whosThere(tile.x,tile.y-tile.lvl,(tile.lvl===0)?0:1);
	if(charOn===undefined&&charBelow!==undefined){charBelow.cantMove=false;charBelow.fixPriority=true;charBelow.behindPilar=false;}
	cUpdatePos();
	charMoving=true;
	charOn=(testBot)?bot:charOn;
	if(charOn !== undefined)
		{
			charOn.setThrough(true);
			charOn.setMoveSpeed(tile.moveSpeed());
			charOn.setDirectionFix(true);
			charOn.setWalkAnime(false);
			cUpdatePos();
			if(tile.express)
			{
				charOn.setTransparent(false);
				playerChar.active=false;
				$gamePlayer.setTransparent(true);
			};

			charOn.forceMoveRoute({
			list:[{
			code: 1,
			indent: null,
			parameters:[]
			},{
			code: 38,
			indent: null,
			parameters:[]
			},{
			code: 45,
			indent: null,
			parameters:["charOn.lvl= (tile.newDir===2)?0:1;charOn.fixPriority=false;charMoving = false;"]
			},{
			code: 0,
			indent: null,
			parameters:[]
			}],
			repeat:false,
			skippable:true,
			wait:false
			});
		};
	tile.forceMoveRoute({
			list:[{
			code: 45,
			indent: null,
			parameters:["if(!tile.express)AudioManager.playSe({name: 'Earth4', volume: 30, pitch: 100, pan: 0});"]
			},{
			code: 1,
			indent: null,
			parameters:[]
			},{
			code: 38,
			indent: null,
			parameters:[]
			},{
			code: 45,
			indent: null,
			parameters:["tile.set_frame(tile.image[0],tile.image[1],tile.image[2],tile.newDir);tile.setPosition(tile.x,tile.y-1);if(tile.newDir===2){tile.setPriorityType(0);tileMovingExpress=false;};tile.lvl --;if(charBelow!==undefined)charBelow.fixPriority=false;"]
			},{
			code: 15,
			indent: null,
			parameters:[5]
			},{
			code: 45,
			indent: null,
			parameters:["tileMoving=false;cacheTile.setTransparent(true);if(tile.express)tile.down=true;botRay();drawBlockingTiles();"]
			},{
			code: 0,
			indent: null,
			parameters:[]
			}],
			repeat:false,
			skippable:true,
			wait:false
			});
		// if(tile.express)
		// {
		// 	// $gameMessage.add("ok");
		// 	tile.forceMoveRoute({
		// 	list:[{
		// 	code: 45,
		// 	indent: null,
		// 	parameters:["if(whosThere(this.x,this.y,0)===undefined&&tile.lvl===0){tempPilar1===this;$gameTemp.reserveCommonEvent(11);}"]
		// 	},{
		// 	code: 0,
		// 	indent: null,
		// 	parameters:[]
		// 	}],
		// 	repeat:true,
		// 	skippable:true,
		// 	wait:false
		// 	});}
	if(tile.express)return;
	switch(tile.newDir){
	case 2:
	$dataMap.data[(3*$dataMap.height+tile.orig_y)*$dataMap.width+tile.orig_x]=tile.id[0];
	break;
	case 4:
	$dataMap.data[(3*$dataMap.height+tile.orig_y)*$dataMap.width+tile.orig_x]=tile.id[1];
	break;
	case 6:
	$dataMap.data[(3*$dataMap.height+tile.orig_y)*$dataMap.width+tile.orig_x]=tile.id[2];
	break;
	case 8:
	$dataMap.data[(3*$dataMap.height+tile.orig_y)*$dataMap.width+tile.orig_x]=tile.id[3];
	break;
}
};

var cacheFunction = function(x,y)
{
	switch(myTileId(x,y))
	{
		case 1:
		cacheTile.set_frame("!cache",1,1,2);
		break;
		case 2:
		cacheTile.set_frame("!cache",1,2,2);
		break;
		case 3:
		cacheTile.set_frame("!cache",1,3,2);
		break;
		case 11:
		cacheTile.set_frame("!cache",2,1,2);
		break;

		case 4:
		cacheTile.set_frame("!cache",1,1,4);
		break;
		case 5:
		cacheTile.set_frame("!cache",1,2,4);
		break;
		case 6:
		cacheTile.set_frame("!cache",1,3,4);
		break;
		case 7:
		cacheTile.set_frame("!cache",2,1,4);
		break;
	}
}
var mapNumber = 1;
var exitChar = function()
{
    chara = playerChar;
    localSave(chara.name);
	chara.exit = true;
	if(chara!==blueChar&&blueChar.cameleon)
	{
		blueChar.canSetTile=blueChar.canSetTile||chara.canSetTile;
		blueChar.canJump=blueChar.canJump||chara.canJump;
		blueChar.canAvoidBot=blueChar.canAvoidBot||chara.canAvoidBot;
	}
	chara.setTransparent(true);
	chara.setPosition(0,0);
	chara.forceMoveRoute({list:[{code: 0}],repeat:false,skippable:true,wait:false});
	blueChar.active = false;
	purpleChar.active = false;
	greenChar.active = false;
	yellowChar.active = false;
 	playerChar.active = false;
 	$gameActors.actor(1).setCharacterImage("", 0);
 	$gamePlayer._characterName="";
 	// $gamePlayer.reserveTransfer($gameMap.mapId(), 0, 0, 0, 2);
 	$gamePlayer.setPosition(0,0);
    playerChar.setPosition(0,0);
 	nbOfChar--;
 	if(blueChar.exit && purpleChar.exit && greenChar.exit && yellowChar.exit)
 		{
 			mapNumber++;
 			$gameVariables.setValue(2,Math.max($gameVariables.value(2),mapNumber));
 			// $gameSwitches.setValue(6,false);
 			// $gameSwitches.setValue(7,false);
 			DataManager.saveGame(1);
 			wallDown.cActive=false;
 			$gameSwitches.setValue(3,false);
 			$gamePlayer.reserveTransfer(mapOrder[mapNumber], 0, 0, 0, 0);
 		}
 	if(!blueChar.exit){swapChar(blueChar)}else if(!purpleChar.exit){swapChar(purpleChar)}else if(!greenChar.exit){swapChar(greenChar)}else {swapChar(yellowChar)};
}

var sortNumber = function(a,b){
	return a-b;
}

var closestChar=function(x,y)
{
	var distBlue = Math.sqrt(Math.pow(blueChar.x*48+24-x,2)+Math.pow(blueChar.y*48+24-y,2));
	var distPurple = Math.sqrt(Math.pow(purpleChar.x*48+24-x,2)+Math.pow(purpleChar.y*48+24-y,2));
	var distGreen = Math.sqrt(Math.pow(greenChar.x*48+24-x,2)+Math.pow(greenChar.y*48+24-y,2));
	var distYellow = Math.sqrt(Math.pow(yellowChar.x*48+24-x,2)+Math.pow(yellowChar.y*48+24-y,2));
	var minDist = Math.min(distBlue,distPurple,distGreen,distYellow);
	if(minDist>50)return;
	switch(minDist)
	{
		case distBlue:
		return blueChar;
		break;
		case distPurple:
		return purpleChar;
		break;
		case distGreen:
		return greenChar;
		break;
		case distYellow:
		return yellowChar;
		break;
	}
};

var distance = function(a,b,c,d)
{
	return Math.sqrt(Math.pow(a-c,2)+Math.pow(b-d,2));
}

var onPilar2 = function(chara)
{
	onPilars=[];
	lowest = whatsThere(chara.x,chara.y+3,0);
	middle = whatsThere(chara.x,chara.y+2,0);
	highest = whatsThere(chara.x,chara.y+1,0);
	if(lowest!==undefined&&chara.y===lowest.orig_y-lowest.lvl)onPilars.push(lowest);
	if(middle!==undefined&&chara.y===middle.orig_y-middle.lvl)onPilars.push(middle);
	if(highest!==undefined&&chara.y===highest.orig_y-highest.lvl)onPilars.push(highest);
return onPilars;
};

var PilarsXY = function(x,y)
{
	Pilars=[];
	lowest = whatsThere(x,y+3,0);
	middle = whatsThere(x,y+2,0);
	highest = whatsThere(x,y+1,0);
	highest2 = whatsThere(x,y,0);
	if(lowest!==undefined&&lowest.y-lowest.lvl<=y)Pilars.push(lowest);
	if(middle!==undefined&&middle.y-middle.lvl<=y)Pilars.push(middle);
	if(highest!==undefined&&highest.y-highest.lvl<=y)Pilars.push(highest);
return Pilars;
};

var lowestPilarXY = function(x,y)
{
	lowest = whatsThere(x,y+3,0);
	middle = whatsThere(x,y+2,0);
	highest = whatsThere(x,y+1,0);
	if(lowest!==undefined&&lowest.y-lowest.lvl===y)return lowest;
	if(middle!==undefined&&middle.y-middle.lvl===y)return middle;
	if(highest!==undefined&&highest.y-highest.lvl===y)return highest;
};

var charOnPilar = function(pilar)
{
	return whosThere(pilar.x,pilar.y-pilar.lvl,1);
};


var oldTransfer = Game_Player.prototype.performTransfer;

var newTransfer = function() {
    if (this.isTransferring()) {
        this.setDirection(this._newDirection);

            $gameMap.setup(this._newMapId);
            this._needsMapReload = false;

        this.locate(this._newX, this._newY);
        this.refresh();
        this.clearTransferInfo();
    }
};

var setRetry = function()
{
	$gameTemp.reserveCommonEvent(15);
};

// function readTextFile(file)
// {
//     var rawFile = new XMLHttpRequest();
//     rawFile.open("GET", file, false);
//     rawFile.onreadystatechange = function ()
//     {
//         if(rawFile.readyState === 4)
//         {
//             if(rawFile.status === 200 || rawFile.status == 0)
//             {
//                 var allText = rawFile.responseText;
//                 alert(allText);
//             }
//         }
//     }
//     rawFile.send(null);
// }

// DataManager.loadMapData = function(mapId) {
//     if (mapId > 0) {
//         var filename = 'Map%1.json'.format(mapId.padZero(3));
//         (mapId === 1)?this.loadDataFile('$dataMap', 'Map011.json'):this.loadDataFile('$dataMap', filename);
//     } else {
//         this.makeEmptyMap();
//     }
// };

Game_Player.prototype.isDebugThrough = function() {
 //   return Input.isPressed('control') && $gameTemp.isPlaytest();
};

var testExchangeChar = function()
{
	var charas=[blueChar, purpleChar, greenChar, yellowChar];
	var test1=false;
	for(var i = 0; i<charas.length; i++)
	{
		if(charas[i]!==playerChar && charas[i].canExchange)test1=true;
	}
	if(playerChar.canExchange && test1)return true;
};

// var exchangeChar = function(char1, char2)
// {
// 	var x0 = char1.x;
// 	var y0 = char1.y;
// 	char1.setPosition(char2.x,char2.y);
// 	$gamePlayer.setPosition(char2.x,char2.y);
// 	char2.setPosition(x0,y0);
// };

var exchangeSelection;

var firstExchange = function()
{
exchangeSelection = (blueChar.canExchange && playerChar!==blueChar)?blueChar:
					(purpleChar.canExchange && playerChar!==purpleChar)?purpleChar:
					(greenChar.canExchange && playerChar!==greenChar)?greenChar:
					(yellowChar.canExchange && playerChar!==yellowChar)?yellowChar:undefined;
return exchangeSelection; 
};

var nextExchange = function()
{
	if(exchangeSelection === undefined) return firstExchange();
	switch(exchangeSelection)
	{
		case blueChar:
		exchangeSelection = (purpleChar.canExchange)?purpleChar:(greenChar.canExchange)?greenChar:(yellowChar.canExchange)?yellowChar:blueChar;
		return exchangeSelection;
		break;
		case purpleChar:
		exchangeSelection = (greenChar.canExchange)?greenChar:(yellowChar.canExchange)?yellowChar:(blueChar.canExchange)?blueChar:purpleChar;
		return exchangeSelection;
		break;
		case greenChar:
		exchangeSelection = (yellowChar.canExchange)?yellowChar:(blueChar.canExchange)?blueChar:(purpleChar.canExchange)?purpleChar:greenChar;
		return exchangeSelection;
		break;
		case yellowChar:
		exchangeSelection = (blueChar.canExchange)?blueChar:(purpleChar.canExchange)?purpleChar:(greenChar.canExchange)?greenChar:yellowChar;
		return exchangeSelection;
		break;
	};
};

var hideTiles = function()
{
	for(var x=0; x<$dataMap.width;x++)
	{
		for(var y=0; y<$dataMap.height;y++)
		{
			if($gameMap.tileId(x,y,3)===75)
			{
				tilesToReveal.push([x,y]);
				$dataMap.data[(3*$dataMap.height+y)*$dataMap.width+x]=3;
				$dataMap.data[(2*$dataMap.height+y)*$dataMap.width+x]=$gameMap.tileId(x,y,2);
			};
		};
	};
};

var revealTiles = function()
{
	var x;
	var y;
		for(var i=0; i<tilesToReveal.length;i++)
		{
				x=tilesToReveal[i][0];
				y=tilesToReveal[i][1];
				$dataMap.data[(3*$dataMap.height+y)*$dataMap.width+x]=$dataMap.data[(2*$dataMap.height+y)*$dataMap.width+x];
		};
};

var tileMovingTrain=false;

var testTrain = function(pilar,dir)
{
    if(dir===6&&whatsThere(pilar.x+1,pilar.y,0)===undefined&&pilar.x<20&&[1].indexOf($dataMap.data[(3*$dataMap.height+pilar.y)*$dataMap.width+pilar.x+1])<0)return true;
    if(dir===4&&whatsThere(pilar.x-1,pilar.y,0)===undefined&&pilar.x>2&&[1].indexOf($dataMap.data[(3*$dataMap.height+pilar.y)*$dataMap.width+pilar.x-1])<0)return true;
    return false;
}
var moveTileRight = function()
{
	var pilar = onPilar(playerChar);
	tileMovingTrain=true;
	pilar.setMoveSpeed($gamePlayer.moveSpeed());
	pilar.setThrough(true);
	var maxLength=0;
	$gamePlayer.setThrough(true);
	$gamePlayer.setDirectionFix(true);
	$gamePlayer.setWalkAnime(false);
    cacheTile.setPosition(pilar.x,pilar.y);
    cacheTile.set_frame('!cache',1,3,2);
	$dataMap.data[(3*$dataMap.height+pilar.y)*$dataMap.width+pilar.x]=3;

			 	pilar.forceMoveRoute({
				list:[/*{
				code: 15,
				indent: null,
				parameters:[1]
				},*/
				{
				code: 45,
				indent: null,
				parameters:["if(whatsThere(this.x+1,this.y,0)===undefined&&this.x<20&&[1].indexOf($dataMap.data[(3*$dataMap.height+this.y)*$dataMap.width+this.x+1])<0){this.stretched=true;AudioManager.playSe({name: 'Earth4', volume: 30, pitch: 100, pan: 0});this.moveStraight(6);$gamePlayer.moveStraight(6)}else{tileMovingTrain=false;$gamePlayer.setThrough(false);this.setThrough(false);$gamePlayer.setDirectionFix(false);$gamePlayer.setWalkAnime(true);$dataMap.data[(3*$dataMap.height+this.y)*$dataMap.width+this.x]=24;}"]
				},/*{
				code: 3,
				indent: null,
				parameters:[]
				},*/{
				code: 0,
				indent: null,
				parameters:[]
				}],
				repeat:true,
				skippable:true,
				wait:false
			});			
}

var updateDataMap=function(x,y)
{
    cacheTile.setPosition(x,y);
    cacheTile.set_frame('!cache',1,3,2);
    if([3,24,32].indexOf($dataMap.data[(3*$dataMap.height+y)*$dataMap.width+x])>0)$dataMap.data[(3*$dataMap.height+y)*$dataMap.width+x]=3;
};

var reinitTileRight = function()
{

onPilar(playerChar).forceMoveRoute({
list:[{
code: 45,
indent: null,
parameters:["if((whosThere(this.x,this.y-this.lvl,1)||botThere(this.x-1,this.y,0)||whatsThere(this.x-1,this.y,0))===undefined&&this.x>2&&[1].indexOf($dataMap.data[(3*$dataMap.height+this.y)*$dataMap.width+this.x-1])<0){updateDataMap(this.x,this.y);allowMove=false;AudioManager.playSe({name: 'Earth4', volume: 30, pitch: 100, pan: 0});this.moveStraight(4);tileMovingTrain=true;}else{if(tileMovingTrain)allowMove=true;tileMovingTrain=false;this.setThrough(false);if(whosThere(this.x,this.y-this.lvl,1)===undefined)stopEvent(this);$dataMap.data[(3*$dataMap.height+this.y)*$dataMap.width+this.x]=24;}"]},
{
code: 0,
indent: null,
parameters:[]}],
repeat:true,skippable:true,wait:false});
}

var moveTileLeft = function()
{
	var pilar = onPilar(playerChar);
	tileMovingTrain=true;
	pilar.setMoveSpeed($gamePlayer.moveSpeed());
	pilar.setThrough(true);
	var maxLength=0;
	$gamePlayer.setThrough(true);
	$gamePlayer.setDirectionFix(true);
	$gamePlayer.setWalkAnime(false);
    cacheTile.setPosition(pilar.x,pilar.y);
    cacheTile.set_frame('!cache',1,3,2);
    $dataMap.data[(3*$dataMap.height+pilar.y)*$dataMap.width+pilar.x]=3;

			 	pilar.forceMoveRoute({
				list:[/*{
				code: 15,
				indent: null,
				parameters:[1]
				},*/
				{
				code: 45,
				indent: null,
				parameters:["if(whatsThere(this.x-1,this.y,0)===undefined&&this.x>2&&[1].indexOf($dataMap.data[(3*$dataMap.height+this.y)*$dataMap.width+this.x-1])<0){AudioManager.playSe({name: 'Earth4', volume: 30, pitch: 100, pan: 0});this.moveStraight(4);$gamePlayer.moveStraight(4);tileMovingTrain=true;}else{tileMovingTrain=false;$gamePlayer.setThrough(false);this.setThrough(false);$gamePlayer.setDirectionFix(false);$gamePlayer.setWalkAnime(true);$dataMap.data[(3*$dataMap.height+this.y)*$dataMap.width+this.x]=24;}"]
				},/*{
				code: 3,
				indent: null,
				parameters:[]
				},*/{
				code: 0,
				indent: null,
				parameters:[]
				}],
				repeat:true,
				skippable:true,
				wait:false
			});			
}

var reinitTileLeft = function()
{
onPilar(playerChar).forceMoveRoute({
list:[{
code: 45,
indent: null,
parameters:["if((whosThere(this.x,this.y-this.lvl,1)||botThere(this.x+1,this.y,0)||whatsThere(this.x+1,this.y,0))===undefined&&this.x<20&&[1].indexOf($dataMap.data[(3*$dataMap.height+this.y)*$dataMap.width+this.x+1])<0){updateDataMap(this.x,this.y);allowMove=false;AudioManager.playSe({name: 'Earth4', volume: 30, pitch: 100, pan: 0});this.moveStraight(6);tileMovingTrain=true;}else{if(tileMovingTrain)allowMove=true;tileMovingTrain=false;this.setThrough(false);if(whosThere(this.x,this.y-this.lvl,1)===undefined)stopEvent(this);$dataMap.data[(3*$dataMap.height+this.y)*$dataMap.width+this.x]=32;}"]},
{
code: 0,
indent: null,
parameters:[]}],
repeat:true,skippable:true,wait:false});
}

var stopTrainTiles=function()
{
for(var i=0; i<pilarEvents.length;i++)
{
	var ev = pilarEvents[i];
	if(ev.trainLeft||ev.trainRight)
	{
	ev.forceMoveRoute({
	list:[
	{
	code: 0,
	indent: null,
	parameters:[]}],
	repeat:false,
	skippable:true,
	wait:false});
	}
}
}

var scene_lvl11 = function(stage)
{
	if(stage===1)
	{
	blueChar.setTransparent(true);
	purpleChar.setTransparent(true);
	greenChar.setTransparent(true);
	blueSwitch.setTransparent(true);
	purpleSwitch.setTransparent(true);
	greenSwitch.setTransparent(true);
	yellowSwitch.setTransparent(true);
	// yellowChar.setTransparent(true);
	door.setTransparent(true);

	for(var i=0; i<botEvents.length;i++)
	{
		botEvents[i].setTransparent(true);
	}

	for(var i=0; i<blockEvents.length;i++)
	{
		blockEvents[i].setTransparent(false);
		blockEvents[i]._tileId=3;
	}
	}

	if(stage===2)
	{
	for(var i = 18; i<=20;i++)
	{
	for(var j=0; j<blockEvents.length;j++)
	{
		if(blockEvents[j].x===i&&blockEvents[j].y===8)blockEvents[j]._tileId=41;

	}
	}

	for(var i = 11; i>=5;i--)
	{
	for(var j=0; j<blockEvents.length;j++)
	{
		if(blockEvents[j].x===16&&blockEvents[j].y===i)blockEvents[j]._tileId=41;

	}
	}

	for(var i = 3; i<=14;i++)
	{
	for(var j=0; j<blockEvents.length;j++)
	{
		if(blockEvents[j].x===i&&blockEvents[j].y===7)blockEvents[j]._tileId=41;

	}
	}

	for(var i = 4; i<=12;i++)
	{
	for(var j=0; j<blockEvents.length;j++)
	{
		if(blockEvents[j].x===10&&blockEvents[j].y===i)blockEvents[j]._tileId=41;

	}
	}
	}
}

var swapTileId=function(x,y)
{
	var temp=$dataMap.data[(3*$dataMap.height+y)*$dataMap.width+x];
	$dataMap.data[(3*$dataMap.height+y)*$dataMap.width+x]=$dataMap.data[(2*$dataMap.height+y)*$dataMap.width+x];
	$dataMap.data[(2*$dataMap.height+y)*$dataMap.width+x]=temp;
}

var swapping;
var swapTile=function(tile1, tile2)
{
swapping=true;
	var x1=tile1.x;var y1=tile1.y;
	var x2=tile2.x;var y2=tile2.y;
	var tempChar1=(tileToChar(tile1)===playerChar)?$gamePlayer:tileToChar(tile1);var tempChar2=(tileToChar(tile2)===playerChar)?$gamePlayer:tileToChar(tile2);
	tempChar1.swapx=tempChar2.x;
	tempChar1.swapy=tempChar2.y;
	tempChar2.swapx=tempChar1.x;
	tempChar2.swapy=tempChar1.y;
	tempChar1.fixPriority;
	tempChar2.fixPriority;
	tempChar1.setThrough(true);
	tempChar2.setThrough(true);
	$dataMap.data[(3*$dataMap.height+y1)*$dataMap.width+x1]=3;
	$dataMap.data[(3*$dataMap.height+y2)*$dataMap.width+x2]=3;
	// tile1.moveStraight(2);
	// tile2.moveStraight(2);
	tile1.setMoveSpeed(4);
	tile2.setMoveSpeed(4);

	tempChar1.setDirection(2);
	tempChar2.setDirection(2);

	tempChar1.setDirectionFix(true);
	tempChar2.setDirectionFix(true);

	tile1.setDirectionFix(true);
	tile2.setDirectionFix(true);

	tempChar1.setStepAnime(false);
	tempChar2.setStepAnime(false);

	tile1.forceMoveRoute({
	list:[{
	code: 15,
	indent: null,
	parameters:[30]
	},{
	code: 45,
	indent: null,
	parameters:["AudioManager.playSe({name: 'Earth4', volume: 30, pitch: 100, pan: 0});"]
	},{
	code: 1,
	indent: null,
	parameters:[]
	},{
	code: 45,
	indent: null,
	parameters:["this.setPriorityType(this.y)"]
	},{
	code: 15,
	indent: null,
	parameters:[15]
	},{
	code: 45,
	indent: null,
	parameters:["this.setPriorityType(0)"]
	},{
	code: 4,
	indent: null,
	parameters:[]
	},{
	code: 45,
	indent: null,
	parameters:["$dataMap.data[(3*$dataMap.height+this.y)*$dataMap.width+this.x]=11;"]
	},{
	code: 0,
	indent: null,
	parameters:[]}],
	repeat:false,
	skippable:true,
	wait:false});

	tile2.forceMoveRoute({
	list:[{
	code: 15,
	indent: null,
	parameters:[30]
	},{
	code: 45,
	indent: null,
	parameters:["AudioManager.playSe({name: 'Earth4', volume: 30, pitch: 100, pan: 0});"]
	},{
	code: 1,
	indent: null,
	parameters:[]
	},{
	code: 45,
	indent: null,
	parameters:["this.setPriorityType(this.y)"]
	},{
	code: 15,
	indent: null,
	parameters:[15]
	},{
	code: 45,
	indent: null,
	parameters:["this.setPriorityType(0)"]
	},{
	code: 4,
	indent: null,
	parameters:[]
	},{
	code: 45,
	indent: null,
	parameters:["$dataMap.data[(3*$dataMap.height+this.y)*$dataMap.width+this.x]=11;"]
	},{
	code: 0,
	indent: null,
	parameters:[]}],
	repeat:false,
	skippable:true,
	wait:false});

	tempChar1.forceMoveRoute({
	list:[{
	code: 29,
	indent: null,
	parameters:[5]
	},{
	code: 15,
	indent: null,
	parameters:[50]
	},{
	code: 1,
	indent: null,
	parameters:[]
	},{
	code: 45,
	indent: null,
	parameters:["this.setPosition(this.swapx,this.swapy+1);"]
	},{
	code: 4,
	indent: null,
	parameters:[]
	},{
	code: 14,
	indent: null,
	parameters:[0,0]
	},{
	code: 45,
	indent: null,
	parameters:["this.setThrough(false);this.fixPriority=false;this.setDirectionFix(false);"]
	},{
	code: 0,
	indent: null,
	parameters:[]}],
	repeat:false,
	skippable:true,
	wait:false});

	tempChar2.forceMoveRoute({
	list:[{
	code: 29,
	indent: null,
	parameters:[5]
	},{
	code: 15,
	indent: null,
	parameters:[50]
	},{
	code: 1,
	indent: null,
	parameters:[]
	},{
	code: 45,
	indent: null,
	parameters:["this.setPosition(this.swapx,this.swapy+1);"]
	},{
	code: 4,
	indent: null,
	parameters:[]
	},{
	code: 14,
	indent: null,
	parameters:[0,0]
	},{
	code: 45,
	indent: null,
	parameters:["this.setThrough(false);this.fixPriority=false;this.setDirectionFix(false);swapping=false;"]
	},{
	code: 0,
	indent: null,
	parameters:[]}],
	repeat:false,
	skippable:true,
	wait:false});

}


var scene_lvl16 = function(sign)
{
	// var switch1=blockEvents[rayCoord.myIndexOfArray([11,3,0])];
	// var switch2=blockEvents[rayCoord.myIndexOfArray([11,6,0])];
	// var switch3=blockEvents[rayCoord.myIndexOfArray([11,9,0])];
	// var switch4=blockEvents[rayCoord.myIndexOfArray([11,12,0])];

	var switch1=$gameMap.event($gameMap.eventIdXy(11,3));
	var switch2=$gameMap.event($gameMap.eventIdXy(11,6));
	var switch3=$gameMap.event($gameMap.eventIdXy(11,9));
	var switch4=$gameMap.event($gameMap.eventIdXy(11,12));
	var param = [switch1,switch2,switch3,switch4];
//	var k=25;
	for(var i=0; i<param.length;i++)
	{
	if(param[i]!==undefined){
	param[i].forceMoveRoute({
	list:[{
	code: 45,
	indent: null,
	parameters:["this.setOpacity(this.opacity()+"+String(sign)+"*25);"]
	},{
	code: 0,
	indent: null,
	parameters:[]}],
	repeat:false,
	skippable:true,
	wait:false});
	}
	}
}

var stopEvent=function(ev)
{
	ev.forceMoveRoute({
	list:[
	{
	code: 0,
	indent: null,
	parameters:[]}],
	repeat:false,
	skippable:true,
	wait:false});

}

var stopAllPilars = function()
{
	for(var i=0;i<allPilars.length;i++)
	{
	if(!allPilars[i].down)stopEvent(allPilars[i]);
	};
}

// for(var x=0; x<$dataMap.width;x++)
// {
// 	for(var y=0; y<$dataMap.height;y++)
// 	{
// 	var temp=$dataMap.data[(3*$dataMap.height+y)*$dataMap.width+x];
// 	$dataMap.data[(3*$dataMap.height+y)*$dataMap.width+x]=3;
// 	$dataMap.data[(2*$dataMap.height+y)*$dataMap.width+x]=temp;
// 	}
// };

// $gameMap.event($gameMap.eventIdXy(8,3)).setPriorityType(11);
// $gameMap.event($gameMap.eventIdXy(8,3)).setPosition(6,12);
// for(var i=0; i<allPilars.length;i++)
// {
// 	if(allPilars[i].x<12)allPilars[i].setOpacity(255);
// };

// $gameScreen.showPicture(50, "banal", 1, blueChar.x*48-50, blueChar.y*48-50, 90, 90, 0, 0);
// $gameScreen.showPicture(51, "recale", 1, blueChar.x*48+50, blueChar.y*48-50, 90, 90, 0, 0);
// $gameScreen.showPicture(52, "loser", 1, blueChar.x*48-50, blueChar.y*48+50, 90, 90, 0, 0);
// $gameScreen.showPicture(53, "ordinaire", 1, blueChar.x*48+50, blueChar.y*48-50, 90, 90, 0, 0);
// $gameScreen.showPicture(54, "rien", 1, blueChar.x*48+50, blueChar.y*48+50, 90, 90, 0, 0);
// $gameScreen.showPicture(55, "mediocre", 1, blueChar.x*48-50, blueChar.y*48-50, 90, 90, 0, 0);
// $gameScreen.showPicture(56, "banal", 1, blueChar.x*48+50, blueChar.y*48+50, 90, 90, 0, 0);
// $gameScreen.showPicture(57, "inutile", 1, blueChar.x*48-50, blueChar.y*48+50, 90, 90, 0, 0);

// $gameScreen.showPicture(50, "loser", 1, blueChar.x*48+50, blueChar.y*48-50, 90, 90, 0, 0);
// $gameScreen.showPicture(51, "useless", 1, blueChar.x*48-50, blueChar.y*48+50, 90, 90, 0, 0);
// $gameScreen.showPicture(52, "ordinary", 1, blueChar.x*48-50, blueChar.y*48-50, 90, 90, 0, 0);
// $gameScreen.showPicture(53, "mess", 1, blueChar.x*48+50, blueChar.y*48-50, 90, 90, 0, 0);
// $gameScreen.showPicture(54, "disappointment", 1, blueChar.x*48-50, blueChar.y*48-50, 90, 90, 0, 0);
// $gameScreen.showPicture(55, "failure", 1, blueChar.x*48+50, blueChar.y*48+50, 90, 90, 0, 0);
// $gameScreen.showPicture(56, "life", 1, blueChar.x*48-50, blueChar.y*48-50, 90, 90, 0, 0);
// $gameScreen.showPicture(57, "weirdo", 1, blueChar.x*48-50, blueChar.y*48+50, 90, 90, 0, 0);

// $gameScreen.movePicture(pictureId, origin, x, y, scaleX,scaleY, opacity, blendMode, duration);

// $gameScreen.movePicture(50, 1, blueChar.x*48,blueChar.y*48,20,20,0,40);
// $gameScreen.movePicture(51, 1, blueChar.x*48,blueChar.y*48,20,20,0,40);
// $gameScreen.movePicture(52, 1, blueChar.x*48,blueChar.y*48,20,20,0,40);
// $gameScreen.movePicture(53, 1, blueChar.x*48,blueChar.y*48,20,20,0,40);
// $gameScreen.movePicture(54, 1, blueChar.x*48,blueChar.y*48,20,20,0,40);
// $gameScreen.movePicture(55, 1, blueChar.x*48,blueChar.y*48,20,20,0,40);
// $gameScreen.movePicture(56, 1, blueChar.x*48,blueChar.y*48,20,20,0,40);
// $gameScreen.movePicture(57, 1, blueChar.x*48,blueChar.y*48,20,20,0,40);


 
