//CONSTANTS
var FIELDSIZE=28;	//blocks
var GRIDSIZE=20;	//pixel
var STEPSIZE=4;		//pixel
var FRAMERATE=70-1*8; 	//ms per step
var FIELDWIDTH=FIELDSIZE*GRIDSIZE;
var FACEBOOKURL="http://www.facebook.com/sharer.php?u=http://nettoman.ch/index.php?score=";

//VARS
var ddir=[0,0];	  	//desired direction of pacman
var dir=[0,0];	  	//actual direction of pacman
var pospac=[0,0]; 	//position of pacman
var pospac_init=[0,0]; 	//position of pacman
var hprio=true;		//true if last pressed key is left or right
var dots=new Array();	//holder for dots
var ndots;		//number of dots on screen
var status=0;		//0->stopped, 1->running, 2->paused, 3->stalled
var ghosts=[];		//holder for ghost-divs
var ghostpos=[];	//two-dim-array of ghostpostions
var ghostpos_init=[];
var ghostdir=[];	//two-dim-array of ghostdirections
var nghosts=0; 		//numer of ghosts on screen;
var ngoodies=0; 	//numer of ghosts on screen;
var timer;		//setTimeout ID
var timer2;		//setTimeout ID
var timer3;		//setTimeout ID
var counter=0;		//stepcounter for gameplay timing

var lives=3;
var level=1;
var score=0;
var highscore=0;
var intelligence=0.2; //intelligence factor 0-1
var pacsprite;
var ztable=new Array();
var btable=new Array();

var levelnum;
var scorenum;
var highnum;
var tram;
var trampos=[12*GRIDSIZE,-40];
var tram_moving=false;
var reversed=false;

var soundon=true;

//soundmanager
soundManager.url = 'js/soundmanager/swf/'; // directory where SM2 .SWFs live
soundManager.waitForWindowLoad = true;
// Experimental HTML5 audio support (force-enabled for iPad)
soundManager.useHTML5Audio = false;
// do this to skip flash block handling for now. 
soundManager.useFlashBlock = false;
// disable debug mode after development/testing..
soundManager.debugMode = false;
soundManager.allowPolling = false;
soundManager.useHighPerformance=true;
soundManager.useMovieStar=false;
soundManager.defaultOptions={
	stream:false,
	autoLoad:true
}

soundManager.onload = function() {
	if(!soundManager.canPlayURL('res/sound/Die.mp3')){
		soundon=false;
		$('soundonoff').hide();
		return;
	}
  soundManager.createSound({
    id: 'sound_die',
    url: 'res/sound/Die.mp3'
  });
  soundManager.createSound({
    id: 'sound_complete',
    url: 'res/sound/Complete.mp3'
  });
  soundManager.createSound({
    id: 'sound_gameover',
    url: 'res/sound/GameOver.mp3'
  });
  soundManager.createSound({
    id: 'sound_goodie',
    url: 'res/sound/Goodie.mp3'
  });
   soundManager.createSound({
    id: 'sound_respect',
    url: 'res/sound/Respect.mp3'
  });
    soundManager.createSound({
    id: 'sound_eat',
    url: 'res/sound/Eat.mp3'
  });
  soundManager.load('sound_die',{volume:100,onload:soundloaded});
  soundManager.load('sound_complete',{volume:100,onload:soundloaded});
  soundManager.load('sound_gameover',{volume:100,onload:soundloaded});
  soundManager.load('sound_goodie',{volume:100,onload:soundloaded});
  soundManager.load('sound_respect',{volume:100,onload:soundloaded});
  soundManager.load('sound_eat',{volume:30,onload:soundloaded});
}
soundManager.onerror = function() {
	soundon=false;
	$('soundonoff').hide();
}
function soundloaded(){
	
}

/*
0-f ->block
- ->dot
p ->pacman
g ->ghost
*/
var maze="\
000000000000- 55555555555555\
000000-00000- 55555555555555\
000000-22222- 55555555555555\
000000-22222- 55555555555555\
000----22222- 55555555555555\
111111-22222- 55555555555555\
111111------- 55555555555555\
111111-33333- 55555555555555\
111111-33333- 55555555555555\
111111-33333p -----555555555\
111111-33333- 6666----- 5555\
111111-33333- 6666-888888888\
111111-33333- 6666-888888888\
111111-------------888888888\
111111-44g44- 7777-888888888\
111111-4ggg4- 7777-888888888\
111111-44444- 7777-888888888\
111111-44444- 7777-888888881\
----------------------------\
888888-99999- bbbb-cccccccc8\
888888-99999- bbbb-ccccccccc\
888888-99999- bbbb-ccccccccc\
888888-99999- bbbb-ccccccccc\
888888------- bbbb-ccccccccc\
8888888aaaaa- bbbb-ccccccccc\
8888888aaaaa-------ccccccccc\
8888888aaaaa- cccccccccccccc\
8888888aaaaa- cccccccccccccc";


Event.observe(window, 'load', preload);

function preload(){
	//preloadimages(['snd-off','snd-on','start-game.png','paused.png','level-complete.png','game-complete.png','game-over.png','level-complete.png','0-black','1-black','2-black','3-black','4-black','5-black','6-black','7-black','0-black','9-black','0-white','1-white','2-white','3-white','4-white','5-white','6-white','7-white','0-white','9-white','dot','pill','credit','ghost-l','ghost-r','ghost-u','ghost-d','pl-1','pl-2','pd-1','pd-2','pu-1','pu-2','pr-1','pr-2','f1'], init); //calls init() when complete
	preloadimages(['Die.mp3','Complete.mp3','GameOver.mp3','Goodie.mp3','Eat.mp3','Respect.mp3','snd-off','snd-on','start-game.png','paused.png','level-complete.png','game-complete.png','game-over.png','level-complete.png','0-black','1-black','2-black','3-black','4-black','5-black','6-black','7-black','0-black','9-black','0-white','1-white','2-white','3-white','4-white','5-white','6-white','7-white','0-white','9-white','dot','pill','credit','ghost-l','ghost-r','ghost-u','ghost-d','pl-1','pl-2','pd-1','pd-2','pu-1','pu-2','pr-1','pr-2','f1'], init); //calls init() when complete
}
function init(){
	$('all').show();
	levelnum = new Num(258,13,1, 'white', $('info'));
	scorenum = new Num(374,13,4, 'white', $('info'));
	highnum = new Num(488,13,4, 'white', $('info'));
	highnum.setvalue(0);
	pacsprite=new Sprite([['pl-1','pl-2'],['pu-1','pu-2'],['pd-1','pd-2'],['pr-1','pr-2'], ['pl-1','blank','pl-1','blank','pl-1','blank','pl-1','blank'],['pu-1','blank','pu-1','blank','pu-1','blank','pu-1','blank'],['pd-1','blank','pd-1','blank','pd-1','blank','pd-1','blank'],['pr-1','blank','pr-1','blank','pr-1','blank','pr-1','blank']], 0,0);
	pacsprite.hide();
	tram=new Sprite([['tram']],0,0);
	tram.hide();
	drawfield();
	document.observe('keydown', respondToKeyDown);
	document.observe('keyup', respondToKeyUp);
	updatescore(0);
	updatelives(0);
	updatelevel(0);
	newgame();
}
function newgame(){
	if($('start2')){$('start2').remove();}
	showinfo('start-game', restart);
	clearInterval(timer);
	status=0;
}

 function respondToKeyDown(event) {
	 switch(event.keyCode){
		case Event.KEY_LEFT:
		case 81:
			ddir[0]=-STEPSIZE;
			hprio=true;
			break;
		case Event.KEY_RIGHT:
		case 83:
			ddir[0]=STEPSIZE;
			hprio=true;
			break;
		case Event.KEY_UP:
		case 87:
			ddir[1]=-STEPSIZE;
			hprio=false;
			break;
		case Event.KEY_DOWN:
		case 65:
			ddir[1]=STEPSIZE;
			hprio=false;
			break;
		case 80: //p pause
			togglePause();
			break;
		case 78: //n new game
			newgame();
			break;
	 }
}
 function respondToKeyUp(event) {
	 switch(event.keyCode){
		case Event.KEY_LEFT:
		case 81:
			ddir[0]=0;
			break;
		case Event.KEY_RIGHT:
		case 83:
			ddir[0]=0;
			break;
		case Event.KEY_UP:
		case 87:
			ddir[1]=0;
			break;
		case Event.KEY_DOWN:
		case 65:
			ddir[1]=0;
			break;
	 }
}


function run(){
	if(status==1){ //running
		movetram();
		counter++;
		var p0=pospac[0]; //local copy
		var p1=pospac[1]; //local copy
		var odir=[dir[0], dir[1]];
		var horcross=(p0%GRIDSIZE==0);
		var vercross=(p1%GRIDSIZE==0);
		
		if(isfree(p0+ddir[0], p1, ddir) && ddir[0]!=0){
			dir[0]=ddir[0];
		}
		if(isfree(p0, p1+ddir[1], ddir) && ddir[1]!=0){
			dir[1]=ddir[1];
		}
		if(!vercross || !isfree(p0+dir[0], p1, dir)){
			dir[0]=0;
		}
		if(!horcross || !isfree(p0, p1+dir[1], dir)){
			dir[1]=0;
		}
		if(dir[0]!=0 && dir[1]!=0){
			if(hprio){
				dir[1]=0;
			}
			else{
				dir[0]=0;
			}
		}
		if(horcross && vercross) {
			var i=p1/GRIDSIZE;
			var j=p0/GRIDSIZE;
			eat(i,j);
			
			if(dir[1] < 0){i=(i>0)? i-1: FIELDSIZE-1;}
			else if(dir[1]>0){i=(i<FIELDSIZE-1)? i+1: FIELDSIZE-1;}
			if(dir[0]<0){j=(j>0)? j-1: FIELDSIZE-1;}
			else if(dir[0]>0){j=(j<FIELDSIZE-1)? j+1: FIELDSIZE-1;}
			var zindex=ztable[i][j];
			pacsprite.setz(zindex);
		}
		//change pospac
		pospac[0]+=dir[0];
		pospac[1]+=dir[1];
		//horizontal rollover
		if(pospac[0]>=FIELDWIDTH) {
			pospac[0]=-GRIDSIZE+STEPSIZE;	
		}
		if(pospac[0]<=-GRIDSIZE) {
			pospac[0]=FIELDWIDTH-STEPSIZE;
		}
		
		//vertical rollover
		if(pospac[1]>=FIELDWIDTH) pospac[1]=-GRIDSIZE+STEPSIZE;
		if(pospac[1]<=-GRIDSIZE) pospac[1]=FIELDWIDTH-STEPSIZE;

		//rotate pac
		if((odir[0]!=dir[0] || odir[1]!=dir[1]) && (dir[1]+dir[0])!=0){ //todo:perf
			var dirnum=(2*dir[0]+dir[1])/STEPSIZE+2;
			dirnum=(dirnum>2)?dirnum-1: dirnum;
			pacsprite.setscene(dirnum);
		}
		//move pac
		pacsprite.move(pospac[0], pospac[1]);
		//check for collisions
		var i;
		for(i=0; i<nghosts; i++){
			if(iscollision(pospac, ghostpos[i]) && ghosts[i].enabled){
				if(!reversed){ //die
					die(ghosts[i]);
				}
				else{ //eat banker
					ghostpos[i][0]=ghostpos_init[i][0];
					ghostpos[i][1]=ghostpos_init[i][1];
					ghosts[i].setz(0);
					ghosts[i].move(ghostpos[i][0], ghostpos[i][1]);
					ghosts[i].hide();
					ghosts[i].enabled=false;
					updatescore(40);
					if(soundon)soundManager.play('sound_respect');
				}
			}
		}
		for(i=nghosts; i<nghosts+ngoodies; i++){
			if(iscollision(pospac, ghostpos[i])){
				var s=ghosts[i].getscene();
				eatgoodie(i, s);
			}
		}
		moveghosts();
	}
	//update sprites
	if(status!=2 && status!=0) { //not paused
		pacsprite.update();
		var z;
		if(reversed){
			for(z=0; z<nghosts; z++){
				ghosts[z].update();
			}
		}
	}
}

function moveghosts(){
	var i,j;
	for (i=0; i<nghosts+ngoodies; i++){
		if(!ghosts[i].enabled) return;
		
		var p0=ghostpos[i][0]; //local copy
		var p1=ghostpos[i][1]; //local copy
		
		var potdir=[ghostdir[i][0],ghostdir[i][1]];
		var cross=((p0%GRIDSIZE==0) && (p1%GRIDSIZE==0));
		var dirchange=(Math.random()<0.5) && cross;
		
		if(dirchange){
			if(Math.random()<intelligence){
				if(Math.random()<0.5){
					potdir[0]=(pospac[0]-p0 > 0)? STEPSIZE: -STEPSIZE;
					potdir[1]=0;
				}
				else{
					potdir[0]=0;
					potdir[1]=(pospac[1]-p1 > 0)? STEPSIZE: -STEPSIZE;
				}
			}
			else{
				potdir[0]=(Math.floor(Math.random()*3)-1)*STEPSIZE;
				potdir[1]=(potdir[0]==0)? (Math.floor(Math.random()*3)-1)*STEPSIZE: 0;
			}
		}
		//collisions ghost2ghost
		var c=false;
		for (j=nghosts-1; j>=0; j--){
			if(i!=j && iscollision([p0+potdir[0], p1+potdir[1]], ghostpos[j])){
				c=true;
				potdir[0]=-potdir[0];
				potdir[1]=-potdir[1];
				break;
			}
		}
		if(isfree(p0+potdir[0], p1+potdir[1], potdir)){
			if(cross){
				var ii=p1/GRIDSIZE;
				var jj=p0/GRIDSIZE;
				
				//if(potdir[1]<0){ii--;}
				//if(ii<0)ii=0;
				
				if(potdir[1] < 0){ii=(ii>0)? ii-1: FIELDSIZE-1;}
				else if(potdir[1]>0){ii=(ii<FIELDSIZE-1)? ii+1: FIELDSIZE-1;}
				if(potdir[0]<0){jj=(jj>0)? jj-1: FIELDSIZE-1;}
				else if(potdir[0]>0){jj=(jj<FIELDSIZE-1)? jj+1: FIELDSIZE-1;}
				
				
				var zindex=ztable[ii][jj];
				ghosts[i].setz(zindex);
				//rotate ghost
				if(i<4){
					var dirnum=(2*potdir[0]+potdir[1])/STEPSIZE+2;
					dirnum=(dirnum>2)?dirnum-1: dirnum;
					ghosts[i].setscene(dirnum);
				}
			}
			ghostdir[i][0]=potdir[0];
			ghostdir[i][1]=potdir[1];
			ghostpos[i]=[p0+potdir[0], p1+potdir[1]];
			//horizontal rollover
			if(ghostpos[i][0]>=FIELDWIDTH) {ghostpos[i][0]=-GRIDSIZE+STEPSIZE;}
			if(ghostpos[i][0]<=-GRIDSIZE) {ghostpos[i][0]=FIELDWIDTH-STEPSIZE;}
			//vertical rollover
			if(ghostpos[i][1]>=FIELDWIDTH) {ghostpos[i][1]=-GRIDSIZE+STEPSIZE;}
			if(ghostpos[i][1]<=-GRIDSIZE) {ghostpos[i][1]=FIELDWIDTH-STEPSIZE;}
			//move ghost
			ghosts[i].move(ghostpos[i][0], ghostpos[i][1]);
		}
		
	}
}

function movetram(){
	if(!tram_moving){return;}
	var c=false;
	var i=Math.floor(trampos[1]/GRIDSIZE)+1;
	var j=Math.floor(trampos[0]/GRIDSIZE);
	for(var z=0; z<nghosts; z++){
		if(iscollision_tram(trampos, ghostpos[z])){
			c=true;
		}
	}
	if(iscollision_tram(trampos, pospac)){
		c=true;
	}
	if(i<FIELDSIZE-1 && trampos[1]>0){
		btable[i+1][j]=1;
		if(c)btable[i+1][j]=0;
	}
	if(i<FIELDSIZE && trampos[1]>=0){
		btable[i][j]=1;
	}
	
	if(i>1){
		btable[i-2][j]=0;
	}
	if(i>=0 && i<FIELDSIZE) {
		//var ii=(i>0)?i-1: i;
		tram.setz(ztable[i][j]);
	}
	if(c)return;
	
	trampos[1]+=3;
	if(trampos[1]>=FIELDWIDTH){ //remove tram
		removetram();
	}
	tram.move(trampos[0]-8,trampos[1]-5);
}
function removetram(){
	var j=Math.floor(trampos[0]/GRIDSIZE);
	var i=Math.max(Math.floor(trampos[1]/GRIDSIZE)-2, 0);
	for(z=i; z<FIELDSIZE; z++){
		btable[z][j]=0;
	}
	trampos[1]=-40;
	tram_moving=false;
	tram.hide();
}

function isfree(x, y, dir){
	var testx=(dir[0]>0)? x+GRIDSIZE-1: x;
	var testy=(dir[1]>0)? y+GRIDSIZE-1: y;
	var i=Math.floor(testy/GRIDSIZE);
	var j=Math.floor(testx/GRIDSIZE);
	return (testx<0 || testy<0 || testx>=FIELDWIDTH || testy>=FIELDWIDTH || !btable[i][j]);
	var character=maze.charAt(i*FIELDSIZE+j);
	return (character!='#' && character!='@') || testx<0 || testx>=GRIDSIZE*FIELDSIZE;
}
function iscollision(p1,p2){
	return (p1[0]==p2[0] || p1[1]==p2[1]) && Math.abs(p1[0]-p2[0])<20 && Math.abs(p1[1]-p2[1])<20;
}
function iscollision_tram(p1,p2){
	return (Math.abs(p1[0]-p2[0])<20 && Math.abs(p1[1]-p2[1])<60);
}

function eat(i,j){ //eat dot
	var index=i*FIELDSIZE+j;
	if(dots[index]){
		if(dots[index].visible()){
			if(soundon){soundManager.play('sound_eat');}
			dots[index].hide(); 
			ndots--;
			updatescore(3);
			if((ndots%45==0) && !tram_moving){ //start tram
				tram.setz(500);
				tram_moving=true;
				btable[0][12]=1;
				tram.move(trampos[0]-8,trampos[1]-5);
				tram.show();
			}
			if(ndots==116 || ndots==70 || ndots==40){
				addgoodie(Math.floor(Math.random()*17)+2,11);
			} 
			if(ndots==0){
				if(soundon) soundManager.play('sound_complete');
				if(counter<3000){ //add bonus points
					updatescore(Math.floor((3000-counter)/100));
				}
				
				if(level<3){
					showinfo('level-complete', startlevel);
				}
				else{
					showinfo('game-complete', newgame);
				}
				status=3;
			}
		}
	}
	
}

function die(enemy){
	var s=pacsprite.getscene();
	pacsprite.setscene(s+4);
	pacsprite.once=true;
	lives--;
	if(lives<=0){
		if(soundon) soundManager.play('sound_gameover');
		showinfo('game-over', newgame);
		status=0; //stopped
	}
	else{
		timer2=setTimeout('reset()', 3000);
		if(soundon) soundManager.play('sound_die');
		status=3; //stalled
	}
}
function reset(){ // reset for start of level
	updatelives(0);
	clearTimeout(timer2);
	//remove goodies
	var i;
	for(i=4; i<ghosts.length; i++){
		if(ghosts[i]){
			try{ghosts[i].remove();}catch(e){}
		}
	}
	ghosts.length=4;
	ngoodies=0;
	resetfield();
	if(status!=2){
		status=1;
	}
	reversed=false;
	//remove tram
	removetram();
}
function startlevel(){ //start next level
	FRAMERATE=60-level*7;
	intelligence+=0.2;
	counter=0;
	clearInterval(timer);
	timer=setInterval(run, FRAMERATE);
	hideinfo();
	reset();
	resetdots();
	updatelevel(1);
}
function restart(){
	level=0;
	lives=3;
	score=0;
	intelligence=0.2;
	status=1; //running
	updatelives(0);
	updatescore(0);
	startlevel();
	pacsprite.show();
	for(var i=0; i<nghosts; i++){
		ghosts[i].show();
	}
}

function drawfield(){ //init ztable, btable
	for(i=0; i<FIELDSIZE; i++){ //rows
		ztable[i]=new Array();
		btable[i]=new Array();
		for(j=0; j<FIELDSIZE; j++){ //columns
			var index=i*FIELDSIZE+j;
			var thechar=maze.charAt(index);
			var isfree=thechar=="-" || thechar=="p" || thechar=="g" || thechar==" ";
			if(isfree){
				ztable[i][j]=0;
				btable[i][j]=false;
			}
			else {
				ztable[i][j]=parseInt(maze.charAt(index), 16)*4;
				btable[i][j]=true;
			}
		}
	}
	for(i=0; i<FIELDSIZE; i++){ //rows
		for(j=0; j<FIELDSIZE; j++){ //columns
			var index=i*FIELDSIZE+j;
			var thechar=maze.charAt(index);
			if(!btable[i][j]){ //isfree
				if(i>0 && btable[i-1][j]){
					ztable[i][j]=ztable[i-1][j]+1;
				}
				else if(j>0  && btable[i][j-1]){
					ztable[i][j]=ztable[i][j-1]+1;
				}
				if(ztable[i][j]==0){
					ztable[i][j]=ztable[i][j-1]+1;
				}
				if(thechar=='g'){ //ghost
					pos=translate(j*GRIDSIZE, i*GRIDSIZE);
					var ghost=new Sprite([['ghost-l','blank'],['ghost-u','blank'],['ghost-d','blank'],['ghost-r','blank']],pos[0],pos[1]);
					ghost.hide();
					ghosts.push(ghost);
					ghostpos.push([j*GRIDSIZE,i*GRIDSIZE]);
					ghostpos_init.push([j*GRIDSIZE,i*GRIDSIZE]);
					ghostdir.push([0,-STEPSIZE]);
					nghosts++;
					maze=setChars(maze, index, ' ');
				}
				else if(thechar=='p'){ //pacman
					pospac=[j*GRIDSIZE,i*GRIDSIZE];
					pospac_init=[j*GRIDSIZE,i*GRIDSIZE];
					pacsprite.move(pospac[0],pospac[1]);
					maze=setChars(maze, index, '-');
				}
				else if(thechar=='-'){ //dot
					pos=translate(j*GRIDSIZE+GRIDSIZE/2, i*GRIDSIZE+GRIDSIZE/2);
					var dot = new Element('div', {'class': 'dot','style': 'left:'+pos[0]+'px;top:'+pos[1]+'px'});
					dot.hide();
					dot.style.zIndex=ztable[i][j]-1;
					Element.insert($('main'), dot);
					dots[index]=dot;
					ndots++;
				}
			}
		}
	}
}

function resetfield(){	//move pac and ghosts to initial position
	var i;
	for(i=0; i<nghosts; i++){
		ghostpos[i]=[ghostpos_init[i][0],ghostpos_init[i][1]];
		ghostdir[i]=[0,0];
	}
	pospac=[pospac_init[0],pospac_init[1]];
	pacsprite.move(pospac[0], pospac[1]);
	dir=[0,0];
	pacsprite.setscene(2);
	pacsprite.once=false;
	pacsprite.show();
}
function resetdots(){
	var i;
	var n=dots.length;
	ndots=0;
	for(i=0; i<n; i++){
		if(dots[i]){
			dots[i].show();
			ndots++;
		}
	}
}

function addgoodie(i,j){
	if(ngoodies>0 || reversed)return;
	var pos=translate(j*GRIDSIZE, i*GRIDSIZE);
	var goodie=new Sprite([['f1'],['f1'],['pill'],['pill'],['pill'],['pill'],['pill'],['pill']],pos[0],pos[1]);
	var ran=Math.floor(Math.random()*8);
	goodie.setscene(ran);
	ghosts[nghosts]=goodie;
	ghostpos[nghosts]=[j*GRIDSIZE,i*GRIDSIZE];
	ghostpos_init[nghosts]=[j*GRIDSIZE,i*GRIDSIZE];
	ghostdir[nghosts]=[0,-STEPSIZE]
	ngoodies++;
}
function eatgoodie(i, s){
	if(ghosts.length>i){
		if(soundon) soundManager.play('sound_goodie');
		var elem=ghosts[i];
		elem.remove(); //remove goodie
		if(s>1){ //is pill
			reversed=true;
			timer2=setTimeout(endreversed, 10000);
		}
		else{  // add bonus 
			var bonuspoints=(s+2)*20;
			updatescore(bonuspoints);
			var p=translate(pospac[0],pospac[1]-20);
			bonus=new Num( p[0], p[1], 2, 'black', $('main'));
			bonus.setvalue(bonuspoints);
			bcount=0;
			timer3=setInterval(animbonus, 100);
		}
		ngoodies--;
	}
}

function endreversed(){
	var i;
	reversed=false;
	for(i=0; i<nghosts; i++){
		ghosts[i].seti(0);
		ghosts[i].show();
	}
	timer2=setTimeout(endreversed_, 2000);
}
function endreversed_(){
	var i;
	for(i=0; i<nghosts; i++){
		ghosts[i].enabled=true;
	}
}

var bcount=0;
function animbonus(){
	if(bcount<20){
		bonus.moveBy(0,-1);
	}else{
		clearInterval(timer3);
		bonus.hide();
	}
	bcount++;
}

function updatescore(d){
	score+=d;
	scorenum.setvalue(score);
}
function updatelives(d){
	lives+=d;
	Element.update($('lives'),"");
	var i;
	for(i=0; i<lives-1; i++){
		var l = new Element('img', {'class': 'credit','src': 'res/images/credit.gif'});
		Element.insert($('lives'), l);
	}
}
function updatelevel(d){
	level+=d;
	levelnum.setvalue(level);
}

function togglePause(){
	if(status!=0){
		if(status==2){ //paused
			status=1;
			hideinfo();
		}
		else if(status==1 || status==3){ //running or stalled
			status=2;
			showinfo('paused', togglePause);
		}
	}
}
function toggleSound(){
	soundon=!soundon;
	if(soundon){
		soundManager.setVolume('sound_die',100);
		soundManager.setVolume('sound_gameover',100);
		soundManager.setVolume('sound_complete',100);
		soundManager.setVolume('sound_respect',100);
		soundManager.setVolume('sound_goodie',100);
		soundManager.setVolume('sound_eat',30);
		$('soundonoff').src="res/images/snd-on.gif";
	}
	else{
		soundManager.setVolume('sound_die',0);
		soundManager.setVolume('sound_gameover',0);
		soundManager.setVolume('sound_complete',0);
		soundManager.setVolume('sound_respect',0);
		soundManager.setVolume('sound_goodie',0);
		soundManager.setVolume('sound_eat',0);
		$('soundonoff').src="res/images/snd-off.gif";
	}
}

function showinfo(str, func){
	var img = new Element('img', {'class': 'infopic','src': 'res/images/'+str+'.png'});
	Element.update($('infodisplay'), img);
	if(str=='game-over' || str=='game-complete'){
		var s=new Num(202,75, 4, 'black', $('infodisplay'));
		s.setvalue(score);
		if(score>highscore){
			highscore=score;
			highnum.setvalue(score);
		}
		var facebook=new Element('img', {'class': 'facebook','src': 'res/images/share-on-facebook.gif'});
		Element.insert($('infodisplay'), facebook);
		facebook.onclick=function(){window.open(FACEBOOKURL+score, "_blank");};
	}
	img.onclick=func;
	if(func!=null){
		$('infodisplay').style.cursor="pointer";
	}
	$('infodisplay').show();
}

function hideinfo(str){
	$('infodisplay').hide();
}

function translate(px,py){
	return [((px-py)+469)*1.02, (((py+px)/2)+63)*1.02];
}

//utils
function setChars (s, at, c) { 
	return s.substr(0,at) + c.substr(0,s.length-at) + s.substr(at + c.length);
}
function debug(msg){
	$('debug').innerHTML=msg;
}


