// JavaScript Document
// CanvasQuest .8
// status: major rewrite

function gameObj(){ };
 
gameObj.prototype = {
  version: 0.5,
  numRes: 0,
  imgLib : [],
  theChar: {},
  monstArr : [],
  itemArr : [],
  statusText : "",
  bgCount: 0,
  statusChanged : false,
  currMap: "",
  init: function(){
    //alert("welcome to CanvasQuest version: "+this.version)
    levelSetup();
    this.setupBg('bgCanvas'+this.bgCount);
    this.setupConsole();
    this.draw();
    window.addEventListener('keydown',doKeyDown,true);
  },
  load: function(lvlurl){
    //document.getElementById('gamedef').setAttribute('src',lvlurl);
    var newjs = document.createElement('script');
    newjs.setAttribute('src',lvlurl);
    //tileMap = null;
    //newjs.setAttribute('id','gamedef');
    document.getElementsByTagName('head')[0].appendChild(newjs)
    
    //this.init();
    //this.setupBg('newBGCanvas')
    //this.imgLib['bgCanvas'] = this.imgLib['newBGCanvas']
    //this.bgCount++;
    setTimeout('theGame.init()',2000);
  },
  pick: function(){
    this.load(prompt('choose a level file',''))
  },
  setupBg : function(bgc){
    //alert('setupbg')
    this.imgLib[bgc] = null;
    this.imgLib[bgc] = document.createElement('canvas');
    this.imgLib[bgc].setAttribute('width', 320);
    this.imgLib[bgc].setAttribute('height',320);
    //alert(this.imgLib['bgCanvas'])
    var ctx = this.imgLib[bgc].getContext('2d');
    for(i = 0; i < 10; i++){
		  for(j = 0; j < 10; j++){
			 ctx.drawImage(document.getElementById(tileMap[i][j].id),tileMap[i][j].x, tileMap[i][j].y,32,32,j*32,i*32,32,32)
		  }
    }
  },
  setupConsole: function(){
    this.imgLib['ui'] = document.getElementById('ui');
    this.imgLib['bgConsole'] = document.createElement('canvas');
    this.imgLib['bgConsole'].setAttribute('width',320);
    this.imgLib['bgConsole'].setAttribute('height',100);
    var ctx = this.imgLib['bgConsole'].getContext('2d');
    ctx.fillRect(0,0,320,100);
    ctx.drawImage(this.imgLib['ui'],0,0);
    ctx.fillStyle='white';
    ctx.fillRect(0,35,320,1)
    ctx.fillStyle='black';
    this.statusText = "Welcome to CanvasQuest";
    this.statusChanged = true;
    this.updateStatus();
  },
  updateStatus: function(){
    if(this.statusChanged){
      this.imgLib['status'] = document.createElement('canvas');
      this.imgLib['status'].setAttribute('width',320);
      this.imgLib['status'].setAttribute('height',100);
      var ctx = this.imgLib['status'].getContext('2d');
      ctx.drawImage(getString(this.statusText), 5,45); 
      ctx.drawImage(getString(""+this.theChar.health),62,6);
      ctx.drawImage(getString(""+this.theChar.gold),172,6);
      this.statusChanged = false;  
    }
  },
  updateWorld : function(){
    for(i=0; i<this.monstArr.length; i++){
      this.monstArr[i].randomMove();
    } 
    this.updateStatus(); 
  },
  savegame: function (){
    setCookie('health',this.theChar.health);
    setCookie('gold', this.theChar.gold);

    setCookie('currMap',this.currMap)
    this.statusText = "Game Saved";
    this.statusChanged = true;
    this.updateStatus();
    this.draw();
  },
  loadgame: function (){
    this.theChar.health = eval(getCookie('health'));
    this.theChar.gold = eval(getCookie('gold'));
    this.load(getCookie('currMap'))


    this.statusText = "Game Loaded";
    this.statusChanged = true;
    this.updateStatus();
    this.draw();
  },
  draw : function (){
    this.updateWorld();
    var ctx = document.getElementById('screen').getContext('2d');
    ctx.clearRect(0,0,320,320)
    ctx.drawImage(this.imgLib['bgCanvas'+this.bgCount],0,0);
    ctx.drawImage(this.imgLib['bgConsole'],0,320);
    ctx.drawImage(this.imgLib['status'],0,320);
    

    for (t=0;t<this.itemArr.length; t++){
      if(this.itemArr[t].health >0){
        ctx.drawImage(this.itemArr[t].canvas, this.itemArr[t].x, this.itemArr[t].y);
      }
    }
    for(i=0; i<this.monstArr.length; i++){
      if(this.monstArr[i].health > 0){
        ctx.drawImage(this.monstArr[i].canvas, this.monstArr[i].x, this.monstArr[i].y);
      }
    }
    
    ctx.drawImage(this.theChar.canvas,this.theChar.x,this.theChar.y)
  }
  
}
function tileObj(id,x,y,col) {
	this.id = id;
	this.x = x;
	this.y = y;
	this.collision = col;
}
function eventObj(id,x,y,evtStr){
  this.id = id;
  this.x = x;
  this.y = y;
  this.eventStr = evtStr;
  this.toMap = ''
}

function charObj(id,imgX,imgY,mapX,mapY){
  this.canvas = document.createElement('canvas');
	this.canvas.setAttribute('width',32);
	this.canvas.setAttribute('height',32);
	this.canvas.getContext('2d').drawImage(document.getElementById(id),imgX,imgY,32,32,0,0,32,32);
  this.x = mapX;
	this.y = mapY;
	this.health = 0;
	this.score = 0;
	this.level = 0;
	this.gold = 0;
	this.type = "monster";
	
	this.moveDown = function () { 
		if(!this.checkCollision(this.x,this.y+32) && !this.checkAtk(this.x,this.y+32)){
			this.y += ((this.y + 32)>288)? 0 : 32; 
			if(this.type != 'monster'){this.checkEvent(this.x,this.y)};
		}
	}
	
	this.moveUp = function (){
  		if(!this.checkCollision(this.x,this.y-32) && !this.checkAtk(this.x,this.y-32)){
			this.y -= ((this.y - 32) <0 )? 0 : 32;
			if(this.type != 'monster'){this.checkEvent(this.x,this.y)};
		}
  }

  this.moveLeft = function () {
  		if(!this.checkCollision(this.x-32,this.y) && !this.checkAtk(this.x-32,this.y)){
			this.x -= ((this.x - 32) < 0)? 0 : 32;
			if(this.type != 'monster'){this.checkEvent(this.x,this.y)};
		}  
  }
  this.moveRight = function (){
  		if(!this.checkCollision(this.x+32,this.y) && !this.checkAtk(this.x+32,this.y)){
			this.x += ((this.x +32) > 288)? 0 : 32;
			if(this.type != 'monster'){this.checkEvent(this.x,this.y)};
		}
  }

	this.randomMove = function(){
		var seed = Math.floor(Math.random() *100);
		if(seed <=20) {this.moveUp()}
		else if(seed <=40) {this.moveRight()}
		else if(seed <=60) {this.moveDown()}
		else if(seed <=80) {this.moveLeft()}
		else {/** no move **/}

	}


	
	this.checkCollision= function (toX,toY){
	   var col = tileMap[toY/32][toX/32].collision;	
	   return col;
	}

	this.checkEvent = function (evtX,evtY){	  
      if(eventMap[evtY/32][evtX/32]){
        //alert(eventMap[evtY/32][evtX/32].eventStr) 
        theGame.statusText =  eventMap[evtY/32][evtX/32].eventStr;
        theGame.statusChanged = true; 
        if(eventMap[evtY/32][evtX/32].type=='goto'){
          window.removeEventListener('keydown',doKeyDown,true);
          theGame.load(eventMap[evtY/32][evtX/32].toMap)
        }
       
        for(k=0;k<theGame.itemArr.length; k++){
          if(theGame.itemArr[k].x == evtX && theGame.itemArr[k].y == evtY){
            theGame.theChar.gold += theGame.itemArr[k].gold;
            if(theGame.itemArr[k].type == 'food') {
              theGame.theChar.health += theGame.itemArr[k].health
            }
            theGame.itemArr[k].health = 0; //'kill' item
            
            eventMap[evtY/32][evtX/32] = null; //remove event;
          }
        }     
      }
  }
  
  this.checkAtk = function(toX,toY){
  
  if(this.type == 'player'){
	for(h=0;h < theGame.monstArr.length; h++){
		if(theGame.monstArr[h].x == toX && theGame.monstArr[h].y == toY && theGame.monstArr[h].health>0){
			//character trying to attack!
			var dmgToMonster = Math.floor(Math.random() * 10);
			var dmgToChar = Math.floor(Math.random()*10);
			theGame.theChar.health -= dmgToChar;
			theGame.monstArr[h].health -= dmgToMonster;
			
			if(theGame.theChar.health > 0){
				if(theGame.monstArr[h].health > 0){
          theGame.statusText = "Monster "+h+": "+dmgToMonster+" dmg, You: "+dmgToChar+".";
          theGame.statusChanged = true;
					//gameStatus1 ="Monster "+h+" takes "+ dmgToMonster+" damage. "
					//gameStatus2 = "You take "+dmgToChar;
				}else{
				  theGame.statusText = "Monster "+h+": dies!, You: "+dmgToChar+".";
				  theGame.statusChanged = true;
					//gameStatus1 = "Monster "+h+" takes "+ dmgToMonster+" dmg and dies!";
					//gameStatus2 = "You take "+dmgToChar+".";
				}
				
			}else {
			 theGame.statusText = "You die! Press space to restart."
			 theGame.statusChanged = true;
				//gameStatus1 = "You take "+dmgToChar+". You die!"
				//gameStatus2 = "Press space to restart game.";
			}
			return true; // hit a monster so dont move
		}
		if(theGame.theChar.health<=0){
			theGame.theChar.health = 0;
			theGame.statusChanged = true;
			return true; //your dead, so dont move..
		}
		
	}
	return false; // player didnt hit a monster
  } return false; //its a monster moving
}
  
  
  
  
  
}


function doKeyDown(evt){
    //alert('keydown ' + evt.keyCode)

    if(evt.keyCode == 71){
      //goto g
      //alert("pick")
      theGame.pick();    
    }
    if(evt.keyCode == 76){
      //load l
      theGame.loadgame();
    }
    if(evt.keyCode == 83){
      //save s
      theGame.savegame();
    }
    
    
  if(evt.keyCode == 40) {
    //down
    theGame.theChar.moveDown();
    theGame.draw();
  }
  if(evt.keyCode == 38) {
    //up
    theGame.theChar.moveUp();
    theGame.draw();
  }
	if(evt.keyCode == 37){
		//left
    theGame.theChar.moveLeft();
    theGame.draw();
	}
	if(evt.keyCode == 39){
		//right
    theGame.theChar.moveRight();
    theGame.draw();
	}
	if (evt.keyCode == 32){
			//clearTimeout(knifeTimer)
			//shootKnife(knightObj.x+5, knightObj.y+5);
			window.location.reload();
			
	}	
}

function getChar(chr){
	switch(chr){
		case 'A' : return {x:5  ,y:5}
		case 'B' : return {x:21 ,y:5}
		case 'C' : return {x:37 ,y:5}
		case 'D' : return {x:53 ,y:5}
		case 'E' : return {x:69 ,y:5}
		case 'F' : return {x:85 ,y:5}
		case 'G' : return {x:101,y:5}
		case 'H' : return {x:117,y:5}
		case 'I' : return {x:133,y:5}
		case 'J' : return {x:149,y:5}
		case 'K' : return {x:165,y:5}
		case 'L' : return {x:181,y:5}
		case 'M' : return {x:197,y:5}

		case 'N' : return {x:5  ,y:21}
		case 'O' : return {x:21 ,y:21}
		case 'P' : return {x:37 ,y:21}
		case 'Q' : return {x:53 ,y:21}
		case 'R' : return {x:69 ,y:21}
		case 'S' : return {x:85 ,y:21}
		case 'T' : return {x:101,y:21}
		case 'U' : return {x:117,y:21}
		case 'V' : return {x:133,y:21}
		case 'W' : return {x:149,y:21}
		case 'X' : return {x:165,y:21}
		case 'Y' : return {x:181,y:21}
		case 'Z' : return {x:197,y:21}

		case 'a' : return {x:5, y:37}
		case 'b' : return {x:21 ,y:37}
		case 'c' : return {x:37 ,y:37}
		case 'd' : return {x:53 ,y:37}
		case 'e' : return {x:69 ,y:37}
		case 'f' : return {x:85 ,y:37}
		case 'g' : return {x:101,y:37}
		case 'h' : return {x:117,y:37}
		case 'i' : return {x:133,y:37}
		case 'j' : return {x:149,y:37}
		case 'k' : return {x:165,y:37}
		case 'l' : return {x:181,y:37}
		case 'm' : return {x:197,y:37}

		case 'n' : return {x:5  ,y:53}
		case 'o' : return {x:21 ,y:53}
		case 'p' : return {x:37 ,y:53}
		case 'q' : return {x:53 ,y:53}
		case 'r' : return {x:69 ,y:53}
		case 's' : return {x:85 ,y:53}
		case 't' : return {x:101,y:53}
		case 'u' : return {x:117,y:53}
		case 'v' : return {x:133,y:53}
		case 'w' : return {x:149,y:53}
		case 'x' : return {x:165,y:53}
		case 'y' : return {x:181,y:53}
		case 'z' : return {x:197,y:53}

		case '1' : return {x:5  ,y:69}
		case '2' : return {x:21 ,y:69}
		case '3' : return {x:37 ,y:69}
		case '4' : return {x:53 ,y:69}
		case '5' : return {x:69 ,y:69}
		case '6' : return {x:85 ,y:69}
		case '7' : return {x:101,y:69}
		case '8' : return {x:117,y:69}
		case '9' : return {x:133,y:69}
		case '0' : return {x:149,y:69}
		case '-' : return {x:165,y:69}
		case '+' : return {x:181,y:69}
		case '=' : return {x:197,y:69}

		case '!' : return {x:5  ,y:85}
		case '@' : return {x:21 ,y:85}
		case '#' : return {x:37 ,y:85}
		case '$' : return {x:53 ,y:85}
		case '%' : return {x:69 ,y:85}
		case '^' : return {x:85 ,y:85}
		case '&' : return {x:101,y:85}
		case '*' : return {x:117,y:85}
		case '(' : return {x:133,y:85}
		case ')' : return {x:149,y:85}
		case '[' : return {x:165,y:85}
		case ']' : return {x:181,y:85}
		case '?' : return {x:197,y:85}

		case '<' : return {x:5  ,y:101}
		case '>' : return {x:21 ,y:101}
		case ',' : return {x:37 ,y:101}
		case '.' : return {x:53 ,y:101}
		case '/' : return {x:69 ,y:101}
		case "`" : return {x:85 ,y:101}
		case '~' : return {x:101,y:101}
		case '{' : return {x:117,y:101}
		case '}' : return {x:133,y:101}
		case ';' : return {x:149,y:101}
		case ':' : return {x:165,y:101}
		case '"' : return {x:181,y:101}
		case "'" : return {x:197,y:101}


		case ' ' :
		default :	return {x:180,y:105}
	}

}

function getString(str){
	var strMap = Array.map(str,getChar)

	tmpCanvas = document.createElement('canvas')
	tmpCanvas.height=9
	tmpCanvas.width=9*strMap.length
	tctx = tmpCanvas.getContext('2d')

	fontImg = document.getElementById('gamefont');

	for(i=0;i<strMap.length; i++){
		tctx.drawImage(fontImg,strMap[i].x, strMap[i].y,7,9,i*9,0,7,9)
	}
	return tmpCanvas;
}


//cookie stuff from  http://www.dustindiaz.com/top-ten-javascript/

function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}
	
function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+"="+escape( value ) +
		( ( expires ) ? ";expires="+expires_date.toGMTString() : "" ) + //expires.toGMTString()
		( ( path ) ? ";path=" + path : "" ) +
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}
	
function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + "=" +
			( ( path ) ? ";path=" + path : "") +
			( ( domain ) ? ";domain=" + domain : "" ) +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}


//fire it up!
var theGame = new gameObj;
//theGame.init();
function resCount(){
	theGame.numRes +=1;
	if(theGame.numRes == 11){
		theGame.init();
	}
}


