// global variables
// gecko detection
var geck;
var webKitTrans;
// graphics
var batpos; //bat x pos, y pos = 300
var ball_X  = 158;
var ball_Y  = 250;
var ball_dX = -(4+Math.random()*4);
var ball_dY = -(4+Math.random()*4);
var ball_R  = 8; //radius
var hBall_R  = ball_R/2; //radius
//enemy box counter
var boxID = 0;
var hits;
var multi = 1; //rank up the points for multiple strikes
var colbox;

var Rx;
var Ry;

var ratiox;
var ratioy;

var timer;
var score = 0;
var TOPscore;


//////// HELPERS ////////////////////
function setCookie(s_term,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=s_term+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(s_term)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(s_term + "=");
  if (c_start!=-1)
    {
    c_start=c_start + s_term.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
return "";
}

function getTransformProperty(element) {
    var properties = ['transform', 'WebkitTransform', 'MozTransform'];
    var p;
    while (p = properties.shift()) {
        if (typeof element.style[p] != 'undefined') {
            return p;
        }
    }
    return false;
}

/////////////////////// MAIN LOOP ////////////////////

function animate()
{
	//check end of game
	if (hits == boxID)
	{
		if (score > getCookie('TOPScore')){
			setCookie('TOPScore',score,100);
			clearInterval(timer);
			document.getElementById("board").innerHTML = '<div id="info" style="position:absolute;left:0px;top:0px;width:320px;text-align:center" onclick="initBOARD()" /><span style="color:green">New Top Score!!<br>'+score+'</span><br><br><br> Click to Play </div>';			
		} else {
			clearInterval(timer);
			document.getElementById("board").innerHTML = '<div id="info" style="position:absolute;left:0px;top:0px;width:320px;text-align:center" onclick="initBOARD()" />Well Done!<br><span style="color:green">Score: '+score+'</span><br>Top-Score:'+getCookie('TOPScore')+'<br><br> Click to Play </div>';
		}
		return false;
	}
	
	ball_X = ball_X + ball_dX;
	ball_Y = ball_Y + ball_dY;

	if ( (ball_X + ball_R) > 320 ) {
		ball_X = 320 - ball_R;
		ball_dX = -ball_dX;
	}
	
	if ( ball_X < 0 ) {
		ball_X = 0;
		ball_dX = -ball_dX;
	}

	if ( (ball_Y + ball_R) > 356 ) {  //hit the bottom
		ball_Y = 356 - ball_R;
		ball_dY = -0.5*ball_dY;
		ball_dX =  0.5*ball_dX;
		
		//update score
		//score = score -100;
		multi=1;
		document.getElementById("info").innerHTML = score+'<br><span style="color:red">-100</span>';
	}
	
	if ( ball_Y < 0 ) {
		ball_Y = 0;
		ball_dY = -ball_dY;
	}
	
	document.getElementById("ball").style.left = ball_X + 'px';
	document.getElementById("ball").style.top  = ball_Y + 'px';
	//document.getElementById("ball").innerHTML= ball_Y+50;
	
	//alert(document.getElementById('5').style.left);
	//var tmp = "BallX.. "+ball_X+"<br>BallY.. "+ball_Y+"<br>BallDX. "+ball_dX+"<br>BallDY. "+ball_dY+"<br>Rx..... "+Rx+"<br>Ry..... "+Ry;
	

	//bat collision (only if ball going down ;)
	if (ball_dY >= -5 ){
		workDIV=document.getElementById('bat');
		Rx = (ball_X + hBall_R) - (	workDIV.coordX + workDIV.hWidth );
		Ry = (ball_Y + hBall_R) - (	workDIV.coordY + workDIV.hWidth );
		if ( Math.abs(Rx) < 25 && Math.abs(Ry) < 25)
		{ //collision detected
			Rx = (workDIV.coordX + workDIV.hWidth)-(workDIV.oldX + workDIV.hWidth);
			Ry = (workDIV.coordY + workDIV.hWidth)-(workDIV.oldY + workDIV.hWidth);
			
			//ball_dX = ball_dX + 0.2*Rx;
			//ball_dY = ball_dY + 0.2*Ry;
			ball_dX = Rx;
			if (Ry<0) {ball_dY = Ry} else { ball_dY = 0}
			
			if( ball_dX!=0 && ball_dY!=0 ){
				//score = score -50;
				multi=Math.floor(multi/2)+1;
				if (multi<1){multi=1}
				document.getElementById("info").innerHTML = score+'<br><span style="color:red">X'+multi+'</span>';			
			}
			document.getElementById('ball').style[webKitTrans] = 'scale(1.5)';
			//$('ball').fade();

		}
	}
	document.getElementById('bat').oldX = document.getElementById('bat').coordX;
	document.getElementById('bat').oldY = document.getElementById('bat').coordY;
	//bat/ball stuff end
	
	
	//collision detection
	for(var j=0; j < boxID; j++)
	{
		//colbox = document.getElementById(j);
		//if (colbox.style.visibility!='hidden'){
//			if ( ((ball_Y+(0.5*ball_R))>document.getElementById(j).style.top)&&((ball_Y+(0.5*ball_R))>(document.getElementById(j).style.top+document.getElementById(j).style.height))&&((ball_X+(0.5*ball_R))>document.getElementById(j).style.left)&&((ball_X+(0.5*ball_R))<(document.getElementById(j).style.left+document.getElementById(j).style.width)) )
		
		var workDIV=document.getElementById(j)	
		if (workDIV.HPoints > 0)
		{
			Rx = (ball_X + hBall_R) - (	workDIV.coordX + workDIV.hWidth );
			Ry = (ball_Y + hBall_R) - (	workDIV.coordY + workDIV.hWidth );
		
			if ( Math.abs(Rx) < 20 && Math.abs(Ry) < 20)
			{ //collision detected
			
				//workDIV.style.visibility='hidden';
				workDIV.HPoints -=1; 
				workDIV.style[webKitTrans] = 'scale(2.2)';
				workDIV.style.opacity='0.5';
				//$(j).fade({ duration: 3.0, from: 0, to: 1 });


				
				//ball_dX = -ball_dX;
				//ball_dY = -ball_dY;
				
				if ( Math.abs(Rx) < Math.abs(Ry) )
				{
					ball_dY = -ball_dY;
				} else {
					ball_dX = -ball_dX;
				}
				//current best collision simulation 
				//ball_dX = ball_dX + (Rx*0.3);
				//ball_dY = ball_dY + (Ry*0.3);
				score = score +(multi * 150);
				multi++;
				document.getElementById("info").innerHTML = score+'<br><span style="color:green">X'+multi+'</span>';
				hits = hits + 1;
			}
		} else {
			workDIV.style.visibility='hidden';
		}
	}
	if (document.getElementById('ball').style[webKitTrans] == 'scale(1.5)')
	{
		document.getElementById('ball').style[webKitTrans] = 'scale(1)';
	}
} //end anim

function initBOARD()
{

	ball_X  = 158;
	ball_Y  = 250;
	ball_dX = -(4+Math.random()*4);
	ball_dY = -(4+Math.random()*4);
	
	/////// draw the boxes  ///////////
	boxID = 0;
	for (var i=0; i < 8; i++){
		for (var j=0; j < 4; j++){
			var newdiv = document.createElement('img');
			newdiv.setAttribute('id', boxID);
			
			newdiv.style.width = '40px';
			newdiv.style.height = '40px';
//			newdiv.coordX = (40 * i)+Math.floor(Math.random()*6-3);
//			newdiv.coordY = ((40 * j) + 20)+Math.floor(Math.random()*6-3);
			newdiv.coordX = (40 * i);
			newdiv.coordY = ((40 * j) + 20);

			newdiv.hWidth = 20;
			newdiv.HPoints = 1;
			
			newdiv.style.position = "absolute";
			newdiv.style.left = newdiv.coordX + 'px';
			newdiv.style.top = newdiv.coordY + 'px';
   
			newdiv.src = "disc"+Math.floor(Math.random()*2+1)+".gif";
   
			//newdiv.innerHTML = "<img src='maskC.gif' width=40 height=40>";
   
			document.getElementById("board").appendChild(newdiv);			
			
			boxID++;
		}		
	}

//<div id="bat" style="position:absolute;width:50px;height:50px;top:300px;left:150px;background:#fff;"><img src='maskC.gif' width=50 height=50></div>
	///// draw bat ///////
		var newdiv = document.createElement('img');
		newdiv.setAttribute('id', 'bat');
		
		newdiv.style.width  = '50px';
		newdiv.style.height = '50px';
  
		newdiv.style.position = "absolute";
		newdiv.style.left = '150px';
		newdiv.style.top  = '300px';
		
		newdiv.coordX = 150;
		newdiv.coordY = 300;
		newdiv.hWidth = 25;		
  
		newdiv.src = "bat.gif";
		//newdiv.style.background = "#fff";
		//newdiv.innerHTML = "<img src='maskC.gif' width=50 height=50>";
   
		document.getElementById("board").appendChild(newdiv);		
	///// end draw ////////		
	///// draw ball ///////
		newdiv = document.createElement('img');
		newdiv.setAttribute('id', 'ball');
		
		newdiv.style.width  = ball_R + 'px';
		newdiv.style.height = ball_R + 'px';
  
		newdiv.style.position = "absolute";
		newdiv.style.left = ball_X + 'px';
		newdiv.style.top =  ball_Y + 'px';
		
		newdiv.src="ball.gif";
		//newdiv.style.background = "#f00";
		//newdiv.innerHTML = "<img src='maskC.gif' width=8 height=8>";
   
		document.getElementById("board").appendChild(newdiv);	
	///// end draw ////////
	
	document.getElementById("info").innerHTML = '0';
	score = 0;
	hits = 0;
	
	///// start animation //
		timer = setInterval('animate()', 50);
	///////////////////////
}

function init()
{
	TOPscore = getCookie('TOPScore');
	if (TOPscore==null || TOPscore=="")
	{
		setCookie('TOPScore',0,100)
	}
	//intro Screen
	document.getElementById("board").innerHTML = '<div id="info" style="position:absolute;left:0px;top:0px;width:320px;text-align:center" onclick="initBOARD()" />Top Score:'+getCookie('TOPScore')+'<br><br><br><br> Click to Play </div>'
	//get browser transformtype
	webKitTrans = getTransformProperty(document.getElementById("board"));
	//USE:
	//		div.style[webKitTrans] = 'rotate(' + (d++ % 360) + 'deg)';


	
    // check geck browser
    geck = (document.all) ? 0 : 1;

    if (geck) 
    {
        document.captureEvents(Event.MOUSEDOWN | Event.MOUSEMOVE | Event.MOUSEUP);
    }

    document.onmousemove = MouseMove;

}

function MouseMove(e) 
{
//iPhione screen size: 320w x 480h
	//this is used to move the bat
        if (geck) {
            //objDiv.style.top = (e.pageY-Y) + 'px';			
            document.getElementById("bat").style.left = e.pageX-25 + 'px';
			document.getElementById("bat").coordX = e.pageX-5;
			
			batpos = (e.pageY-20);
			if (batpos < 175) { batpos = 175 }
			if (batpos > 360) { batpos = 360 }			
            document.getElementById("bat").style.top = batpos + 'px';
			
			document.getElementById("bat").coordY = batpos;
			
			return false;
		}
}

function init2()
{
    document.body.ontouchmove = function(e) {
        // prevent window scrolling!
        e.preventDefault();
	}


	document.getElementById("board").ontouchmove = function(e){
		if(e.touches.length == 1){ // Only deal with one finger
			var touch = e.touches[0]; // Get the information for finger #1
			//var node = touch.target; // Find the node the drag started from
	
            document.getElementById("bat").style.left = touch.pageX-25 + 'px';
			document.getElementById("bat").coordX = touch.pageX-25;
			
			batpos = (touch.pageY-30);
			if (batpos < 175) { batpos = 175 }
			if (batpos > 360) { batpos = 360 }			
            document.getElementById("bat").style.top = batpos + 'px';
			
			document.getElementById("bat").coordY = batpos;	

    //node.style.position = "absolute";
    //node.style.left = touch.pageX + "px";
    //node.style.top = touch.pageY + "px";
		}
	}
}