// Fete Accomplie Animation
// Characters by Jean-Philippe Delhomme http://www.jphdelhomme.com/
// Code by Raphael Perret http://www.raphaelperret.ch/
// for Patrick Roppel Studio http://www.patrickroppel.com 
// enjoy

$(document).ready(function() {



// Variables ---------------------------------------------------------------------------------

// html5Preloader
var preLoader = new html5Preloader();
var myLoader = new html5Preloader();

// speed of elements on canvas
var backgroundSpeed = 100; // pixels per second
var situationSpeed = 100; 

//width, height of the canvas
var w = 960;
var h = 540;
var width = 960;
var height = 540;
var gLoop;

var debug = false;		// adding characters, flipping, directions
var debug2 = false;		// background & situation arrays
var audioDebug = false;	// audio mixing

// Sounds -----------------------------------
// Rooms ------------
var soundForrest = $("#soundForrest").get(0);
var soundGallery = $("#soundGallery").get(0);
var soundNight = $("#soundNight").get(0);

// Situations -------
var soundCello = $("#soundCello").get(0);
var soundCelloDog = $("#soundCelloDog").get(0);
var soundCello = $("#soundCello").get(0);
var soundDj = $("#soundDj").get(0);
var soundDogBarking = $("#soundDogBarking").get(0);
var soundDogWhining = $("#soundDogWhining").get(0);
var soundParrot = $("#soundParrot").get(0);
var soundParrotAsleep = $("#soundParrotAsleep").get(0);
var soundQuartett = $("#soundQuartett").get(0);
var soundPianoSolo = $("#soundPianoSolo").get(0);
var soundDinnerTable = $("#soundDinnerTable").get(0);
var soundViolaMan = $("#soundViolaMan").get(0);
var soundViolaWoman = $("#soundViolaWoman").get(0);
var soundViolinTrio = $("#soundViolinTrio").get(0);
// Characters -------
var soundCouple = $("#soundCouple").get(0);
var soundFoto = $("#soundFoto").get(0);
var soundLadyRed = $("#soundLadyRed").get(0);
var soundManBeard = $("#soundManBeard").get(0);
var soundManBlue = $("#soundManBlue").get(0);
var soundManGrayGlasses = $("#soundManGrayGlasses").get(0);
var soundManGrayPointynose = $("#soundManGrayPointynose").get(0);
var soundRotisseurTableMeat = $("#soundRotisseurTableMeat").get(0);
var soundWaiterFlowers = $("#soundWaiterFlowers").get(0);
var soundWaiterGlasses = $("#soundWaiterGlasses").get(0);


// Image definitions ------------------------
// left and right edge of scenes
// Extra Images : URL, dx, dy, sound, no character behind, width, height, later img object, later canvas, later canvas context

var loadingImg = [	
	["./imgPng/extra/loading.png", 0, 0, null, false, 960, 540]					// loading...
	];


var extraImg = [
	["./imgPng/extra/left.png", 0, 0, null, false, 30, 540],					// fade in left
	["./imgPng/extra/right.png", 930, 0, null, false, 30, 540]					// fade in right
	];


// Room Images
// images data array: url, x, y, sound, no character in back + imageObject after preload
var roomImg = [
	["./imgPng/rooms/white.png", 0, 0, null, false, width, height],				// 0
	["./imgPng/rooms/forrest.png", 0, 0, soundForrest, true, width, height],	// 1
	["./imgPng/rooms/white.png", 0, 0, null, false, width, height],				// 2
	["./imgPng/rooms/forrestNight.png", 0, 0, soundNight, true, width, height],	// 3
	["./imgPng/rooms/white.png", 0, 0, null, false, width, height],				// 4
	["./imgPng/rooms/night.png", 0, 0, soundNight, false, width, height],		// 5
	["./imgPng/rooms/white.png", 0, 0, null, false, width, height],				// 6
	["./imgPng/rooms/gallery.png", 0, 0, soundGallery, false, width, height],	// 7
	["./imgPng/rooms/white.png", 0, 0, null, false, width, height],				// 8
	["./imgPng/rooms/white.png", 0, 0, null, false, width, height]];			// 9
	
	// 	["./imgPng/rooms/restaurant.png", 40, 40, 670, 600, 1]

// avoid repetitions in random scene generation
var	previousRoom = null; // <--------------------------------------- Mission Impossible !!!

// Situation Images
// images data array: url, width, height + imageObject after preload
var situationImg = [																	//y from top 
	["./imgPng/situations/coatCheck.png", 281, 335], 			// coatCheck: 0			37
	["./imgPng/situations/coatCheckMan.png", 157, 326],			// coatCheckMann: 1		49
	["./imgPng/situations/dinnerTable.png", 564, 250],			// dinnerTable: 2		150
	["./imgPng/situations/dj.png", 207, 312],					// dj: 3				84
	["./imgPng/situations/piano.png", 348, 285],				// piano: 4				106
	["./imgPng/situations/pianist.png", 163, 228],				// pianist: 5			164
	["./imgPng/situations/cello.png", 221, 272],				// cellist: 6			122
	["./imgPng/situations/celloMusicstand.png", 97, 149],		// musicstand: 7		246
	["./imgPng/situations/violinMan.png", 152, 235],			// violinMan: 8			166
	["./imgPng/situations/violinWoman.png", 138, 255],			// violinMan: 9			144
	["./imgPng/situations/dog1.png", 115, 125],					// dog1: 10				270
	["./imgPng/situations/dog2.png", 124, 114],					// dog2: 11				280
	["./imgPng/situations/flowers1.png", 72, 134],				// flowers1: 12			259
	["./imgPng/situations/flowers2.png", 79, 134],				// flowers2: 13			260
	["./imgPng/situations/flowers3.png", 97, 161],				// flowers3: 14			234
	["./imgPng/situations/candlestick1.png", 73, 133],			// candlestick1: 15		260
	["./imgPng/situations/candlestick2.png", 73, 128],			// candlestick2: 16		264
	["./imgPng/situations/parrot.png", 114, 328],				// parrot: 17			71
	["./imgPng/situations/parrotCover.png", 118, 243],			// parrotCover: 18		71
	["./imgPng/situations/torch1.png", 55, 253],				// torch1: 19			140
	["./imgPng/situations/torch2.png", 61, 263],				// torch2: 20			128
	["./imgPng/situations/torch3.png", 74, 264],				// torch3: 21			128
	["./imgPng/situations/owl.png", 102, 169],					// owl: 22				230
	["./imgPng/situations/table.png", 110, 179],				// table: 23			215
	];

// array with situation images combining to one situation
// img index, x, y, sound

var situations = [
[[0, 500, 160, null]],															// 0: coatCheck only
[[0, 500, 160, null], [1, 760, 170, null]],										// 1: coatCheck + Man
[[2, 200, 255, soundDinnerTable]],												// 2: dinnerTable
[[3, 100, 204, soundDj]],														// 3: dj
[[3, 50, 189, soundDj], [2, 350, 255, soundDinnerTable]],						// 4: dj + dinnerTable
[[4, 200, 217, null]],															// 5: piano
[[4, 200, 217, soundPianoSolo], [5, 90, 269]],									// 6: piano + pianist
[[6, 200, 227, soundCelloDog], [7, 80, 351, null]],								// 7: cellist links + musicstand
[[6, 600, 227, soundCelloDog], [7, 480, 351, null]],								// 8: cellist rechts + musicstand
[[8, 105, 271, soundViolaMan]],													// 9: violinMan links
[[9, 680, 249, soundViolaWoman]],												// 10: violinWoman rechts
[[6, 200, 227, soundViolinTrio], [8, 380, 271, null], [9, 500, 249, null]],		// 11: cello + violinWoman + violinMan
[[6, 500, 227, soundQuartett], [8, 680, 271, null], [9, 800, 249, null],	// 12: cello + violinWoman + violinMan + piano + pianist
[4, 150, 217, null], [5, 40, 269]], 								
[[6, 75, 227, soundCelloDog], [2, 320, 255, soundDinnerTable]],					// 13: cello + dinnerTable
//[[10, 90, 375, null]],															// 14: dog1
//[[11, 90, 385, null]],															// 15: dog2
//[[10, 75, 375, null], [11, 135, 385, null]],									// 16: dog1 + dog2
[[3, 100, 189, soundDj], [10, 400, 375, soundDogBarking]],						// 17: dj + dog1
[[6, 200, 227, soundCelloDog], [10, 420, 375, null]],							// 18: cellist + dog1
[[12, 200, 364, null], [13, 420, 365, null], [14, 600, 339, null]],				// 19: flowers 1 - 3
[[15, 300, 365, null], [16, 700, 369, null]],									// 20: candlestick 1 + 2
[[17, 250, 176, soundParrot]],													// 21: parrot
[[17, 250, 176, null], [18, 250, 176, soundParrotAsleep]],						// 22: parrot + cover
[[19, 150, 245, null], [20, 220, 233, null], [21, 800, 233, null]],				// 23: torch 1, 2, 3
//[[22, 450, 335, null]],														// 24owl
[[23, 750, 320, null]],															// table

];

// avoid repetition in random scene generation
var previousSitu = null;


// Characters
// images data array: url, width, height, scale, direction (-> 1 / 0 <-), sound, yOffset + imageObject
var characterImg = [																						//yOffset	// grösse
	["./imgPng/characters/andreas.png", 148, 347, 1, 1, null, 20],						// andreas: 0					-55		148 347
	["./imgPng/characters/couple.png", 229, 352, 1, 0, soundCouple, 28],				// old couple: 1				-40		229 352
	["./imgPng/characters/lady1.png", 148, 369, 1, 0, soundLadyRed, 27],				// lady orange: 2				-24		148	369
	["./imgPng/characters/lady2.png", 126, 345, 1, 0, null, 26],						// lady black: 3				-49		126	345
	["./imgPng/characters/lady3.png", 163, 339, 1, 1, null, 28],						// lady pink: 4					-53		163	339
	["./imgPng/characters/man1.png", 115, 345, 1, 0, soundManGrayPointynose, 27],		// man gray: 5					-48		115	345
	["./imgPng/characters/man2.png", 109, 337, 1, 1, soundManGrayGlasses, 19],			// man checker: 6				-64		109	337
	["./imgPng/characters/man3.png", 106, 344, 1, 0, soundManBlue, 28],					// man blue: 7					-48		106 344
	["./imgPng/characters/man4.png", 138, 340, 1, 1, null, 27],							// man drink: 8					-53		138 340
	["./imgPng/characters/photographer.png", 133, 328, 1, 0, soundFoto, 25],			// photographer: 9				-67		133	328		
	["./imgPng/characters/rotisseur.png", 253, 336, 1, 0, null, 30],					// rotisseur cover: 10			-54		253	336
	["./imgPng/characters/rotisseurDog.png", 201, 336, 1, 0, null, 30],					// rotisseur dog: 11			-54		201	336
	["./imgPng/characters/rotisseurTableDog.png", 211, 340, 1, 0, null, 26],			// table w dog: 12				-54		211	340
	["./imgPng/characters/rotisseurTableMeat.png", 208, 340, 1, 0, soundRotisseurTableMeat, 26],	// table w meat: 13				-54		208	340
	["./imgPng/characters/trendycoupleMan.png", 125, 345, 1, 0, soundManBeard, 24],		// trendy couple man: 14		-51		125	345	
	["./imgPng/characters/trendycoupleWoman.png", 124, 337, 1, 0, null, 26],			// trendy couple woman: 15		-58		124 337
	["./imgPng/characters/waiterCandlestick.png", 142, 343, 1, 0, null, 30],			// waiter w candlesticks: 16	-47		142	343
	["./imgPng/characters/waiterDrinks.png", 167, 343, 1, 0, soundWaiterGlasses, 30],	// waiter w drinks: 17			-47		167 343
	["./imgPng/characters/waiterFlowers.png", 135, 343, 1, 0, soundWaiterFlowers, 30],	// waiter w flowers: 18			-47		135	343
	["./imgPng/situations/dog1.png", 115, 125, 1, 0, soundDogWhining, 30],				// dog1: 19						
	["./imgPng/situations/dog2.png", 124, 114, 1, 0, soundDogBarking, 30]				// dog2: 20						
	];

// characters combinations
// characterImg array index, xOffset, yOffset, stop,  
var characters = [
	[[0, 0, 0, 1]], 						// 0: andreas
	[[0, 0, 0, 1], [17, 100, 0, 1]],		// 1: anreas with waiter
	[[1, 0, 0, 1]],							// 2: old couple
	[[2, 0, 0, 1]],							// 3: lady orange
	[[2, 0, 0, 1], [5, 100, 0, 1]],			// 4: lady orange man gray
	[[3, 0, 0, 1]],							// 5: lady black 
	[[7, 0, 0, 1], [3, 100, 0, 1]],			// 6: man blue, lady black
	[[4, 0, 0, 1]],							// 7: lady pink
	[[5, 0, 0, 1]],							// 8: man gray
	[[6, 0, 0, 1]],							// 9: man checker
	[[7, 0, 0, 1]], 						// 10: man blue
	[[8, 0, 0, 1]],							// 11: man drink
	[[9, 0, 0, 1]],							// 12: photographer
	[[12, 0, 0, 0], [10, 20, 0, 0]],		// 13: rotisseur + table dog	---> out for now  line 738
	[[13, 0, 0, 0], [10, 20, 0, 0]],		// 14: rotisseur + table meat
	[[11, 0, 0, 0]],						// 15: rotisseur dog			---> out for now  line 738
	[[14, 0, 0, 1]],						// 16: trendy couple man
	[[15, 0, 0, 1]],						// 17: trendy couple woman
	[[14, 0, 0, 1], [15, 100, 0, 1]],		// 18: trendy couple man + woman
	[[16, 0, 0, 0]],						// 19: waiter candlesticks
	[[17, 0, 0, 1]],						// 20: waiter w. drinks
	[[18, 0, 0, 0]],						// 21: waiter w. flowers
	[[19, 0, 0, 0], [20, 100, 0, 0]],		// 22: 2 dogs
	
	// making some charactes appearing less and some more...
	
	[[1, 0, 0, 1]],							// 23: old couple
	[[2, 0, 0, 1]],							// 24: lady orange
	[[2, 0, 0, 1], [5, 100, 0, 1]],			// 25: lady orange man gray
	[[3, 0, 0, 1]],							// 26: lady black 
	[[7, 0, 0, 1], [3, 100, 0, 1]],			// 27: man blue, lady black
	[[4, 0, 0, 1]],							// 28: lady pink
	[[5, 0, 0, 1]],							// 29: man gray
	[[6, 0, 0, 1]],							// 30: man checker
	[[7, 0, 0, 1]], 						// 31: man blue
	[[8, 0, 0, 1]],							// 32: man drink
	[[9, 0, 0, 1]],							// 33: photographer

	[[13, 0, 0, 0], [10, 20, 0, 0]],		// 34: rotisseur + table meat
	
	[[14, 0, 0, 1]],						// 35: trendy couple man
	[[15, 0, 0, 1]],						// 36: trendy couple woman
	[[14, 0, 0, 1], [15, 100, 0, 1]],		// 37: trendy couple man + woman	

	[[17, 0, 0, 1]],						// 38: waiter w. drinks	
	[[17, 0, 0, 1]],						// 39: waiter w. drinks	
];


// Scenes
// scenes array
var scenes = new Array();


// Canvas Ini --------------------------------------------------------------------------------

	// visible canvas ----------------
	c0 = document.getElementById('c0');
	ctx0 = c0.getContext('2d');
	c0.width = width;
	c0.height = height;

	c1 = document.getElementById('c1');
	ctx1 = c1.getContext('2d');
	c1.width = width;
	c1.height = height;	
	
	
	// position of slide-in elements : background/ situation
	var slideX = 0;
	
	// boolean to scroll background or situation
	var scrolling = false;
	var scrollLeftRight = false;
	var sceneLoopCount = 0;
	var elementChange = 0;	// 0 = background, 1 = situation


// Helper Functions -------------------------------------------------------------------------
// rounding hack to avoid float coordinates
var rnd = function(number){
	var rounded = (0.5 + number) << 0;
	return rounded;
}

// END Helper Functions ---------------------------------------------------------------------


// Objekte ----------------------------------------------------------------------------------

// Static Images: Room + Situation -----------------------------------------------
// Class defines 'background' and 'situation' of scene
var StaticImage = function(buffer, image, x, y, sound, noBack){
	// that will be the context
	var that = this;
	
	that.buffer = buffer;
	that.image = image;
	that.x = x;
	that.y = y;
	that.sound = sound;
	that.noBack = noBack;

	that.playSound = function(snd, vol){
		if(audioDebug == true){console.dir("play audio "+ snd)};
		if(audioDebug == true){console.dir(snd)};
		snd.volume = vol;
		snd.play();
	}	

	if (that.sound != null && soundOn == true){
		that.playSound(that.sound, 0.7);
	}
	
	
	// Methods -------------
	that.draw = function(){
    	try {
    		that.buffer.drawImage(that.image, rnd(that.x), rnd(that.y));
    		} catch (e) {
    			console.dir("exception");
    		}	
	}	
	
	that.pauseSound = function(){
		that.sound.pause();
	}	
	
};

// END Static Images -------------------------------------------------------------


// Character -----------------------------------------------
// Characters moving around on the Scene
var Character = function(buffer, image, width, height, scale, direction, sound, number, front, speed, move, xOffset, stops, behaviour, xStart, yOffset){
	// that will be the context
	var that = this;

	that.buffer = buffer;
	that.image = image;
	that.width = width;
	that.height = height;
	that.scale = scale;
	that.direction = direction; 	// image direction of character (-> 1 / 0 <-)
	that.sound = sound;
	that.number = number;
	that.front = front;				// in front or not
	that.speed = speed;
	that.moveDirection = move;
	that.xOffset = xOffset;
	that.stops = stops;				// stop for a chat
	that.behaviour = behaviour;	 	// behaviour: 0 walk in and stop, 1 walk in stop and return
	that.xStart = xStart;			// start in the middle of the scene at the beginning, this is the offset from the edge
	that.yOffset = yOffset;			// We started with a character height of 420px now we have different heights yOffset shifts charactes down
	that.timeToStopReturn = false;	// true when time has come to stop, wait and return
	that.returning = false; 		// keep track when returning (don't flip characterdirection)

	that.moving = true;
	that.date = new Date();				// linear motion
	that.time = that.date.getTime(); 
	that.lastTime = that.time;

	
	that.flipped = false;			// check if coordinate system is flipped to display or not -> important for collision detection
	that.flippedX = 0;				// calculate the x on screen of flipped characters

	if (that.moveDirection == 0 && that.direction == 1 && that.returning == false || that.moveDirection == 1 && that.direction == 0 && that.returning == false ||
    	that.moveDirection == 0 && that.direction == 0 && that.returning == true || that.moveDirection == 1 && that.direction == 1 && that.returning == true){
    	that.flipped = true;	
    };
    
    // y 
	// in front or back
	if (that.front == 1){
		that.y = 540 - that.height - that.yOffset + 7; // 540 - 420 = 120
	}
	if (that.front == 0){
		that.scale = 0.75;
		that.y = 540 - that.height - that.yOffset + 42; 
	}
	
	that.x;
	
	if (debug == true){console.dir("direcion: "+ that.direction + " moveDirection: "+ that.moveDirection)};
	
	if (that.moveDirection == 1 && that.direction == 1){
		that.x = 0 - ((that.width + that.xOffset) * that.scale) + that.xStart;
	}
	if (that.moveDirection == 1 && that.direction == 0){
		that.x = 0 - ((that.width + that.xOffset) * that.scale) + that.xStart;
	}
	
	if (that.moveDirection == 0 && that.direction == 0){
		that.x = w + xOffset - that.xStart;	
	}
	if (that.moveDirection == 0 && that.direction == 1){
		that.x = w + ((that.width + that.xOffset ) * that.scale) - that.xStart;
	}
	


	// when timer goes off, it's time to stop and return	
	that.stopReturnIni = function(){
		that.timeToStopReturn = true;
	}	
	
	// start timer to stop, wait and return character
	if (that.behaviour == 1 && that.stops == 1){
		var seconds = 15000 + (Math.random() * 5000);
		var timer = setTimeout(that.stopReturnIni, seconds);
	}
	
	
	// Methods -----------------------------------
	
	// play and pause sound -------------
	that.playSound = function(snd, vol){
		if(audioDebug == true){console.dir("play audio "+ snd)};
		if(audioDebug == true){console.dir(snd)};

		snd.volume = vol;
		snd.play();		

		// exception rules ----		
		if (that.number == 6){ 		// say twinkle poem when stopping
			snd.volume = 0.0;
		}
	}	

	if (that.sound != null && soundOn == true){
		that.playSound(that.sound, 0.7);
	}	
	
	that.pauseSound = function(){
		that.sound.pause();
	}	
	
	
	// move character -------------------
	that.move = function(){
		if (that.moving == false){
		
			that.date = new Date();				// linear motion
			that.time = that.date.getTime(); 
			that.lastTime = that.time;			
		}
	
	
		if (that.moving == true){
	
			var date = new Date();
			var time = date.getTime();
			var timeDiff = time - that.lastTime;
 			var linearDistancePerFrame = that.speed * timeDiff / 1000;

	
			if (that.moveDirection == 1){
				that.x += linearDistancePerFrame;
			}
			if (that.moveDirection == 0){
				that.x -= linearDistancePerFrame;
			}
			
			that.lastTime = time;
		}
	}
	
	// draw to offscreen buffer ---------	
	that.draw = function(){
		
		// the "normal" coordinate system characters -----
    	if (that.moveDirection == 1 && that.direction == 1 && that.returning == false || that.moveDirection == 0 && that.direction == 0 && that.returning == false || 
    	that.moveDirection == 0 && that.direction == 1 && that.returning == true || that.moveDirection == 1 && that.direction == 0 && that.returning == true){
    		try {
				that.buffer.drawImage(that.image, rnd(that.x), rnd(that.y), rnd(that.width * that.scale), rnd(that.height * that.scale));

				if (debug == true){
					that.buffer.fillStyle = "rgba(0, 0, 255, 0.1)";
					that.buffer.fillRect(that.x, that.y, that.width * that.scale, that.height * that.scale);
				
					that.buffer.strokeStyle = "rgb(0, 0, 255)";		
					that.buffer.beginPath();
					that.buffer.moveTo(that.x, 0);
					that.buffer.lineTo(that.x, 600);
					that.buffer.stroke();
				}
				
			} catch (e) {
				console.dir("exception");
			}
		}
		
		// the flipped characters --------
		if (that.moveDirection == 0 && that.direction == 1 && that.returning == false || that.moveDirection == 1 && that.direction == 0 && that.returning == false ||
    	that.moveDirection == 0 && that.direction == 0 && that.returning == true || that.moveDirection == 1 && that.direction == 1 && that.returning == true){
			try {
				that.buffer.scale(-1, 1);
				that.buffer.drawImage(that.image, rnd(-that.x - (that.width * that.scale)), rnd(that.y), rnd(that.width * that.scale), rnd(that.height * that.scale));
				// -that.x -that.width -> make sure left corner of character is x:0, same as if not flipped

				if (debug == true){
					that.buffer.fillStyle = "rgba(255, 0, 0, 0.1)";
					that.buffer.fillRect(-that.x - (that.width * that.scale), that.y, that.width * that.scale, that.height * that.scale);				
				}
				
				that.buffer.scale(-1, 1);

				if (debug == true){
					that.buffer.strokeStyle = "rgb(255, 0, 0)";		
					that.buffer.beginPath();
					that.buffer.moveTo(that.x, 0);
					that.buffer.lineTo(that.x, 600);
					that.buffer.stroke();
				}	
				
			} catch (e) {
				console.dir("exception");
			}	
		}
	}
	


	// Characters stopping in front of each other, waiting and moving again ---------------------
	that.stopAgain = function(){
		that.stops = 1;
	}

	that.stopTimeout = function(){
		if (debug == true){console.dir("stop character timeout")};
		that.moving = true;

// 		if (that.sound != null){
// 			that.sound.pause();
// 		}	
		
		var timer = setTimeout(that.stopAgain, 4000);	// after how long to stop again
	}
	

	
	// stop moving: talk / take pictures ------------
	that.stop = function(seconds){
		that.seconds = seconds;
		that.moving = false;
		that.stops = 0;
				
		// sound ---------------------
		if (that.number == 6){ 		// say twinkle poem when stopping
			playSound(that.sound, 0.7);
		}

// 		if (that.sound != null){
// 			playSound(that.sound, 0.4);
// 		}
	
		var timer = setTimeout(that.stopTimeout, seconds);
	}
	
	// stop by itself --------------
	
	


	// Characters moving into the scene, waiting and returning -----------------------

	// stop, wait and return -------------------------
	that.stopReturn = function(){
		// reverse move direction	
		that.moveDirection = Math.abs(that.moveDirection -1);
		
		that.moving = true;
		that.timeToStopReturn = false;
		that.returning = true;
		
		if (debug == true){
			console.dir("--- stopReturn ---");
			console.dir("moveDirection: "+ that.moveDirection);
			console.dir("driection: "+ that.direction);		
			console.dir("--- stopReturn ---/");
		}
	}

	// stop, wait, return ----------------------------
	that.stopWait = function(seconds){
		if (that.moving == true){
			that.seconds = seconds;
			that.moving = false;
			var timer = setTimeout(that.stopReturn, seconds);	
			
			if (debug == true){
				console.dir("--- stopWait ---");
				console.dir("moveDirection: "+ that.moveDirection);
				console.dir("direction: "+ that.direction);		
				console.dir("--- stopWait ---/");
			}
		}
	}

	
};

// END Character -----------------------------------------------


// Scene ---------------------------------------------
var Scene = function(buffer){

	//'that' will be the context now
    var that = this;
    
    that.buffer = buffer;
	that.room = null;
    that.situ = null;
    that.move = true;
    that.moveBack = false;
    that.moveBackDir = null; 		// direction in which to move background
    that.moveSit = false;
    that.moveSitDir = null;			// direction in which to move situation
    that.presentSitu = null; 
    that.situationX = 0; 			// current situation x
    
	that.backDate = new Date();				// linear motion
	that.backTime = that.backDate.getTime(); 
	that.backLastTime = that.backTime;

	that.sitDate = new Date();				// linear motion
	that.sitTime = that.sitDate.getTime(); 
	that.sitLastTime = that.sitTime;
	
    // Characters --------------
    that.sceneCharacters = new Array();	
    
    // generate the situation ----    
    that.generateRoom = function(){
    	var r = Math.round( Math.random() * (roomImg.length -1));
    	
    	if (debug == true){console.dir("room number generated: "+ r)};
    	
    	if (r != previousRoom){
    		previousRoom = r;
    		that.room = r;
    		if(debug2 == true){console.dir("that.room "+ that.room)};
    	} else {
    		that.generateRoom();
    	}
    }
    
    that.generateSitu = function(){
    	var s = Math.round( Math.random() * (situations.length -1));
    	if (debug == true){console.dir("situ number generated: "+ s)};

		// no previous situation, no double dogs
    	if (s != previousSitu){
    		var dog = false;
    		for (i = 0; i < that.sceneCharacters.length; i++){
    			if (that.sceneCharacters[i].number == 22){
    				dog = true;
    			}
    		}
    		
			if ((dog == false) || (dog == true && s != 14) || (dog == true && s !=15) || (dog == true && s != 16) || (dog == true && s != 17)  || (dog == true && s != 18) ){
				previousSitu = s;
				that.situ = s;
				if(debug2 == true){console.dir("that.situ "+ that.situ)};
			} 			
			
		} else {
			that.generateSitu();
    	}    
	}    

    that.generateRoom();
    that.generateSitu();
    
    that.timer = setTimeout(onTimeout, 1000);
    that.timerFlag = false; // true when timer went off
        
    
	//attributes -------------------------------
	// create Arrays for background and situation
	that.backgroundElements = new Array();
	that.situationElements = new Array();	
	
	if (debug == true){console.dir("room number: "+ that.room + " situ number: "+ that.situ)};
	
	
	// addBackground ---------------------------
	that.addBackground = function(x){
		var newX = roomImg[that.room][1] + x;
		that.backgroundElements.push( new StaticImage(that.buffer, roomImg[that.room][8], newX, roomImg[that.room][2], roomImg[that.room][3], roomImg[that.room][4]));	
   		if(debug2 == true){console.dir("--- background array ---")};
   		if(debug2 == true){console.dir(that.backgroundElements)};   		
	}

	// addSituation ----------------------------
	that.addSituation = function(x){
		// then the siutation with all images belonging to it -> from array situations and situationImg
		for (var i = 0; i < situations[that.situ].length; i++){
			img = situations[that.situ][i][0];
			
			var newX = situations[that.situ][i][1] + x;
			// image, x, y, sound
			that.situationElements.push( new StaticImage(that.buffer, situationImg[img][4], newX, situations[that.situ][i][2], situations[that.situ][i][3]));
			if(audioDebug == true){console.dir("audio situation: "+ situations[that.situ][i][3])};
	   		if(debug2 == true){console.dir("--- situation array ---")};
	   		if(debug2 == true){console.dir(that.situationElements)};
		}  
	}
	
	that.addBackground(0);	// add background at x pos 0
	that.addSituation(0);	// add situation at x pos 0
	
	// change background - add and scroll in 
	that.changeBackground = function(dir){
		that.moveBackDir = dir; 
		that.generateRoom();

		if (that.moveBackDir == 0){
			that.addBackground(-width);		
		}
		if (that.moveBackDir == 1){
			that.addBackground(width);		
		}

		that.moveBack = true;
	}
	
	that.changeSituation = function(dir){
		that.moveSitDir = dir;
		that.presentSitu = that.situ;			// keep track of present situation
		that.generateSitu();
		
		if (that.moveSitDir == 0){
			that.addSituation(-width);
		}
		if (that.moveSitDir == 1){
			that.addSituation(width);
		}
		
		that.moveSit = true;
	}
	
	
	that.moveBackground = function(){					// 0 : left to right - 1 : right to left
		
		if (that.moveBack == false){
		
			that.backDate = new Date();				// linear motion
			that.backTime = that.backDate.getTime(); 
			that.backLastTime = that.backTime;			
		}
	
		if (that.moveBack == true){
				
			var date = new Date();
			var time = date.getTime();
			var timeDiff = time - that.backLastTime;
 			var linearDistancePerFrame = backgroundSpeed * timeDiff / 1000;	
				
			if (that.moveBackDir == 0){
				for (var i = 0; i < that.backgroundElements.length; i++){
				
					that.backgroundElements[i].x += linearDistancePerFrame;

					if (that.backgroundElements[that.backgroundElements.length -1].x >= 0 ){
						that.moveBack = false;
						
						if (that.backgroundElements[0].sound != null && that.backgroundElements[0].sound != that.backgroundElements[1].sound){
							that.backgroundElements[0].pauseSound();			// pause audio
							};	
						if (audioDebug == true){console.dir("--------------- audio paused --------------")};
						
						that.backgroundElements.splice(0, that.backgroundElements.length -1);
						
						sLoop = setTimeout(sceneChange, 25000);				// change Scene in 25"						
						
						if(debug2 == true){console.dir("--- deleted from background array/ right out ---")};
						if(debug2 == true){console.dir(that.backgroundElements)};
					}
				}			
			}
			
			if (that.moveBackDir == 1){
				for (var i = 0; i < that.backgroundElements.length; i++){
				
					that.backgroundElements[i].x -= linearDistancePerFrame;

					if (that.backgroundElements[that.backgroundElements.length -1].x <= 0 ){
						that.moveBack = false;

						if (that.backgroundElements[0].sound != null && that.backgroundElements[0].sound != that.backgroundElements[1].sound){
							that.backgroundElements[0].pauseSound();			// pause audio
							};	
						if (audioDebug == true){console.dir("--------------- audio paused --------------")};
						
						that.backgroundElements.splice(0, that.backgroundElements.length -1);

						sLoop = setTimeout(sceneChange, 25000);				// change Scene in 25"						

						if(debug2 == true){console.dir("--- deleted from background array/ left out ---")};
						if(debug2 == true){console.dir(that.backgroundElements)};
					}		
				}
			}
			
			that.backLastTime = time;
		}	
	}
	
	
	that.moveSituation = function(){					// 0 : left to right - 1 : right to left

		if (that.moveSit == false){
		
			that.sitDate = new Date();					// linear motion
			that.sitTime = that.sitDate.getTime(); 
			that.sitLastTime = that.sitTime;			
		}


		if (that.moveSit == true){
		
			var date = new Date();
			var time = date.getTime();
			var timeDiff = time - that.sitLastTime;
 			var linearDistancePerFrame = situationSpeed * timeDiff / 1000;			
			
			if (that.moveSitDir == 0){
				for (var i = 0; i < that.situationElements.length; i++){

					var linearDistancePerFrame = situationSpeed * timeDiff / 1000;								
					that.situationElements[i].x += linearDistancePerFrame;
				}
				that.situationX += linearDistancePerFrame;
				
				if (that.situationX >= width ){
					that.moveSit = false;
					if (situations[that.presentSitu].length > 0){
					
						for (var i = 0; i < situations[that.presentSitu].length; i++){
							if (that.situationElements[i].sound != null){
								var found = false;
								
								if (audioDebug == true){console.dir("------ audio not null ---------")};							
							
								for (var j = situations[that.presentSitu].length; j < that.situationElements.length -1; j++ ){
									if (that.situationElements[i].sound == that.situationElements[j].sound){
										if (audioDebug == true){console.dir("true")};
										found = true;
									} 
								}	

								if (found == false){
									if (audioDebug == true){console.dir("pause"+ that.situationElements[i].sound)};
									that.situationElements[i].pauseSound();
								}	
								
							}							
						}					
					
					
						that.situationElements.splice(0, situations[that.presentSitu].length);
						
						sLoop = setTimeout(sceneChange, 25000);				// change Scene in 25"										
						
				   		if(debug2 == true){console.dir("--- deleted from situation array/ right out ---")};
				   		if(debug2 == true){console.dir(that.situationElements)};						
					}
					that.situationX = 0;
				}		
			}
			if (that.moveSitDir == 1){
				for (var i = 0; i < that.situationElements.length; i++){
					var linearDistancePerFrame = situationSpeed * timeDiff / 1000;								
					that.situationElements[i].x -= linearDistancePerFrame;
				}
				that.situationX -= linearDistancePerFrame;
				
				if (that.situationX <= -width ){
					that.moveSit = false;
					if (situations[that.presentSitu].length > 0){
					
						for (var i = 0; i < situations[that.presentSitu].length; i++){
							if (that.situationElements[i].sound != null){
								var found = false;
								
								if (audioDebug == true){console.dir("------ audio not null ---------")};							
							
								for (var j = situations[that.presentSitu].length; j < that.situationElements.length -1; j++ ){
									if (that.situationElements[i].sound == that.situationElements[j].sound){
										if (audioDebug == true){console.dir("true")};
										found = true;
									} 
								}	

								if (found == false){
									if (audioDebug == true){console.dir("pause"+ that.situationElements[i].sound)};
									that.situationElements[i].pauseSound();
								}	
								
							}							
						}					
					
					
						that.situationElements.splice(0, situations[that.presentSitu].length);
						
						sLoop = setTimeout(sceneChange, 25000);				// change Scene in 25"						
						
				   		if(debug2 == true){console.dir("--- deleted from situation array/ left out ---")};
				   		if(debug2 == true){console.dir(that.situationElements)};						
					}				
					that.situationX = 0;
				}		
			}
		that.sitLastTime = time;			
		}	
	}	
	
	
	// Extras left and right fade in -------------------
	// draw on canvas c1!
	var extras = new Array();
	for (var i = 0; i < extraImg.length; i++){
		extras.push( new StaticImage(ctx1, extraImg[i][8], extraImg[i][1], extraImg[i][2], extraImg[i][3], extraImg[i][4]));
	}
	
    

	// methods ----------------------------------
	// character frequency ----------------------
	that.setFrequency = function(){
		return (Math.random() * 6000 + 10000);			// <--- how long to wait for next character
	}
	
	function onTimeout(){
		if (debug == true){console.dir("onTimeout called")};

		if (that.sceneCharacters.length < 8){				// <--- max charactes in scene !!!
			that.addCharacter(0);
		}
		that.timerFlag = true;
	}
	
	that.checkCharacter = function(){
		if (that.timerFlag == true){
			that.timer = setTimeout(onTimeout, that.setFrequency());
			that.timerFlag = false;
		}
	}
	
	// move -------------------------------
	that.moveCharacter = function(){
		if (that.move == true){
		
			// go throught characters array
			for (var i = 0; i < that.sceneCharacters.length; i++){
	
				// check collision of characters that walk in, stop and continue walking
				if (that.sceneCharacters[i].behaviour == 0){
				
					// move back plane: left to right ->
					if ((that.sceneCharacters[i].front == 0) && (that.sceneCharacters[i].moving == true) && (that.sceneCharacters[i].stops == 1) && (that.sceneCharacters[i].moveDirection == 1)){
					
						for(j = 0; j < that.sceneCharacters[i]; j++){		// lower in array
							if ((that.sceneCharacters[j].front == 0) && (that.sceneCharacters[j].moving == true) && (that.sceneCharacters[j].moveDirection == 0) && 
							(that.sceneCharacters[j].stops == 1) && (Math.abs(that.sceneCharacters[i].x + (that.sceneCharacters[i].width * that.sceneCharacters[i].scale) - that.sceneCharacters[j].x) < 20)) {
								
								var seconds = 20000 + (Math.random() * 15000);
								that.sceneCharacters[j].stop(seconds);
								that.sceneCharacters[i].stop(seconds);
								
								if (debug == true){
									console.dir("stop back left to right");							
									console.dir("x i "+that.that.sceneCharacters[i].x);
									console.dir("x j "+that.that.sceneCharacters[j].x);														
								}
							}
						}	
								
						for (j = i+1; j < that.sceneCharacters.length; j++){	// higher in array
							if ((that.sceneCharacters[j].front == 0) && (that.sceneCharacters[j].moving == true) && (that.sceneCharacters[j].moveDirection == 0) && 
							(that.sceneCharacters[j].stops == 1) && (Math.abs(that.sceneCharacters[i].x  + (that.sceneCharacters[i].width * that.sceneCharacters[i].scale) - that.sceneCharacters[j].x) < 20)) {
								
								var seconds = 20000 + (Math.random() * 15000);
								that.sceneCharacters[j].stop(seconds);
								that.sceneCharacters[i].stop(seconds);
								
								if (debug == true){
									console.dir("stop back left to right");
									console.dir("x i "+that.that.sceneCharacters[i].x);
									console.dir("x j "+that.that.sceneCharacters[j].x);														
								}
							}
						}
					}
					
					// back plane right to left <-
					if ((that.sceneCharacters[i].front == 0) && (that.sceneCharacters[i].moving == true) && (that.sceneCharacters[i].stops == 1) && (that.sceneCharacters[i].moveDirection == 0)){
					
						for(j = 0; j < that.sceneCharacters[i]; j++){		// lower in array
							if ((that.sceneCharacters[j].front == 0) && (that.sceneCharacters[j].moving == true) && (that.sceneCharacters[j].moveDirection == 1) && 
							(that.sceneCharacters[j].stops == 1) && (Math.abs(that.sceneCharacters[i].x - (that.sceneCharacters[j].x + (that.sceneCharacters[j].width * that.sceneCharacters[j].scale))) < 20)) {
								
								var seconds = 20000 + (Math.random() * 15000);						
								that.sceneCharacters[j].stop(seconds);
								that.sceneCharacters[i].stop(seconds);				
								
								if (debug == true){
									console.dir("stop back right to left");								
									console.dir("x i "+that.that.sceneCharacters[i].x);
									console.dir("x j "+that.that.sceneCharacters[j].x);							
								}
							}
						}	
								
						for (j = i+1; j < that.sceneCharacters.length; j++){	// higher in array
							if ((that.sceneCharacters[j].front == 0) && (that.sceneCharacters[j].moving == true) && (that.sceneCharacters[j].moveDirection == 1) && 
							(that.sceneCharacters[j].stops == 1) && (Math.abs(that.sceneCharacters[i].x - (that.sceneCharacters[j].x + (that.sceneCharacters[j].width * that.sceneCharacters[j].scale))) < 20)) {
								
								var seconds = 20000 + (Math.random() * 15000);
								that.sceneCharacters[j].stop(seconds);
								that.sceneCharacters[i].stop(seconds);
								
								if (debug == true){
									console.dir("stop back right to left");	
									console.dir("x i "+that.that.sceneCharacters[i].x);
									console.dir("x j "+that.that.sceneCharacters[j].x);														
								}
							}
						}
					}
					
					// front plane left to right ->
					if ((that.sceneCharacters[i].front == 1) && (that.sceneCharacters[i].moving == true) && (that.sceneCharacters[i].stops == 1) && (that.sceneCharacters[i].moveDirection == 1)){
					
						for(j = 0; j < that.sceneCharacters[i]; j++){		// lower in array
							if ((that.sceneCharacters[j].front == 1) && (that.sceneCharacters[j].moving == true) && (that.sceneCharacters[j].moveDirection == 0) && 
							(that.sceneCharacters[j].stops == 1) && (Math.abs(that.sceneCharacters[i].x + that.sceneCharacters[i].width - that.sceneCharacters[j].x) < 40)) {
								
								var seconds = 20000 + (Math.random() * 15000);
								that.sceneCharacters[j].stop(seconds);
								that.sceneCharacters[i].stop(seconds);		
								
								if (debug == true){
									console.dir("stop front left to right");							
									console.dir("x i "+that.that.sceneCharacters[i].x);
									console.dir("x j "+that.that.sceneCharacters[j].x);								
								}
							}
						}	
								
						for (j = i+1; j < that.sceneCharacters.length; j++){	// higher in array
							if ((that.sceneCharacters[j].front == 1) && (that.sceneCharacters[j].moving == true) && (that.sceneCharacters[j].moveDirection == 0) && 
							(that.sceneCharacters[j].stops == 1) && (Math.abs(that.sceneCharacters[i].x + that.sceneCharacters[i].width - that.sceneCharacters[j].x) < 40)) {
								
								var seconds = 20000 + (Math.random() * 15000);
								that.sceneCharacters[j].stop(seconds);
								that.sceneCharacters[i].stop(seconds);
								
								if (debug == true){
									console.dir("stop front left to right");
									console.dir("x i "+that.that.sceneCharacters[i].x);
									console.dir("x j "+that.that.sceneCharacters[j].x);														
								}
							}
						}
					}
					
					// front plane right to left <-
					if ((that.sceneCharacters[i].front == 1) && (that.sceneCharacters[i].moving == true) && (that.sceneCharacters[i].stops == 1) && (that.sceneCharacters[i].moveDirection == 0)){
					
						for(j = 0; j < that.sceneCharacters[i]; j++){		// lower in array
							if ((that.sceneCharacters[j].front == 1) && (that.sceneCharacters[j].moving == true) && (that.sceneCharacters[j].moveDirection == 1) && 
							(that.sceneCharacters[j].stops == 1) && (Math.abs(that.sceneCharacters[i].x - (that.sceneCharacters[j].x + that.sceneCharacters[j].width)) < 40)) {
								
								var seconds = 20000 + (Math.random() * 15000);
								that.sceneCharacters[j].stop(seconds);
								that.sceneCharacters[i].stop(seconds);				
								
								if (debug == true){
									console.dir("stop front right to left");
									console.dir("x i "+that.that.sceneCharacters[i].x);
									console.dir("x j "+that.that.sceneCharacters[j].x);														
								}
							}
						}	
								
						for (j = i+1; j < that.sceneCharacters.length; j++){	// higher in array
							if ((that.sceneCharacters[j].front == 1) && (that.sceneCharacters[j].moving == true) && (that.sceneCharacters[j].moveDirection == 1) && 
							(that.sceneCharacters[j].stops == 1) && (Math.abs(that.sceneCharacters[i].x - (that.sceneCharacters[j].x + that.sceneCharacters[j].width)) < 40)) {
								
								var seconds = 20000 + (Math.random() * 15000);
								that.sceneCharacters[j].stop(seconds);
								that.sceneCharacters[i].stop(seconds);
	
								if (debug == true){
									console.dir("stop front right to left");
									console.dir("x i "+that.that.sceneCharacters[i].x);
									console.dir("x j "+that.that.sceneCharacters[j].x);														
								}
							}
						}
					}	
				
				}
				
				// charactes that walk in, stop and return
				if (that.sceneCharacters[i].behaviour == 1 && that.sceneCharacters[i].timeToStopReturn == true){
					
					// stop
					var seconds = 20000 + (Math.random() * 15000);
					that.sceneCharacters[i].stopWait(seconds);				
				}
				
			that.sceneCharacters[i].move();
			}    	    	
    	}
	}
	
	

	// check for double character in sceneCharacters array
	that.checkDouble = function(a, c){
		var r = 0; // result
		
		if (debug == true){console.dir("c: " + c)};
		
		for (var i = 0; i < c.length; i++){		// Uncaught TypeError: Cannot read property 'length' of undefined

			var num = c[i][0];
			var l = a.length -1;			
			
			while (l >= 0) {

			   if (a[l].number == num) {
				   r++; // increase r if match found
			   }
			   l--;
			}
		}
		return r;
	}
	
	// check for exception rules ------------
	that.checkException = function(c){
		// no dogs for now....
		if (c == 13 || c == 15){
			if (debug == true) {console.dir("-- double character ---")};
			return true;
		}
		// no double dog...		
		if ( (that.situ == 14 || that.situ == 16 || that.situ == 17 || that.situ == 18) && (c == 13 || c == 15 || c == 22) ){
			if (debug == true) {console.dir("-- double character ---")};
			return true;
		} else {
			return false;
		}
	}


	// add character -------------------------------
	that.addCharacter = function(xStart){
		var c = Math.round((Math.random() * (characters.length -1)));
		var f = Math.round(Math.random());			// front
		var s = 10 + (Math.random() * 10);			// speed
		var m = Math.round(Math.random());  		// move from left to right or right to left (-> 1 / 0 <-)
		var b = 0;									// behaviour
		var b = Math.round(Math.random() * 3); 		// behaviour: 0 walk in and stop, 1 walk in stop and return
		if (b > 1){ b = 0}; 						// limit to two possibilities, more chances of walk and stop...
//		var b = 1;		
	
		var that = this;
		that.xStart = xStart;
		
		// Exception Rules -------------
		// no characters in back with forrest backdrop!!!
// 		if (elements[0].noBack == true){
// 			f = 1;
// 		}

		// speed up the dogs
		if (c == 22){
			s = s + 65;
		}
		
		// dogs in front - resize problem
		if (c == 22){
			f = 1;
		}
		
		// check for exceptions like no double dog...
		var ex = that.checkException(c);
		if (ex == true){
			that.addCharacter(that.xStart);
		} else {
		
			// if 1 or more sceneCharacters are on stage, check if already there
			if (that.sceneCharacters.length > 0){
	
				if (debug == true){ console.dir("c before check: "+ c)};
				var doubleCheck = that.checkDouble(that.sceneCharacters, characters[c]);
							
				if (doubleCheck > 0){
					that.addCharacter(that.xStart);			
				}	
				
				if (doubleCheck == 0){
					for (var i = 0; i < characters[c].length; i++){
						var img = characters[c][i][0];
						var stop = characters[c][i][3];
						if (debug == true){console.dir("nummer "+ img + " stop "+ stop)};
						
						// buffer, offscreenCanvas, width, height, scale, direction, sound, number, front, speed, moveDirection ... xOffset, stop, return
						that.sceneCharacters.push (new Character(that.buffer, characterImg[img][8], characterImg[img][1], characterImg[img][2], characterImg[img][3], characterImg[img][4], characterImg[img][5], img, f, s, m, characters[c][i][1], characters[c][i][3], b, that.xStart, characterImg[img][6]));			
					}
				}
			}
			
			// nothat.that.sceneCharacters on stage...
			if (that.sceneCharacters.length == 0){
				for (var i = 0; i < characters[c].length; i++){
					var img = characters[c][i][0];
										
					// buffer, offscreenCanvas, width, height, scale, direction, sound, number, front, speed, moveDirection
					that.sceneCharacters.push (new Character(that.buffer, characterImg[img][8], characterImg[img][1], characterImg[img][2], characterImg[img][3], characterImg[img][4], characterImg[img][5], img, f, s, m, characters[c][i][1], characters[c][i][3], b, that.xStart, characterImg[img][6]));			
				}
			}		
		
		}		
	}

	
	that.deleteCharacter = function(){
    	for (var i = 0; i < that.sceneCharacters.length; i++){
			if (that.sceneCharacters[i].moveDirection == 1 && that.sceneCharacters[i].direction == 1 && that.sceneCharacters[i].x > width){
				if (that.sceneCharacters[i].sound != null){
					that.sceneCharacters[i].pauseSound();
				} 
				
				that.sceneCharacters.splice(i,1);
				if (debug == true){
					console.dir("deleted 1 1");
					console.dir(that.sceneCharacters);
				}
				return;
			}

			if (that.sceneCharacters[i].moveDirection == 1 && that.sceneCharacters[i].direction == 0 && (that.sceneCharacters[i].x - (that.sceneCharacters[i].width * that.sceneCharacters[i].scale)) > width){
				if (that.sceneCharacters[i].sound != null){
					that.sceneCharacters[i].pauseSound();
				} 

				that.sceneCharacters.splice(i,1);
				if (debug == true){
					console.dir("deleted 1 0");
					console.dir(that.sceneCharacters);
				}
				return;
			}
						
			if (that.sceneCharacters[i].moveDirection == 0 && that.sceneCharacters[i].direction == 0 && (that.sceneCharacters[i].x < 0 - (that.sceneCharacters[i].width * that.sceneCharacters[i].scale)) ){
				if (that.sceneCharacters[i].sound != null){
					that.sceneCharacters[i].pauseSound();
				} 

				that.sceneCharacters.splice(i,1);
				if (debug == true){
					console.dir("deleted 0 0");
					console.dir(that.sceneCharacters);
				}	
				return;
			}

			if (that.sceneCharacters[i].moveDirection == 0 && that.sceneCharacters[i].direction == 1 && (that.sceneCharacters[i].x < 0 - (that.sceneCharacters[i].width * that.sceneCharacters[i].scale)) ){
				if (that.sceneCharacters[i].sound != null){
					that.sceneCharacters[i].pauseSound();
				} 

				that.sceneCharacters.splice(i,1);
				if (debug == true){
					console.dir("x "+that.that.sceneCharacters[i].x);
					console.dir("deleted 0 1");
					console.dir("!!! Attention !!!");
					console.dir(that.sceneCharacters);				
				}
				return;
			}
    	}   
	}
	

	// scene draw ----------------------
    that.draw = function(){

    // first draw background image
    	for (var i = 0; i < that.backgroundElements.length; i++){
	    	that.backgroundElements[i].draw();
    	}    	

    
    // then drawthat.that.sceneCharacters in back
    	for (var i = 0; i < that.sceneCharacters.length; i++){
			if (that.sceneCharacters[i].front == 0){
				that.sceneCharacters[i].draw();			
			}
    	}    	
       
    // then elements in room
    	for (var i = 0; i < that.situationElements.length; i++){
			that.situationElements[i].draw();
    	}

	// thenthat.that.sceneCharacters in front
    	for (var i = 0; i < that.sceneCharacters.length; i++){
			if (that.sceneCharacters[i].front == 1){
				that.sceneCharacters[i].draw();			
			}
    	}  
    	
    // then extras like fade in on sides
    // draw only until fade in is over
   		if (aLevel > 0.05){
	    	for (var i = 0; i < extras.length; i++){
				extras[i].draw();
    		}
    	}	
    }
    
      

    // add random Characters at beginning of scene -------------
    var startCharacters = Math.round(Math.random() * 3 + 2);
    	if (debug == true){ console.dir("startCharacters: "+ startCharacters)};
		for (i = 0; i < startCharacters; i++){
			if (debug == true){ console.dir("ping")};
			var x = Math.round(Math.random() * 600 + 200)
			that.addCharacter(x);    
    }

};

// END Scene -----------------------------------------



// Methoden der Dokument Ebene ---------------------------------------------------------------------

// play sound -------------------

var playSound = function(snd, vol){
	snd.volume = vol;
	snd.play();
}


// clear the canvases - only while fading in
var clear = function(){
	ctx0.clearRect(0,0,width,height);
		
	if (aLevel > 0.05){
		ctx1.clearRect(0,0,width,height);
	}
};

// move ---------------------------
var move = function(){

	for (var i = 0; i < scenes.length; i++){
		scenes[i].moveBackground();
		scenes[i].moveSituation();
	
		scenes[i].deleteCharacter();
		scenes[i].moveCharacter();
		scenes[i].checkCharacter();
	}

};

var aLevel = 1.0; // Alpha Level

// draw offscreen buffer and copy to canvas -------
var draw = function(){ 
	var that = this;

	// draw all scenes to offscreen buffer
	for (var i = 0; i < scenes.length; i++){
		scenes[i].draw();
	}	
	
	// fade in on load ...
	if (aLevel > 0.05){
		fadeIn(aLevel);
		aLevel -= 0.005;
	}
};


// mute sound --------------------------------------
var mute = function(){
	if (soundOn == false){
		
		for (var i = 0; i < scenes[0].backgroundElements.length; i++){
			if (scenes[0].backgroundElements[i].sound != null){
				scenes[0].backgroundElements[i].pauseSound();			// pause audio
			}	
		}	
			
		for (var i = 0; i < scenes[0].situationElements.length; i++){
			if (scenes[0].situationElements[i].sound != null){
				scenes[0].situationElements[i].pauseSound();
			}			
		}

		for (var i = 0; i < scenes[0].sceneCharacters.length; i++){
			if (scenes[0].sceneCharacters[i].sound != null){
				scenes[0].sceneCharacters[i].pauseSound();
			}
		}
	}	

if (soundOn == true){
		
		for (var i = 0; i < scenes[0].backgroundElements.length; i++){
			if (scenes[0].backgroundElements[i].sound != null){
				scenes[0].backgroundElements[i].sound.play();			// pause audio
			}	
		}	
			
		for (var i = 0; i < scenes[0].situationElements.length; i++){
			if (scenes[0].situationElements[i].sound != null){
				scenes[0].situationElements[i].sound.play();
			}			
		}

		for (var i = 0; i < scenes[0].sceneCharacters.length; i++){
			if (scenes[0].sceneCharacters[i].sound != null){
				scenes[0].sceneCharacters[i].sound.play();
			}
		}
	}	
		
	
};


// fade in with alpha channel on load
var fadeIn = function(alphaLevel){
 	// draw white layer on top
 	ctx1.fillStyle = 'rgba(255, 255, 255,'+ alphaLevel +')';
 	ctx1.fillRect(0, 0, width, height);	
};



// preload  ---------------------------------------------------

// load content -----------------------------------------------
var loadContent = function(){
// pre rendering happens later, when all images are loaded....
	
	// then load rest into myLoader ----------------------	
	for (var i = 0; i < extraImg.length; i++){		
		myLoader.addFiles('extraLoaded'+ i + '*:'+ extraImg[i][0]);
	}	
	
	for (var i = 0; i < roomImg.length; i++){	
		myLoader.addFiles('roomLoaded'+ i +'*:'+ roomImg[i][0]);
	}
	
	for (var i = 0; i < situationImg.length; i++){
		myLoader.addFiles('situationLoaded'+ i +'*:'+ situationImg[i][0]);
	}
	
	for (var i = 0; i < characterImg.length; i++){	
		myLoader.addFiles('characterLoaded'+ i +'*:'+ characterImg[i][0]);
	}
	
};	



var preLoad = function(){
	preLoader.addFiles('loadingImg0*:'+ loadingImg[0][0]);
};



/*
var loadInArray = function(){
	// preload extra images -> fade in left and right
	for (var i = 0; i < extraImg.length; i++){		
		extraImg[i][7] = myLoader.getFile('extraLoaded'+i);
	}	

	// preload room images
	for (var i = 0; i < roomImg.length; i++){
		roomImg[i][7] = myLoader.getFile('roomLoaded'+i);
	}

	// preload situation images
	for (var i = 0; i < situationImg.length; i++){
		situationImg[i][3] = myLoader.getFile('situationLoaded'+i);
	}

	// load that.sceneCharacters
	for (var i = 0; i < characterImg.length; i++){	
		characterImg[i][7]= myLoader.getFile('characterLoaded'+i);
	}		
};	
*/


// init scenes ----------------------------------------
var initScene = function(buffer){
	// create scenes 
	var that = this;
	that.buffer = buffer;
	
	// add scene to scenes array
	scenes.push(new Scene(that.buffer));
};


var sceneChange = function(){
	if (debug == true){ console.dir("sceneChange triggered")};	

		
		var dir = Math.round( Math.random());				// move left to right -> or right to left <-
		elementChange = sceneLoopCount % 2;						// 0 = background, 1 = situation	

		if (elementChange == 1){
			scenes[0].changeBackground(dir);			// 0 = background, 1 = situation
		}																		
		if (elementChange == 0){
			scenes[0].changeSituation(dir);			// 0 = background, 1 = situation							
		}											
		
	sceneLoopCount++;		// increase loopcount (background/ situation change)
};



var scroll = function(){

};


// preRendering -------------------------------------------------------------
var preRender  = function(){
	if (debug2 == true){console.dir("--- pre render !!!!!---")};

	// pre render extra images
	for (var i = 0; i < extraImg.length; i++){
		extraImg[i][8] = document.createElement('canvas'); 		// canvas
		extraImg[i][8].width = extraImg[i][5];			
		extraImg[i][8].height = extraImg[i][6];					
		
		var cx = extraImg[i][8].getContext('2d');				// context		
//		cx.drawImage(extraImg[i][7], 0, 0);						// draw image to canvas
		cx.drawImage(myLoader.getFile('extraLoaded'+i), 0, 0);						// draw image to canvas		
	}


	// pre render room images
	for (var i = 0; i < roomImg.length; i++){
		roomImg[i][8] = document.createElement('canvas'); 		// canvas
		roomImg[i][8].width = roomImg[i][5];			
		roomImg[i][8].height = roomImg[i][6];					
		
		var cx = roomImg[i][8].getContext('2d');				// context		
		cx.drawImage(myLoader.getFile('roomLoaded'+i), 0, 0);						// draw image to canvas
	}	
	

	// pre render situation iamges
	for (var i = 0; i < situationImg.length; i++){
		situationImg[i][4] = document.createElement('canvas'); 		// canvas
		situationImg[i][4].width = situationImg[i][1];			
		situationImg[i][4].height = situationImg[i][2];					
		
		var cx = situationImg[i][4].getContext('2d');				// context		
		cx.drawImage(myLoader.getFile('situationLoaded'+i), 0, 0);						// draw image to canvas
	}	


	// pre render that.sceneCharacters
	for (var i = 0; i < characterImg.length; i++){	
		characterImg[i][8] = document.createElement('canvas'); 		// create offscreen canvas
		characterImg[i][8].width = characterImg[i][1];			
		characterImg[i][8].height = characterImg[i][2];					
		
		var cx = characterImg[i][8].getContext('2d');	// get drawing context		
		cx.drawImage(myLoader.getFile('characterLoaded'+i), 0, 0);			// draw image to canvas
	}

};



// the gameLoop -------------------------------------------------------------
var GameLoop = function(){
  	clear();
	scroll();  	
  	move();
	draw();
	mute();


	
  	gLoop = setTimeout(GameLoop, 1000 / 30);		// <--- Frame Rate ----- !!!
};

// the loadLoop -------------------------------------------------------------
// first load the page with document.ready function
// then load images, go into loadLoop and exit with window.load function
// into the Game Loop

var lLoop = null;			// global variable
var loopCount = 0;

var loadLoop = function(){
	
	if (debug2 == true){console.dir("--- loadLoop ---")};
	ctx1.fillStyle = "#BEB7B0";	
	ctx1.clearRect(0, 0, width, height);

	// draw the preload image
	ctx1.drawImage(preLoader.getFile('loadingImg0'), 0, 0);
	
	// draw the dots
	var count = loopCount % 4;
	switch (count){
		case 0: 
			break;
		case 1: 
			ctx1.fillRect(529, 300, 2, 2);
			break;
		case 2:
			ctx1.fillRect(529, 300, 2, 2);
			ctx1.fillRect(537, 300, 2, 2);			
			break;
		case 3:
			ctx1.fillRect(529, 300, 2, 2);
			ctx1.fillRect(537, 300, 2, 2);
			ctx1.fillRect(545, 300, 2, 2);			
			break;
	} 
	
	loopCount++;
	
	// exit loadLoop when all pictures loaded --------------
    myLoader.onfinish = function(){			
    	if (debug2 == true) {console.dir("--- loaded ---")};    	
    	
//    	loadInArray();
    	preRender();		// pre render all images as canvases to speed up drawing
    	

		if (debug2 == true){ console.dir("--- start ---")};	    	    
		initScene(ctx0);			// start moving in first scene			
		scrolling = false;
		scenes[0].move = true;							

    	clearTimeout(lLoop); 
		sLoop = setTimeout(sceneChange, 25000);				// change Scene in 25"			
					
		GameLoop();			// start the game and scene loops
		
	}
	
	lLoop = setTimeout(loadLoop, 500);
};


// program start and running ------------------------------------------------
	preLoad();								// the loading image
	
	preLoader.onfinish = function(){		// then the rest
		loadContent();
		loadLoop();
	};

	
});


// The end my friend

