ig.module(
	'game_ipad.main' 
)
.requires(
	'impact.game_ipad',
	'impact.font',
	'impact.image',
	'impact.timer' ,
	'game_ipad.entities.player',
	'game_ipad.entities.cannon',
	'game_ipad.entities.cannon_ground',
	'game_ipad.entities.plane_1',
	'game_ipad.entities.plane_2',
	'game_ipad.entities.plane_3',
	'game_ipad.entities.plane_4',
	'game_ipad.entities.bossplane',
	'game_ipad.entities.tank_1',
	'game_ipad.entities.tank_2',
	'game_ipad.entities.tank_3',
	'game_ipad.entities.building_3',
	'game_ipad.entities.building_2',
	'game_ipad.entities.building_1',
	'game_ipad.entities.building_big',
	'game_ipad.entities.building_4',
	'game_ipad.entities.cannon_water',
	'game_ipad.entities.bullet',
	'game_ipad.entities.tower',
	'game_ipad.entities.bullet1',
	'game_ipad.entities.bullet2',
	'game_ipad.entities.oil_barrels',
	'game_ipad.entities.energy',
	'game_ipad.levels.round10',
	'game_ipad.levels.round9',
	'game_ipad.levels.round8',
	'game_ipad.levels.round7',
	'game_ipad.levels.round6',
	'game_ipad.levels.round5',
	'game_ipad.levels.round4',
	'game_ipad.levels.round3',
	'game_ipad.levels.round2',
	'game_ipad.levels.round1'
)
.defines(function(){
FullsizeLogoScreen = ig.Image.extend({
    draw: function() {
        if( !this.loaded ) { return; }
        ig.system.context.drawImage( this.data, 0, 0 );
    }
});    

MyGame = ig.Game.extend({
	// Load a font & images
	font: new ig.Font( 'media_ipad/menu_score_font.png' ),
	imgStar: new ig.Image( 'media_ipad/star.png' ),
	logo: new FullsizeLogoScreen( 'media_ipad/logo.jpg' ),
    title: new FullsizeLogoScreen( 'media_ipad/cover.png' ),
	menuScreen: new ig.Image( 'media_ipad/aircombat-menu.jpg' ),
	scoreScreen: new ig.Image( 'media_ipad/back2.jpg' ),	
	successScreen: new FullsizeLogoScreen( 'media_ipad/levelcomplete.png' ),
	dashBoard: new ig.Image( 'media_ipad/status.png' ),
	scorePanel: new ig.Image( 'media_ipad/levelscore.png' ),
	levelPanel: new ig.Image( 'media_ipad/levelscore.png' ),
	text: new ig.Image( 'media_ipad/landingtext.png' ),	
	bossflag: 0,

	health: 300,
	fuellevel: 6,
	old_health: 300,	
	gamestate: '',
    isPlaying: false,
    goMenu: false,
	fps: 60,
	timer: new ig.Timer(1),
	name:'',
	arrHighScore: [],
	level:1,
	score: 0,
	old_score: 0,
	old_numstars: 0,
	numhostages: 0,
	old_numhostages: 0,
	numstars:0,
	player_life: 3,	
	touchX:0,
	touchY:0,
	numpowers: 1,
	islanding: 0,
	drawy: 0,
	topY:20,
	stepbrowser: 6,
    speedrate: 4,
	screenrate: 2.1875,
	flag: 0,
	panelpos:0,
	init: function() {
		// Bind keys
		ig.input.bind(ig.KEY.MOUSE1, 'go');   
//		ig.input.bind(ig.KEY.DBLTAP, 'land');   
		ig.input.initMouse();
		if( ig.ua.android ) {
			this.drawy = 20;	
			this.speedrate = 6;	
		}
		else if( ig.ua.iPhone ) {
			this.drawy = 11;		
		} else {
			this.drawy = 0;
		}
		
	},
//-----------------------------------------------------------------------------------------------------------------------
	update: function() 
	{
		var ys = new Array();
			ys[1]=512;	ys[3]=660;	ys[5]=730;
			ys[2]=550;	ys[4]=698;	ys[6]=768;
			ys[7]=416;	ys[8]=432;	ys[9]=15;
			ys[10]=60;  ys[11]=590; ys[12]=628;
			ys[13]=795;	ys[14]=833; 
			this.panelpos = 15;

		// Update all entities and backgroundMaps
		if (this.isPlaying == false){
			if( ig.input.pressed('go')) 
			{ 
				var x = ig.input.mouse.x; 
				var y = ig.input.mouse.y; 
				if(this.goMenu==false&&this.timer.delta()>=0){
		            this.goMenu=true; 
					this.gamestate='menu';
			    }
				else if(this.gamestate=='menu'){
					if(( y>ys[1] && y<ys[2] )&&( x>130 && x<335)){						
						this.player_life = 3;
						this.gamestate='ready';
						this.level = 1;
						this.score = 0;
						this.numstars = 0;
						this.numhostages = 0;
					}
					if((y>ys[3] && y<ys[4] )&&( x>285 && x<490)){
						this.gamestate='help';
					}
					if(( y>ys[5] && y<ys[6] )&&( x>352 && x<557)){
						this.gamestate='about';					         
					}
					if(( y>ys[11] && y<ys[12] )&&( x>216 && x<421)){
					   //	this.gamestate='highscore';
						this.getscore();
					}
					if(( y>ys[13] && y<ys[14] )&&( x>420 && x<625)){
						//more game부분
					}
                } // by kss on loading level
				else if (this.gamestate=='ready'){
						this.touchX = 0; 	this.touchY = 0;
						switch(this.level){
							case 1: this.loadLevel( LevelRound1 ); this.bossflag = 0;  break;//
							case 2: this.loadLevel( LevelRound2 ); this.bossflag = 0;  break;//
							case 3: this.loadLevel( LevelRound3 ); this.bossflag = 0;  break;//
							case 4: this.loadLevel( LevelRound4 ); this.bossflag = 0;  break;//
							case 5: this.loadLevel( LevelRound5 ); this.bossflag = 0;  break;//
							case 6: this.loadLevel( LevelRound6 ); this.bossflag = 0;  break;//
							case 7: this.loadLevel( LevelRound7 ); this.bossflag = 0;  break;//
							case 8: this.loadLevel( LevelRound8 ); this.bossflag = 0;  break;//
							case 9: this.loadLevel( LevelRound9 ); this.bossflag = 0;  break;//
							case 10: this.loadLevel( LevelRound10 ); this.bossflag = 0;  break;//
						}						
						
						this.isPlaying = true;
						this.gamestate='round';
						this.score = this.old_score;
										
                }
				else if (this.gamestate == 'gameover'){
					this.gamestate = 'inputname';
					this.goMenu = true;
					this.old_score = 0;
				}
				else if (this.gamestate == 'success'){
					this.gamestate = 'inputname';
				}
				else if (this.gamestate=='highscore'){
					if(x > 18 && x < 115 && y > 758 && y < 797){//press back to menu
						this.gamestate = 'menu';
						this.goMenu = true;
						this.level = 1;
					}
				}
				else if (this.gamestate=='help'){
					if(x > 18 && x < 115 && y > 758 && y < 797){//press back to menu
						this.gamestate = 'menu';
						this.goMenu = true;
						this.level = 1;
					}
				}
				else if (this.gamestate=='about'){
					if(x > 18 && x < 115 && y > 758 && y < 797){//press back to menu
						this.gamestate = 'menu';
						this.goMenu = true;
						this.level = 1;
					}
				}
				
            }
            
        }
		else{
			
			var player = this.getEntitiesByType( EntityPlayer )[0];
			
			if ( player ) 
			{  
				if(this.screen.y > 0)
				{
					this.screen.y -= this.stepbrowser/2 * this.speedrate;
					player.pos.y -= this.stepbrowser/2 * this.speedrate;
				}
				//player.pos.y -= this.stepbrowser/2 * this.speedrate;
				if (this.screen.y < 0 )
				{
					if (this.level ==1)
					{
						player.pos.y -= this.stepbrowser/2 * this.speedrate;
					}
					else if (this.level == 10)
					{
						if (this.bossflag >=2)
						{
							player.pos.y -= this.stepbrowser/2 * this.speedrate;
						}
						else
							player.pos.y -= 0;
					}
					else
					{
						if (this.bossflag == 0)
						{
							player.pos.y -= 0;
						}
						else
						{
							player.pos.y -= this.stepbrowser/2 * this.speedrate;
						}
					}
				}
				if (player.fuel >= 0)
				{
					player.fuel -= 0.8;
				}

				this.fuellevel = Math.round(player.fuel/100);
				
				this.health = player.health;
				if (this.screen.y <= 0 && player.pos.y < 10 )
				{//// if round ended, continue next
					if(this.level < 10 && this.level > 1 && this.bossflag == 1){
						this.gamestate = 'ready';
						this.screen.y = 0;
						this.level += 1 ;
						this.isPlaying = false;
						//save previous level's score,stars,hostages
						this.old_score = this.score;
						this.old_numstars = this.numstars;
						this.old_numhostages = this.numhostages;
						this.old_health = this.health;
					}
					if (this.level == 1)
					{
						this.gamestate = 'ready';
						this.screen.y = 0;
						this.level += 1 ;
						this.isPlaying = false;
						//save previous level's score,stars,hostages
						this.old_score = this.score;
						this.old_numstars = this.numstars;
						this.old_numhostages = this.numhostages;
						this.old_health = this.health;
					}
					if (this.level == 10)
					{
					
						if (this.bossflag >= 2)
						{
							this.old_score = 0;
							this.gamestate = 'success';
							this.isPlaying = false;
							this.numpowers = 1;
						}
					}
					
				}

				if(player.pos.y - this.screen.y +131 > ig.system.height)
					player.pos.y = this.screen.y + ig.system.height - 131;
			}else //if player is killed
			{	
		
				this.player_life -= 1;
				this.touchX = 0;
				this.touchY = 0;
				if(this.player_life > 0)
				{			
					this.gamestate = 'ready';
					this.isPlaying = false;
					// restore previous level's score,stars,hostages
					this.score = this.old_score;
					this.numstars = this.old_numstars ;
					this.numhostages = this.old_numhostages ;
					
				}
				else
				{// if game over
					this.gamestate='gameover';
					this.isPlaying = false;
				}
			
			}
			
		}
		this.parent();
	},
//------------------------------------------------------------------------------------------------------------------------
	savescore: function(){
				
		$('#highscore').blur();
		$('#canvas').focus();
		$('#highscore').css('z-index', 0);
		$('#canvas').css('z-index', 10);
		
		if( this.name == '' ) {
			this.getscore();
			return;
		}
		var that = this;
		var req = $.ajax({
			url:( "game.php" + '?nocache=' + Math.random() ), 
			data: {a: 's', n: that.name, s: that.score},
			dataType: 'json',
			async:false,
			success:function(scores) {
				that.arrHighScore = scores;
				document.getElementById('highscore').blur();
				that.gamestate = 'highscore';
				window.scrollTo(0,1);
				this.name = '';
			}
		});
		
	},
	getscore: function(){
		var that = this;
		var req = $.ajax({
			url:( "game.php" + '?nocache=' + Math.random() ), 
			data: {a: 'l'},
			dataType: 'json',
			async:false,
			success:function(scores) {
				that.arrHighScore = scores;
				that.gamestate = 'highscore';
			}
		});	
	},
//------------------------------------------------------------------------------------------------------------------------
	preDraw: function() {
	},
	drawScore: function(){

			this.scorePanel.draw(2,this.panelpos);
			this.levelPanel.draw(425,this.panelpos);
			this.font.draw( 'SCORE ' + this.score, 12, this.panelpos+4 );
			this.font.draw( 'LEVEL '+this.level,440,this.panelpos+4);
			this.font.draw( ' X ' + this.player_life, 590, this.panelpos+4 );

	},
//------------------------------------------------------------------------------------------------------------------------
	draw: function() {
		
		this.preDraw();
		this.parent();
        if (this.isPlaying == false && this.gamestate!='ready'&& this.gamestate!='success'
					&& this.gamestate!='gameover'&& this.gamestate!='highscore'&& this.gamestate!='inputname'
					&& this.gamestate!='ready')
        {
        	if(this.timer.delta()>=0 && this.goMenu==false)
	            this.title.draw();
        
			else if(this.goMenu==true && this.timer.delta()>=0)
                this.menuScreen.draw(0,this.drawy,0,0,700,881);
            else if(this.isPlaying==false)
				this.logo.draw();
		}
		else if (this.isPlaying == true){
 			this.drawScore();
			this.drawDash();
			this.drawtext();
			this.checkButtonPressed();
		}
		/////by kss about ready screen
			
		switch(this.gamestate){
			case 'ready': 
				if(this.level==1){
					var readyScreen = new ig.Image( 'media_ipad/ready.jpg' );	
					readyScreen.draw(0,this.drawy,0,0,700,881);
				}
				else{
					var readyScreen = new FullsizeLogoScreen( 'media_ipad/levelcomplete.png' );	
					readyScreen.draw();
					}				
				break;
			case 'success':
				this.successScreen.draw();
				break;
			case 'inputname':
				this.inputname();
				break;
			case 'highscore':
				this.scoreScreen.draw(0,this.drawy,0,0,700,881);
				this.font.draw('H I G H  S C O R E S',160, this.topY + 60);
				this.showHighScore();
				break;
			case 'about':				
				this.scoreScreen.draw(0,this.drawy,0,0,700,881);
				this.font.draw('A   B   O   U   T',200, this.topY + 70);
                this.font.draw('AIR COMBAT, ',240, this.topY + 180);
				this.font.draw('DEVELOPED BY TWEENSOFT INC.',120, this.topY + 250);
				this.font.draw('WWW.TWEENSOFT.COM',190, this.topY + 320);
				//this.font.draw('TWEENSOFT INC.',70, this.topY + 220);
				//this.font.draw('WWW.TWEENSOFT.COM',70, this.topY + 250);
				break;
			case 'help':
				this.scoreScreen.draw(0,this.drawy,0,0,700,881);
				this.font.draw('H  E  L  P',260, this.topY + 60);
				this.font.draw('ARE  YOU  READY  PILOT ?',125, this.topY + 140);
				this.font.draw('SHOOT AS MANY ENEMIES AS POSSIBLE.',77, this.topY + 210);
				//this.font.draw('ENEMIES AS POSSIBLE.',5, this.topY + 160);
				this.font.draw('COLLECT EXTRA ENERGY, FIRE POWER,',87, this.topY + 280);
				//this.font.draw('FIRE POWER,HOSTAGES',5, this.topY + 240);
				this.font.draw('HOSTAGES AND STARS.',180, this.topY + 350);
				this.font.draw('TO INCREASE YOUR SCORE.',167, this.topY + 420);
				break;
			case 'gameover':
				var readyScreen = new FullsizeLogoScreen( 'media_ipad/gameover.png' );	
				readyScreen.draw();
				break;
		}
	},
	drawDash: function(){		
		var dashpos_y = 750;
		if(ig.ua.iPhone)
			dashpos_y = 419;
		this.dashBoard.draw(0,dashpos_y);
		this.font.draw( this.numstars , 565, dashpos_y+30);		
		this.font.draw( this.numhostages , 477, dashpos_y+30);
		
		var energylevel = this.health / 50 ;
		if(energylevel > 6) energylevel = 6;
		var imgEnergyStatus = new ig.Image('media_ipad/energy.png');
		imgEnergyStatus.draw(188,dashpos_y+40,Math.round(6-energylevel)*26,0,26,24);
		
		var imgFuel = new ig.Image('media_ipad/fuel.png');
		imgFuel.draw(320,dashpos_y+40,Math.round(6-this.fuellevel)*14,0,14,26);
		
		var imgAltitude = new ig.Image('media_ipad/altitude.png');
		if (this.islanding == 0)
		{
			imgAltitude.draw(250,dashpos_y+40,0,0,18,22);
		}
		else
			imgAltitude.draw(250,dashpos_y+40,36,0,18,22);
		
		
	},
	
	drawtext: function()
	{
		var player = this.getEntitiesByType( EntityPlayer )[0];
	
		var arrY2 = new Array();
		arrY2[2] = 1848*player.screenratey;		arrY2[7] = 1342*player.screenratey;
		arrY2[3] = 946*player.screenratey;		arrY2[8] = 1254*player.screenratey;
		arrY2[4] = 396*player.screenratey;		arrY2[9] = 1254*player.screenratey;
		arrY2[5] = 550*player.screenratey;		arrY2[10] = 704*player.screenratey;
		arrY2[6] = 1584*player.screenratey; 

		if (this.level == 1)
		{
			if (this.screen.y < (1738 - 100)*player.screenratey && this.screen.y > (1738 - 500)*player.screenratey && this.islanding == 0)
			{
				this.text.draw(70*player.screenratex,200*player.screenratey,0,0,438,75);
			}
			if (this.screen.y < (836 - 100)*player.screenratey && this.screen.y > (836 - 500)*player.screenratey && this.islanding == 0)
			{
				this.text.draw(70*player.screenratex,200*player.screenratey,0,0,438,75);
			}
		}
		else
		{
			if (this.screen.y < arrY2[this.level] - 100*player.screenratey && this.screen.y > arrY2[this.level] - 600*player.screenratey && this.islanding == 0)
			{
				this.text.draw(70*player.screenratex,200*player.screenratey,0,0,438,75);
			}

		}
	
	},

	inputname: function()
	{
		$('#canvas').blur();
		$('#highscore').focus();
		$('#highscore').css('z-index', 10);
		$('#canvas').css('z-index', 0);
		var namescreen = new FullsizeLogoScreen('media_ipad/back.png');
		namescreen.draw();
		this.font.draw('INPUT YOUR NAME AND',165, this.topY + 80);
		this.font.draw('TAP TO CONTINUE',205, this.topY + 110);

		this.name = ig.$( '#highscore' ).value.toUpperCase();
		var length = this.name.length;
		this.font.draw( this.name, 370 - length * 14, 400 );
	},
	
	showHighScore: function() {		
		for( i = 0; i < 10; i++ ) {
			this.font.draw( i + 1 + '.', 120, 50 * i + 200 );
			
			if( this.arrHighScore[i] != undefined ) { 
				this.font.draw( this.arrHighScore[i].name, 160, 50 * i + 200 ); 
				this.font.draw( this.arrHighScore[i].score, 470, 50 * i + 200 ); 				
			} else {
				this.font.draw( '... ... ...', 280, 50 * i + 200 );
			}
		}
		
		
	},
//------------------------------------------------------------------------------------------------------------------------

	
	checkButtonPressed: function()
	{
		var player = this.getEntitiesByType( EntityPlayer )[0];
		
		if( ig.input.pressed('go')) 
		{

			var x = ig.input.mouse.x+this.screen.x;
			var y = ig.input.mouse.y+this.screen.y;
			var dx = x - player.pos.x;
			var dy = y - player.pos.y;
			var unitspeed = this.stepbrowser * this.speedrate;
			if (ig.input.mouse.y < 800 && ig.input.mouse.y > 20)
			{
				player.destX = dx - 32;
				player.destY = dy - 64;
				dx = player.destX;
				dy = player.destY;
				
				//this.touchX = unitspeed * this.speedrate;
				//this.touchY = unitspeed * Math.abs(player.destY/player.destX) * this.speedrate;
				
				
				this.touchX = Math.abs(dx * unitspeed /Math.sqrt(dy * dy + dx * dx));
				this.touchY = Math.abs(dy * unitspeed /Math.sqrt(dy * dy + dx * dx));
			

    			if (player.cp == 1)
    			{

    				this.stepbrowser = 6;
    				this.islanding = 0;
    				player.currentAnim = player.anims.shoot;
    				player.isShooting = 1;
    			}
			}
		}
	}
	
});
fpsIPhone = 60;
//fpsPC = 10;

//	window.scrollTo(0,1);
	ig.main('#canvas', MyGame, fpsIPhone, 700, 881, 1);


});