/*=====================================================================================================================================

	---------------- DECLARATION VARIABLES ----------------

//===================================================================================================================================*/

var canvas;
var canvasContext;
var _xmouse;
var _ymouse;

var count = new Array();
var explodeBrique = new Array();
var listExplodingBrique = new Array();
var nbBalle = 1;
var table;
var grille;
var level = 1;
var balle = new Array();


/*=====================================================================================================================================

	---------------- *** DEBUT *** DEFINITION DES CLASSES ----------------

//===================================================================================================================================*/


var Ball = Class.create({
	initialize: function(radius){
		this._currentColor = 'rgba(0,92,157,1)';
		this._dir_x = 1;
		this._dir_y = 1;
		if(Math.random()<0.5)
			this._dir_x = -1;
		do{
			this._speed_x = Math.round(2+4*Math.random());
			this._speed_y = Math.round(2+4*Math.random());
		}while(this._speed_x == this._speed_y);
		this._canMove = true;
		this._radius = radius;
		this.losed = false;
		this.x = (canvas.width - this._radius) /2;
		this.y = (canvas.height - this._radius) /2;
		this.draw();
	},
	canMove: function(){
		if(this._canMove == true){
			this._canMove = false;
		}else{
			this._canMove = true;
		}	
	},
	draw: function(){
		canvasContext.fillStyle = this._currentColor;
		canvasContext.beginPath();
		canvasContext.arc(this.x, this.y, this._radius,0,Math.PI*2, true);
		canvasContext.closePath();
		canvasContext.fill();
	},
	erase: function(){
		canvasContext.fillStyle = "#cccccc";
		canvasContext.beginPath();
		canvasContext.arc(this.x, this.y, this._radius+1,0,Math.PI*2, true);
		canvasContext.closePath();
		canvasContext.fill();
	},
	move: function(){
		if(this._canMove == true){
			this.erase();
			this.x += this._speed_x*this._dir_x;
			this.y += this._speed_y*this._dir_y;
			if(this.x <= 0+(this._radius/2)) {
				this._dir_x = 1;
			}else if(this.x >= canvas.width-(this._radius/2)){
				this._dir_x = -1;
			}else if(this.y <= 0+(this._radius/2) ){
				this._dir_y = 1;	
			}else if(this.y > canvas.height-(this._radius/2)){
				this.losed = true;
				isGameOver();
			}
			this.draw();
		}
	}
});


var Grille = Class.create({
	initialize: function(motif){
		this.motif = motif;
		this.width = canvas.width-10;
		this.height = canvas.height/3;
		this.nbBriqueH;
		this.nbBriqueV;
		this.brique = new Array();
		this.colorList = [[153,153,153],[102,102,102],[51,51,51],[0,0,0]];
		this.x = 2;
		this.y = 5;
		this.loadGrille();
	},
	loadGrille: function(){
		var durete;
		var countSurprise = 0;
		var isSurprise = false;
		switch(this.motif){
			case 1:
				this.nbBriqueH = 8;
				this.nbBriqueV = 4;
				for(i=0; i<this.nbBriqueH;i++){
					for(j=0;j<this.nbBriqueV;j++){
						if(j > 1) durete = 1;
						else durete = 2;
						if(countSurprise < 5){
							if( Math.round(1+10*Math.random()) >= 8 ){
								isSurprise = true;
								countSurprise++;
							}
						}
						this.brique['brique'+i+'_'+j] = new Brique((i*100)+this.x,(j*35)+this.y,95,30,this.colorList[durete-1],durete,isSurprise);
						isSurprise = false;
					}
				}
				break;
			case 2:
				this.nbBriqueH = 8;
				this.nbBriqueV = 6;
				for(i=0; i<this.nbBriqueH;i++){
					for(j=0;j<this.nbBriqueV;j++){
						if(j > 1 && j <= 3) durete = 2;
						else if(j>3 ) durete = 1;
						else durete = 3;
						if(countSurprise < 6){
							if( Math.round(1+10*Math.random()) >= 8 ){
								isSurprise = true;
								countSurprise++;
							}
						}
						this.brique['brique'+i+'_'+j] = new Brique((i*100)+this.x,(j*35)+this.y,95,30,this.colorList[durete-1],durete,isSurprise);
						isSurprise = false;
					}
				}
				break;
			case 3:
				this.nbBriqueH = 8;
				this.nbBriqueV = 6;
				for(i=0; i<this.nbBriqueH;i++){
					for(j=0;j<this.nbBriqueV;j++){
						if(countSurprise < 5){
							if( Math.round(1+10*Math.random()) >= 8 ){
								isSurprise = true;
								countSurprise++;
							}
						}
						if(i%2 == 0){
							if(j%2 == 0){				
								this.brique['brique'+i+'_'+j] = new Brique((i*100)+this.x,(j*35)+this.y,95,30,this.colorList[1],2,isSurprise);		
							}else{ this.brique['brique'+i+'_'+j]=0; }
						}else{
							if(j%2 != 0){
								this.brique['brique'+i+'_'+j] = new Brique((i*100)+this.x,(j*35)+this.y,95,30,this.colorList[1],2,isSurprise);
							}else{ this.brique['brique'+i+'_'+j]=0; }
						}
						isSurprise = false;
					}
				}
				break;
			case 4:
				this.nbBriqueH = 8;
				this.nbBriqueV = 8;
				for(i=0; i<this.nbBriqueH;i++){
					for(j=0;j<this.nbBriqueV;j++){
						if(j!=2 && j!=5){
							this.brique['brique'+i+'_'+j] = new Brique((i*100)+this.x,(j*35)+this.y,95,30,this.colorList[0],1);
						}else{ this.brique['brique'+i+'_'+j]=0; }
					}
					
				}
				break;
			case 5:
				this.nbBriqueH = 8;
				this.nbBriqueV = 8;
				for(i=0; i<this.nbBriqueH;i++){
					for(j=0;j<this.nbBriqueV;j++){
						if(i!=2 && i!=5){
							this.brique['brique'+i+'_'+j] = new Brique((i*100)+this.x,(j*35)+this.y,95,30,this.colorList[0],1);
						}else{ this.brique['brique'+i+'_'+j]=0; }
					}
				}
				break;		
		}
	},
	draw: function(){
		for(i=0; i<this.nbBriqueH;i++){
			for(j=0;j<this.nbBriqueV;j++){
				if (this.brique['brique'+i+'_'+j] != 0) this.brique['brique'+i+'_'+j].draw();
			}
		}
	},
	erase: function(){
		for(i=0; i<this.nbBriqueH;i++){
			for(j=0;j<this.nbBriqueV;j++){
				if (this.brique['brique'+i+'_'+j] != 0) this.brique['brique'+i+'_'+j].erase();
			}
		}
	}
});

var Fragment = Class.create({
	initialize: function(x,y,l,h,coul){
		this._dir_x = 1;
		this._dir_y = 1;
		if(Math.random()<0.5)
			this._dir_x = -1;
		if(Math.random()<0.5)
			this._dir_y = -1;
		do{
			this._speed_x = Math.round(1+4*Math.random());
			this._speed_y = Math.round(1+4*Math.random());
		}while(this._speed_x == this._speed_y);
		this.x = x;
		this.y = y;
		this.l = l;
		this.h = h;
		this._color = coul;
		this.draw();
	},
	draw: function(){
		canvasContext.fillStyle = this._color;
		canvasContext.fillRect(this.x, this.y, this.l, this.h);
	},
	erase: function(){
		canvasContext.fillStyle = "#cccccc";
		canvasContext.fillRect(this.x, this.y, this.l, this.h);
	}
});

var Brique = Class.create({
	initialize: function(posx,posy,larg,haut,coul,hardness,surprise){
		this._hardness = hardness;
		this.beenTouched = 0;
		this.l = larg;
		this.h = haut;
		
		this.surprise = surprise;
		
		this._color = coul;
		
		this.lEclat = this.l/5;
		this.hEclat = this.h/2;
		this.eclat = new Array();
		this.destroyed = false;
		this.x = posx;
		this.y = posy;
		this.loadBrique();
	},
	loadBrique: function(){
		for(var i=0;i<this.l;i+=this.lEclat){
			for(var j=0; j<this.h; j+=this.hEclat){
				this.eclat['fragment'+i+'_'+j] = new Fragment(i+this.x,j+this.y,this.lEclat,this.hEclat,'rgba('+this._color[0]+','+this._color[1]+','+this._color[2]+',1)');
			}
		}
	},
	touch: function(){
		this.beenTouched++;
		if(this.beenTouched == this._hardness) this.destroyed = true;
	},
	explode: function(){
		grille.erase();
		for(var i=0;i<this.l;i+=this.lEclat){
			for(var j=0; j<this.h; j+=this.hEclat){
				this.eclat['fragment'+i+'_'+j].x += this.eclat['fragment'+i+'_'+j]._speed_x*this.eclat['fragment'+i+'_'+j]._dir_x;
				this.eclat['fragment'+i+'_'+j].y += this.eclat['fragment'+i+'_'+j]._speed_y*this.eclat['fragment'+i+'_'+j]._dir_y;				
			}
		}
		grille.draw();
	},
	draw: function(){
		for(var i=0;i<this.l;i+=this.lEclat){
			for(var j=0; j<this.h; j+=this.hEclat){
				this.eclat['fragment'+i+'_'+j].draw();
			}
		}
	},
	erase: function(){
		for(var i=0;i<this.l;i+=this.lEclat){
			for(var j=0; j<this.h; j+=this.hEclat){
				this.eclat['fragment'+i+'_'+j].erase();
			}
		}
	},
	changeOpacity: function(alpha){
		for(var i=0;i<this.l;i+=this.lEclat){
			for(var j=0; j<this.h; j+=this.hEclat){
				this.eclat['fragment'+i+'_'+j]._color = 'rgba('+this._color[0]+','+this._color[1]+','+this._color[2]+','+alpha+')';
			}
		}
	}
});


var Table = Class.create({
	initialize: function(larg,haut){
		this.l = larg;
		this.h = haut;
		this.x = (canvas.width/2) - this.l;
		this.y = 590;
		this._canMove = true;
		this.draw();
	},
	draw: function(){
		canvasContext.fillStyle = "#000000";
		canvasContext.fillRect(this.x, this.y, this.l, this.h);
	},
	erase: function(){
		canvasContext.fillStyle = "#cccccc";
		canvasContext.fillRect(this.x, this.y, this.l, this.h);	},
	move: function(param){
		if(this._canMove == true){
			this.erase();
			switch(param){
				case "mouse":
					var pos = _xmouse - this.l/2;
					this.x = pos;
					break;
				case "left":
					this.x -= 15;
					break;
				case "right":
					this.x += 15;
					break;
			}
			this.draw();
		}
	},
	canMove: function(){
		if(this._canMove == true){
			this._canMove = false;
		}else{
			this._canMove = true;
		}
	}
});

/*=====================================================================================================================================

	---------------- *** FIN *** DEFINITION DES CLASSES ----------------
	
	---------------- *** DEBUT *** MAIN ----------------

//===================================================================================================================================*/

function game(){
	table = new Table(100,5);
	table.canMove();
		
	grille = new Grille(level);
	
	for(var i=1;i<=nbBalle;i++){
		balle['ball'+i] = new Ball(10);
		balle['ball'+i].canMove();
	}
}

function isGameOver(){
	var gameover = true;
	for(var i=1;i<=nbBalle;i++){
		if(balle['ball'+i].losed == false){
			gameover = false;
		}
	}
	if(gameover == true){
		count = 0;
		explodeBrique = 0;
		listExplodingBrique = 0;
		count = new Array();
		explodeBrique = new Array();
		listExplodingBrique = new Array();
		
		canvasContext.fillStyle = "#cccccc";
		canvasContext.fillRect(0, 0, canvas.width, canvas.height);
		for(var i=1;i<=nbBalle;i++){
			balle['ball'+i].y = canvas.height + 100;
			balle['ball'+i] = 0;
			balle['ball'+i] = new Ball(10);
		}
		
		grille=0;
		grille = new Grille(level);
		
		table.l = 100;
		table.draw();
		
		alert("You've lost ! Try again");
	}
}

function isLevelComplete(){

	var levelComplete = true;
	for(var i=0;i<grille.nbBriqueH;i++){
		for(var j=0;j<grille.nbBriqueV;j++){
			if(grille.brique['brique'+i+'_'+j] != 0){
				return;
			}
		}
	}
	
	if(level == 5){
		alert("Fˇlicitations ! Vous avez fini le jeu !");
		canvasContext.fillStyle = "#cccccc";
		canvasContext.fillRect(0, 0, canvas.width, canvas.height);
	}else{
		level++ ;
		count = 0;
		explodeBrique = 0;
		listExplodingBrique = 0;
		count = new Array();
		explodeBrique = new Array();
		listExplodingBrique = new Array();
		
		canvasContext.fillStyle = "#cccccc";
		canvasContext.fillRect(0, 0, canvas.width, canvas.height);
		
		grille = 0;
		grille = new Grille(level);
		
		for(var i=1;i<=nbBalle;i++){
			balle['ball'+i].y = canvas.height + 100;
			balle['ball'+i] = 0;
			balle['ball'+i] = new Ball(10);
		}
		table.l = 100;
		table.draw();
		alert("Vous avez fini le niveau ! Passage au niveau "+level+".");
	}

}

function engine(){
			
	for(var i=1;i<=nbBalle;i++){
	
		if( balle['ball'+i].x  >= table.x 
			&& balle['ball'+i].x  <= table.x + table.l
			&& balle['ball'+i].y + (balle['ball'+i]._radius) >= table.y
			
			){
				balle['ball'+i]._dir_y = -balle['ball'+i]._dir_y;
				
				if( balle['ball'+i].x+(balle['ball'+i]._radius/2) > table.x + ((table.l/2)+(0.1*table.l)) ){
					// PARTIE DROITE
					
					if( balle['ball'+i]._dir_x == -1 ) balle['ball'+i]._dir_x = -balle['ball'+i]._dir_x;
					
					if (balle['ball'+i].x+(balle['ball'+i]._radius/2) > table.x + ((table.l/2)+(0.1*table.l)) 
						&& balle['ball'+i].x+(balle['ball'+i]._radius/2) <= table.x + ((table.l/2)+(0.2*table.l))){
						// ENTRE 60 ET 70 %;
						balle['ball'+i]._speed_x = 4;
						balle['ball'+i]._speed_y = 8;
						
					}else if(balle['ball'+i].x+(balle['ball'+i]._radius/2) > table.x + ((table.l/2)+(0.2*table.l))
							&& balle['ball'+i].x+(balle['ball'+i]._radius/2) <= table.x + ((table.l/2)+(0.3*table.l))){
						// ENTRE 70 ET 80 %;
						balle['ball'+i]._speed_x = 6;
						balle['ball'+i]._speed_y = 7;
						
					}else if(balle['ball'+i].x+(balle['ball'+i]._radius/2) > table.x + ((table.l/2)+(0.3*table.l))
							 && balle['ball'+i].x+(balle['ball'+i]._radius/2) <= table.x + ((table.l/2)+(0.4*table.l))){
						// ENTRE 80 ET 90 %;
						balle['ball'+i]._speed_x = 8;
						balle['ball'+i]._speed_y = 4;
					}else{
					   // 90 - 100;
					   balle['ball'+i]._speed_x = 10;
					   balle['ball'+i]._speed_y = 2;
					}

				}else if ( balle['ball'+i].x+(balle['ball'+i]._radius/2) < table.x + ((table.l/2)-(0.1*table.l)) ){
					// PARTIE GAUCHE
					if( balle['ball'+i]._dir_x == 1 ) balle['ball'+i]._dir_x = -balle['ball'+i]._dir_x;
										
					if (balle['ball'+i].x+(balle['ball'+i]._radius/2) >= table.x + ((table.l/2)-(0.4*table.l)) 
						&& balle['ball'+i].x+(balle['ball'+i]._radius/2) < table.x + ((table.l/2)-(0.3*table.l))){
						// ENTRE 0 ET 10 %;
						balle['ball'+i]._speed_x = 10;
						balle['ball'+i]._speed_y = 2;

					}else if(balle['ball'+i].x+(balle['ball'+i]._radius/2) >= table.x + ((table.l/2)-(0.3*table.l))
							&& balle['ball'+i].x+(balle['ball'+i]._radius/2) < table.x + ((table.l/2)-(0.2*table.l))){
						// ENTRE 10 ET 20 %;
						balle['ball'+i]._speed_x = 8;
						balle['ball'+i]._speed_y = 4;
					}else if(balle['ball'+i].x+(balle['ball'+i]._radius/2) >= table.x + ((table.l/2)-(0.2*table.l))
							 && balle['ball'+i].x+(balle['ball'+i]._radius/2) < table.x + ((table.l/2)-(0.1*table.l))){
						// ENTRE 0 ET 30 %;
						balle['ball'+i]._speed_x = 6;
						balle['ball'+i]._speed_y = 7;
					}else{
						// 30 - 40 %
						balle['ball'+i]._speed_x = 4;
						balle['ball'+i]._speed_y = 8;
					}
				}else{
				    // CENTRE ENTRE 40 et 60 %
				    balle['ball'+i]._speed_y = 10;
				    balle['ball'+i]._speed_x = 2;
				}
				
				
		}
		balle['ball'+i].move();
		table.draw();
	}
	
	for(var i=0;i<grille.nbBriqueH;i++){
		for(var j=0;j<grille.nbBriqueV;j++){						
			
			for(var k=1;k<=nbBalle;k++){
				if( (balle['ball'+k].y + (balle['ball'+k]._radius) >= grille.brique['brique'+i+'_'+j].y
					&& balle['ball'+k].y <= grille.brique['brique'+i+'_'+j].y + grille.brique['brique'+i+'_'+j].h
					&& balle['ball'+k].x + (balle['ball'+k]._radius) >= grille.brique['brique'+i+'_'+j].x
					&& balle['ball'+k].x  <= grille.brique['brique'+i+'_'+j].x + grille.brique['brique'+i+'_'+j].l)
					&& grille.brique['brique'+i+'_'+j].destroyed == false
					){
						balle['ball'+k]._dir_y = -balle['ball'+k]._dir_y;
						
						grille.brique['brique'+i+'_'+j].touch();
						
						if(grille.brique['brique'+i+'_'+j].destroyed == true){
							explodeBrique.unshift(true);
							listExplodingBrique.unshift('brique'+i+'_'+j);
							count.unshift(20);
							if(grille.brique['brique'+i+'_'+j].surprise == true){
									timeSurprise = 0;
									if(Math.random()<0.5){
										table.erase();
										table.l = 200;
										table.draw();
									}else{
										table.erase();
										table.l = 50;
										table.draw();
									}
							}
						}
				}	
			}
		}
	}
	for(i=0;i< listExplodingBrique.length ;i++){
		if(explodeBrique[i] == true){
			if(grille.brique[listExplodingBrique[i]] != 0){
				grille.brique[listExplodingBrique[i]].explode();
				grille.brique[listExplodingBrique[i]].changeOpacity(count[i]*0.05);
				count[i]--;
			}
			if(count[i] == 0){
				count[i] = 20;
				grille.brique[listExplodingBrique[i]].erase();
				grille.brique[listExplodingBrique[i]] = 0;
				grille.draw();
				listExplodingBrique.pop();
				count.pop();
				explodeBrique.pop();
				isLevelComplete();
			}
		}
	}
	
	if(timeSurprise == 250){
		timeSurprise = 0;
		table.erase();
		table.l = 100;
		table.draw();
		}else{
		timeSurprise++;
	}
	
	setTimeout("engine()",20);
}	

var timeSurprise = 0;

function initialize(){
	document.getElementById('status').innerHTML = 'Play/Pause : Space bar. Have fun, even if it\'s quite buggy ;)';
	canvas = document.getElementById('test_canvas');
	canvas.style.visibility = "visible";
	if (canvas.getContext){
		canvasContext = canvas.getContext('2d');
		canvasContext.fillStyle = "#cccccc";
		canvasContext.fillRect(0, 0, canvas.width, canvas.height);
		game();
		
		canvas.addEventListener('mousemove', ev_mousemove, false);
		document.addEventListener('keydown', ev_keydown, false);		
		setTimeout("engine()",15);
	}
}

function findPosElement(obj){
	var left = 0;
	var top = 0;
	while(obj.offsetParent != undefined && obj.offsetParent != null) {
			left += obj.offsetLeft;
			top += obj.offsetTop;
			obj = obj.offsetParent;
	}
	return [left,top];
}

function ev_keydown(ev){		
	if (window.event){
		keycode = window.event.keyCode;
	} 
	else if(ev){
		keycode = ev.which;	
	}
	
	switch(keycode){
		case 32:
			for(var i=1;i <= nbBalle; i++){
				balle['ball'+i].canMove();
			}
			table.canMove();
			break;
		case 37:
			table.move('left');
			//leftarrow
			break;
		case 39:
			table.move('right');
			//rightarrow
			break;
	
	}
}

function ev_mousemove(ev) {
	var coord = findPosElement(canvas);
  	_xmouse = ev._x - coord[0];
  	_ymouse = ev._y - coord[1];
	if (ev.layerX || ev.layerX == 0) { // Firefox
    	_xmouse = ev.layerX - coord[0];
    	_ymouse = ev.layerY - coord[1];
  	} else if (ev.offsetX || ev.offsetX == 0) { // Opera
    	_xmouse = ev.offsetX;
    	_ymouse = ev.offsetY;
 	}
  	table.move('mouse');

}

/*=====================================================================================================================================

	---------------- *** FIN *** MAIN ----------------

//===================================================================================================================================*/
