ig.module(
	'game.entities.engine'
)
.requires(
	'impact.entity',
	'impact.font',
	'game.entities.menu',
	'game.entities.levelBox',
	'game.entities.timeBox',
	'game.entities.scoreBox',
	'game.entities.craked',
	'game.entities.miss',
	'game.entities.quitButton',
	'game.entities.quitMessage',
	'game.entities.item'
)
.defines(function(){

EntityEngine = ig.Entity.extend({
	
	/****************** Menu Entity instance. ************************/
	menu				: null,
	
	/****************** Timer. ***************************************/
	startTime			: new ig.Timer(),
	popupTimer			: new ig.Timer(),
	badItemCreateTimer	: new ig.Timer(),
	
	/****************** Current view of the game. *********************/
	currentView			: null,
	
	/****************** holes . ***************************************/
	holes				: [],
	popupFlags			: [],
	
	/****************** Entity instances. *****************************/
	levelBox			: null,
	timeBox				: null,
	scoreBox			: null,
	totalScoreBox		: null,
	quitButton			: null,
	quitMessage			: null,
	
	/****************** Life and bad life.  ***************************/
	life				: FinalData.MAX_LIFE,
	bad_life			: 0,
	
	/****************** Time Intervals. *******************************/
	popupInterval		: 0,
	stayInterval		: 0,
	popdownInterval		: 0,
	
	/****************** Count variables. *******************************/
	total_item_count	: 0,
	good_item_count		: 0,
	bad_item_count		: 0,
	
	/****************** Boolean variable. ******************************/
	popFlag				: false,
	badItemFlag			: false,
	
	/****************** Font instances. ********************************/
	highScoreFont		: new ig.Font(FinalData.img_highscore_font),
	levelCompleteFont	: new ig.Font(FinalData.img_levelComplete_font),
	
	/****************** Image instances. ************************/
	imgBackground		: new ig.Image(FinalData.img_game_background),
	imgTimeLevelScore	: new ig.Image(FinalData.img_timelevelscore),
	imgLevelComplete	: new ig.Image(FinalData.img_levelComplete),
	imgTapToContinue	: new ig.Image(FinalData.img_tap_to_continue1),
	imgLife				: new ig.Image(FinalData.img_life),
	imgBadLife			: new ig.Image(FinalData.img_bad_life),
	imgEmptyBox			: new ig.Image(FinalData.img_empty_box),
	imgTotalScoreText	: new ig.Image(FinalData.img_totalscore_text),
	imgGameOverText		: new ig.Image(FinalData.img_gameover_text),
	imgPlayAgainText	: new ig.Image(FinalData.img_playagain_text),
	imgEnterHighScoreText: new ig.Image(FinalData.img_enterhighscore_text),
	imgBackButton		: new ig.Image(FinalData.img_back_button),
	
//----------------------------------------------------------------------------------------------------------------------------------
	init: function( x, y, settings ) {
		this.parent( x, y, settings );
		
		this.startMenu();
	},
//----------------------------------------------------------------------------------------------------------------------------------
	update: function() {
		// Update all entities and backgroundMaps
		this.parent();
		
		switch(this.currentView) {
			case FinalData.MAIN_GAME_VIEW:
				this.mouseCheckInMainGame();
				break;
				
			case FinalData.QUIT_VIEW:
				this.mouseCheckInQuitView();
				break;
				
			case FinalData.LEVEL_COMPLETE_VIEW:
				this.mouseCheckInLevelComplete();
				break;
			
			case FinalData.GAME_OVER_VIEW:
				this.mouseCheckInGameOver();
				break;
			
			case FinalData.INPUT_NAME_VIEW:
				this.MouseCheckInInputNameView();
		}
	},
//----------------------------------------------------------------------------------------------------------------------------------
	draw: function() {
		// Draw all entities and backgroundMaps
		this.parent();
		
		switch(this.currentView) {
			case FinalData.QUIT_VIEW:
				this.imgBackground.draw(this.pos.x, this.pos.y);
				this.drawGameInfo();
				this.imgTimeLevelScore.draw(this.pos.x + FinalData.TIMELEVELSCORE_POS.x, this.pos.y + FinalData.TIMELEVELSCORE_POS.y);
				
				break;
			case FinalData.MAIN_GAME_VIEW:
				this.imgBackground.draw(this.pos.x, this.pos.y);
			
				this.drawGameInfo();

				this.imgTimeLevelScore.draw(this.pos.x + FinalData.TIMELEVELSCORE_POS.x, this.pos.y + FinalData.TIMELEVELSCORE_POS.y);
				
				if( this.timeBox.getTime() == 0 ) {
					this.clearGame();
					this.levelComplete();
				}
				this.playPopup();
				break;
			
			case FinalData.LEVEL_COMPLETE_VIEW:
				this.imgBackground.draw(this.pos.x, this.pos.y);
				this.imgTimeLevelScore.draw(this.pos.x + FinalData.TIMELEVELSCORE_POS.x, this.pos.y + FinalData.TIMELEVELSCORE_POS.y);
				
				this.imgLevelComplete.draw(this.pos.x + FinalData.LEVELCOMPLETE_POS.x, this.pos.y + FinalData.LEVELCOMPLETE_POS.y);
				
				if(ig.ua.iPad) {
					
					this.levelCompleteFont.draw(this.levelBox.getLevel(), this.pos.x + FinalData.LEVELCOMPLETE_LEVEL_POS.x, this.pos.y + FinalData.LEVELCOMPLETE_LEVEL_POS.y);
				}
				
				this.imgTapToContinue.draw(this.pos.x + FinalData.TAP_TO_CONTINUE_POS.x, this.pos.y + FinalData.TAP_TO_CONTINUE_POS.y);
				break;
			
			case FinalData.GAME_OVER_VIEW:
				this.imgBackground.draw(this.pos.x, this.pos.y);
				this.imgTimeLevelScore.draw(this.pos.x + FinalData.TIMELEVELSCORE_POS.x, this.pos.y + FinalData.TIMELEVELSCORE_POS.y);
				this.imgEmptyBox.draw(this.pos.x, this.pos.y);
				this.imgTotalScoreText.draw(this.pos.x + FinalData.TOTALSCORE_TEXT_POS.x, this.pos.y + FinalData.TOTALSCORE_TEXT_POS.y);
				//removed_task_menu this.imgGameOverText.draw(this.pos.x + FinalData.GAMEOVER_TEXT_POS.x, this.pos.y + FinalData.GAMEOVER_TEXT_POS.y);
				this.imgPlayAgainText.draw(this.pos.x + FinalData.PLAYAGAINTEXT_POS.x, this.pos.y + FinalData.PLAYAGAINTEXT_POS.y);
				//removed_task_menu this.imgEnterHighScoreText.draw(this.pos.x + FinalData.ENTERHIGHSCORE_POS.x, this.pos.y + FinalData.ENTERHIGHSCORE_POS.y);
				break;
			
			case FinalData.INPUT_NAME_VIEW:
				this.imgBackground.draw(this.pos.x, this.pos.y);
				this.imgEmptyBox.draw(this.pos.x, this.pos.y);
				this.imgEnterHighScoreText.draw(this.pos.x + FinalData.INPUTNAME_TEXT_POS.x, this.pos.y + FinalData.INPUTNAME_TEXT_POS.y);
				this.imgBackButton.draw(this.pos.x + FinalData.BACK_BUTTON_POS.x, this.pos.y + FinalData.BACK_BUTTON_POS.y);
				this.inputName();
				break;
		}
	},
//-------------------------------------------------------------------------------------------------------------------------------------------
	inputName: function() {
		var str = ig.$( '#highscore' ).value.toUpperCase();
		var length = str.length;
		this.highScoreFont.draw( str, this.pos.x + FinalData.INPUTNAME_POS.x - length * 5, this.pos.y + FinalData.INPUTNAME_POS.y + FinalData.INPUTNAME_INTENT);
	},
//-------------------------------------------------------------------------------------------------------------------------------------------
	drawGameInfo: function() {
		var x, y;
		
		if(this.bad_life >= FinalData.MAX_BAD_LIFE) {
			this.openView(FinalData.GAME_OVER_VIEW);
			return;
		}
		
		if(this.life <= 0) {
			this.openView(FinalData.GAME_OVER_VIEW);
			return;
		}
		
		for(i = 0; i < this.life; i++) {
			x = FinalData.LIFE_POS.x - FinalData.LIFE_SIZE.x * i;
			y = FinalData.LIFE_POS.y;
			this.imgLife.draw(x, this.pos.y + y);
		}
		
		for(i = 0; i < this.bad_life; i++) {
			x = FinalData.BAD_LIFE_POS.x + FinalData.BAD_LIFE_SIZE.x * i;
			y = FinalData.BAD_LIFE_POS.y;
			this.imgBadLife.draw(x, this.pos.y + y);
		}
	},
//-------------------------------------------------------------------------------------------------------------------------------------------
	mouseCheckInQuitView: function() {
		if( ig.input.pressed('mouse')) { 
			var x = ig.input.mouse.x;
			var y = ig.input.mouse.y;
			
			//press the yes button in the quit message.
			
			if( x >= FinalData.QUIT_MESSAGE_POS.x + FinalData.YES_INTENT_POS.x && x <= FinalData.QUIT_MESSAGE_POS.x  + FinalData.YES_INTENT_POS.x + FinalData.YES_SIZE.x &&
				y >= FinalData.QUIT_MESSAGE_POS.y + FinalData.YES_INTENT_POS.y && y <= FinalData.QUIT_MESSAGE_POS.y + FinalData.YES_INTENT_POS.y + FinalData.YES_SIZE.y) {
				this.clearGameInfo();
				this.openView(this.menu.openView(FinalData.MAIN_MENU_VIEW));
				
			//press the no button in the quit message.
			} else if(x >= FinalData.QUIT_MESSAGE_POS.x + FinalData.NO_INTENT_POS.x && x <= FinalData.QUIT_MESSAGE_POS.x  + FinalData.NO_INTENT_POS.x + FinalData.NO_SIZE.x &&
				y >= FinalData.QUIT_MESSAGE_POS.y + FinalData.NO_INTENT_POS.y && y <= FinalData.QUIT_MESSAGE_POS.y + FinalData.NO_INTENT_POS.y + FinalData.NO_SIZE.y) {
				this.timeBox.startTimeBox();
				this.openView(FinalData.MAIN_GAME_VIEW);
				this.quitMessage.kill();
				for( i = 0; i < FinalData.HOLE_COUNT; i++ ) {
					if(this.holes[i] != undefined)	this.holes[i].startItem();
				}
				
			}
		}
	},
//-------------------------------------------------------------------------------------------------------------------------------------------
	mouseCheckInMainGame: function() {
		if( ig.input.pressed('mouse')) { 
			var x = ig.input.mouse.x;
			var y = ig.input.mouse.y;
			
			if( x >= FinalData.QUIT_BUTTON_POS.x && x <= FinalData.QUIT_BUTTON_POS.x + FinalData.QUIT_BUTTON_SIZE.x &&
				 y >= FinalData.QUIT_BUTTON_POS.y && y <= FinalData.QUIT_BUTTON_INTENT + FinalData.QUIT_BUTTON_POS.y + FinalData.QUIT_BUTTON_SIZE.y) {
				 this.quitMessage = ig.game.spawnEntity(EntityQuitMessage, FinalData.QUIT_MESSAGE_POS.x, FinalData.QUIT_MESSAGE_POS.y);
				 this.openView(FinalData.QUIT_VIEW);
			}
			
			for( i = 0; i < FinalData.HOLE_COUNT; i++ ) {
				if( x >= this.pos.x + FinalData.HOLE_POSX[i] && x <= this.pos.x + FinalData.HOLE_POSX[i] + FinalData.HOLE_SIZE.x &&
					 y >= this.pos.y + FinalData.HOLE_POSY[i] && y <= this.pos.y + FinalData.HOLE_POSY[i] + FinalData.HOLE_SIZE.y) {
					if(this.popupFlags[i] && !this.holes[i].crakeFlag) {
					 //	 if( !this.holes[i].crakedFlag ) {
							this.holes[i].craked();
							crakedFlag = true;
					//	}
					}
					break;
				}
			}
			
		}
	},
//----------------------------------------------------------------------------------------------------------------------------------
	mouseCheckInLevelComplete: function() {
		if( ig.input.pressed('mouse')) {
			if( this.levelBox.getLevel() <= FinalData.MAX_LEVEL ) {
				
				this.startLevel(this.levelBox.getLevel() + 1);
			} else {
				
				this.clearGameInfo();
				
				this.menu.getHighScoreData();
				
				var score = this.scoreBox.getScore();
				
				if( (this.menu.arrHighScore[FinalData.MAX_HIGHSCORE_COUNT - 1] == undefined) || (this.menu.arrHighScore[FinalData.MAX_HIGHSCORE_COUNT - 1] != undefined && score > this.menu.arrHighScore[FinalData.MAX_HIGHSCORE_COUNT - 1].score) ) {
					
					this.openView(FinalData.INPUT_NAME_VIEW);
				}
				else {

					this.openView(this.menu.openView(FinalData.HIGH_SCORES_VIEW));
				}
			}
		}
	},
//----------------------------------------------------------------------------------------------------------------------------------
	mouseCheckInGameOver: function() {
		if(ig.input.pressed('mouse')) {
			var x = ig.input.mouse.x;
			var y = ig.input.mouse.y;
			
			if(x >= this.pos.x + FinalData.PLAYAGAINTEXT_POS.x && x <= this.pos.x + FinalData.PLAYAGAINTEXT_POS.x + FinalData.PLAYAGAINTEXT_SIZE.x &&
				y >= this.pos.y + FinalData.PLAYAGAINTEXT_POS.y && y <= this.pos.y + FinalData.PLAYAGAINTEXT_POS.y + FinalData.PLAYAGAINTEXT_SIZE.y) {
				this.openView(FinalData.MAIN_GAME_VIEW);
				
				this.clearGameInfo();
				this.startGame();
			}
			
			if(x >= this.pos.x + FinalData.ENTERHIGHSCORE_POS.x && x <= this.pos.x + FinalData.ENTERHIGHSCORE_POS.x + FinalData.ENTERHIGHSCORE_SIZE.x &&
				y >= this.pos.y + FinalData.ENTERHIGHSCORE_POS.y && y <= this.pos.y + FinalData.ENTERHIGHSCORE_POS.y + FinalData.ENTERHIGHSCORE_SIZE.y) {	
				
				this.clearGameInfo();
				
				this.menu.getHighScoreData();
				
				var score = this.scoreBox.getScore();
				
				if( (this.menu.arrHighScore[FinalData.MAX_HIGHSCORE_COUNT - 1] == undefined) || (this.menu.arrHighScore[FinalData.MAX_HIGHSCORE_COUNT - 1] != undefined && score > this.menu.arrHighScore[FinalData.MAX_HIGHSCORE_COUNT - 1].score) ) {
					
					this.openView(FinalData.INPUT_NAME_VIEW);
				}
				else {

					this.openView(this.menu.openView(FinalData.HIGH_SCORES_VIEW));
				}
				
			}
		}
	},
//----------------------------------------------------------------------------------------------------------------------------------
	MouseCheckInInputNameView: function() {
		if(ig.input.pressed('mouse')) {
			var x = ig.input.mouse.x;
			var y = ig.input.mouse.y;
			if( x >= this.pos.x + FinalData.BACK_BUTTON_POS.x && x <= this.pos.x + FinalData.BACK_BUTTON_POS.x + FinalData.BACK_BUTTON_SIZE.x
				&& y >= this.pos.y + FinalData.BACK_BUTTON_POS.y && y <= this.pos.y + FinalData.BACK_BUTTON_POS.y + FinalData.BACK_BUTTON_SIZE.y) {
				var name = ig.$( '#highscore' ).value.toUpperCase();
				if( name == '' ) {
						return;
				}
				var that = this;
				var req = $.ajax({
					url:( "game.php" + '?nocache=' + Math.random() ), 
					data: {a: 's', n:name, s: this.scoreBox.getScore()},
					dataType: 'json',
					async: false,
					success:function(scores) {
						that.arrHighScore = scores;
					}
				});
				document.getElementById('highscore').blur();
				$('#highscore').css('width', 0);
				$('#highscore').css('height', 0);
				$('#highscore').css('z-index', 0);
				$('#canvas').css('z-index', 10);
				var elem = document.getElementById("myBody");
				var elemChild = document.getElementById( "highscore");
				elem.removeChild( elemChild );  
				$('#canvas').focus();
				this.openView(this.menu.openView(FinalData.HIGH_SCORES_VIEW));
			}
		}
	},
//----------------------------------------------------------------------------------------------------------------------------------
	openView: function(view) {
		switch(view) {
			case FinalData.QUIT_VIEW:
				this.timeBox.stop();
				for( i = 0; i < FinalData.HOLE_COUNT; i++ ) {
					if(this.holes[i] != undefined)	this.holes[i].stopItem();
				}
				break;
				
			case FinalData.GAME_OVER_VIEW:
				this.clearTargets();
				this.clearGameInfo();
				
				this.life = 3;
				this.bad_life = 0;
				this.timeBox.stop();
				this.totalScoreBox = ig.game.spawnEntity(EntityScoreBox, this.pos.x + FinalData.TOTALSCORE_POS.x, this.pos.y + FinalData.TOTALSCORE_POS.y);
				this.totalScoreBox.setScore(this.scoreBox.getScore());
				break;
			
			case FinalData.INPUT_NAME_VIEW:
				this.createEditBox();
				break;
		}
		this.currentView = view;
	},
//---------------------------------------------------------------------------------------------------------------------------------
	createEditBox: function() {
		var elem = document.getElementById( "myBody" );
		var newChild =  document.createElement( "input" );
		newChild.type = "text";
		newChild.id = "highscore";
		newChild.setAttribute('maxlength', 8);
		elem.appendChild( newChild );
		newChild.focus();
		
		ig.$('#highscore').value = '';
		$('#highscore').css('position', 'absolute');
		$('#highscore').css('border', '0px solid');
		$('#highscore').css('left', 0);
		$('#highscore').css('top', 0);
		$('#highscore').css('width', FinalData.SCREEN_WIDTH);
		$('#highscore').css('height', FinalData.EDIT_HEIGHT);
		$('#highscore').css('background-color', 'transparent');
		$('#highscore').css('color', 'transparent');
		$('#highscore').css('z-index', 10);
		$('#canvas').css('z-index', 0);
		ig.$("#highscore").focus();	
		
		$('#highscore').bind('blur', function() {
			window.scrollTo(0, 1);
			FinalData.INPUTNAME_INTENT = 0;
		});
		
		$('#highscore').bind('focus', function() {
			FinalData.INPUTNAME_INTENT = FinalData.ENTERNAME_TEMP_VALUE;
		});
		
	},
//----------------------------------------------------------------------------------------------------------------------------------
	startMenu: function() {
		this.menu = ig.game.spawnEntity( EntityMenu, this.pos.x , this.pos.y , {engine: this} );
	},
//----------------------------------------------------------------------------------------------------------------------------------
	startGame: function() {
		this.menu.openView(FinalData.HIDE_SCREEN_VIEW);
		
		this.bad_life = 0;
		this.life = FinalData.MAX_LIFE;
		
		this.levelBox = ig.game.spawnEntity(EntityLevelBox, this.pos.x + FinalData.LEVELBOX_POS.x, this.pos.y + FinalData.LEVELBOX_POS.y);
		this.timeBox = ig.game.spawnEntity(EntityTimeBox, FinalData.TIMEBOX_POS.x, this.pos.y + FinalData.TIMEBOX_POS.y);
		this.scoreBox = ig.game.spawnEntity(EntityScoreBox, FinalData.SCOREBOX_POS.x, this.pos.y + FinalData.SCOREBOX_POS.y);
		
		this.quitButton = ig.game.spawnEntity(EntityQuitButton, FinalData.QUIT_BUTTON_POS.x, FinalData.QUIT_BUTTON_POS.y + FinalData.QUIT_BUTTON_INTENT);
		
		this.startLevel(1);
	},
//----------------------------------------------------------------------------------------------------------------------------------
	startLevel: function(level) {
		if(level > FinalData.MAX_LEVEL) {
			this.menu.openView(FinalData.MAIN_MENU_VIEW);
			return;
		}
		this.levelBox.setLevel(level);
		
		this.openView(FinalData.MAIN_GAME_VIEW);
		
		this.timeBox.start();
		
		this.total_item_count = FinalData.TOTAL_ITEMS_COUNT[level - 1];
		this.good_item_count = FinalData.GOOD_ITEMS_COUNT[level - 1];
		this.bad_item_count = this.total_item_count - this.good_item_count;
			
		this.popupInterval = FinalData.INIT_TIME / FinalData.TOTAL_ITEMS_COUNT[level - 1];
		this.stayInterval = FinalData.INITSTAY_TIME;
		this.popdownInterval = FinalData.INIT_POPDOWN;
		
		this.popupTimer.set(this.popupInterval);
		
		this.badItemCreateTimer.set(FinalData.INIT_TIME / this.bad_item_count);
		
		for(i = 0; i < FinalData.HOLE_COUNT; i++) {
			this.popupFlags[i] = false;
		}
	},
//----------------------------------------------------------------------------------------------------------------------------------
	levelComplete: function() {
		this.openView(FinalData.LEVEL_COMPLETE_VIEW);
		this.timeBox.initTimeBox();
		this.clearTargets();
	},
//----------------------------------------------------------------------------------------------------------------------------------
	clearTargets: function() {
		for( i = 0; i < FinalData.HOLE_COUNT; i++ ) {
			if(this.holes[i] != undefined)	ig.game.removeEntity(this.holes[i]);
		}
	},
//----------------------------------------------------------------------------------------------------------------------------------
	clearGameInfo: function() {
		if(this.levelBox != undefined) ig.game.removeEntity(this.levelBox);
		if(this.scoreBox != undefined) ig.game.removeEntity(this.scoreBox);
		if(this.timeBox != undefined) ig.game.removeEntity(this.timeBox);
		if(this.totalScoreBox != undefined) ig.game.removeEntity(this.totalScoreBox);
		if(this.quitButton != undefined) ig.game.removeEntity(this.quitButton);
		if(this.quitMessage != undefined) ig.game.removeEntity(this.quitMessage);
		
		this.clearGame();
	},
//----------------------------------------------------------------------------------------------------------------------------------
	clearGame: function() {
		for( i = 0; i < ig.game.entities.length; i++) {
			if(ig.game.entities[i] instanceof EntityItem || ig.game.entities[i] instanceof EntityPopupScore || ig.game.entities[i] instanceof EntityStarkill ||
			 ig.game.entities[i] instanceof EntityMiss || ig.game.entities[i] instanceof EntityWave) {
				ig.game.removeEntity(ig.game.entities[i]);
			}
		}
	},
//----------------------------------------------------------------------------------------------------------------------------------
	playPopup: function() {
		if(this.popupTimer.delta() > 0 && this.checHoles()) {
			var r = this.getCreateItemPos();
			
			var name;

			if(this.badItemCreateTimer.delta() > 0) {
				this.badItemFlag = false;
				this.badItemCreateTimer.reset();
			}
			
			if(Math.random() < 0.5 && this.bad_item_count > 0 && !this.badItemFlag) {
				var bad_itemPos = Math.floor(Math.random() * FinalData.LEVEL_BAD_ITEMS[this.levelBox.getLevel() - 1].length);
				name = FinalData.LEVEL_BAD_ITEMS[this.levelBox.getLevel() - 1][bad_itemPos];
				this.bad_item_count--;
				this.badItemFlag = true;
			} else {
				var good_itemPos = Math.floor(Math.random() * FinalData.LEVEL_GOOD_ITEMS[this.levelBox.getLevel() - 1].length);
				name = FinalData.LEVEL_GOOD_ITEMS[this.levelBox.getLevel() - 1][good_itemPos];
			}
			var x = FinalData.HOLE_POSX[r];
			var y = FinalData.HOLE_POSY[r];
			
			this.popupFlags[r] = true;
			this.holes[r] = ig.game.spawnEntity(EntityItem, x, this.pos.y + y, {name: name, engine: this, hole_pos: r});
			
			this.popupTimer.reset();
		}
	},
//---------------------------------------------------------------------------------------------------------------------------------
	freeHole: function(pos) {
		this.popupFlags[pos] = false;
	},
//---------------------------------------------------------------------------------------------------------------------------------
	getCreateItemPos: function() {
		while(true){
			var r = Math.floor(Math.random() * FinalData.HOLE_COUNT);
			if(!this.popupFlags[r]) {
				return r;
			}
		}
	},
//---------------------------------------------------------------------------------------------------------------------------------
	checHoles: function() {
		for(i = 0; i < FinalData.HOLE_COUNT; i++) {
			if(!this.popupFlags[i]) {
				return true;
			}
		}
		return false;
	}
//---------------------------------------------------------------------------------------------------------------------------------
});
});