/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
var wall=true;
var ball;
var yGravity=2;
var xGravity=0.2;
var ballSpeedY=0;
var ballSpeedX=parseInt(Math.random()*40);
var falling=true;
var gravityInterval;
$(document).ready(function(e){
  //initBall();

})

function initBall(){
     $("body").prepend("<div id='ball'><img src='/site_elements/layout/ball.png'></div>");
   ball=$("#ball");
   gravityInterval=setInterval("squareFall()", 30);
   setInterval("squareThrow()", 30);
   ball.css("top",0);
   $('#ball').draggable({
       start: startDragging,
       drag: currentDragging,
       stop: stopDragging,
       cursor: 'move'
    });
    $('#ball').mousedown(function(){ falling=false;})

}

function squareFall(){
  if(!falling){
      return;
  }
  var posBall=ball.position();
  ballSpeedY+=yGravity
  var posY=posBall.top+ballSpeedY
  ball.css("top",posY);
  posBall=ball.position();
  
  if((posBall.top+ball.height())>=returnLimitGround()){
 
    ball.css("top",(returnLimitGround()-ball.height()));
    ballSpeedY=-ballSpeedY
  }
  //$("#status").html(ballSpeedY +" " +ballSpeedX );


}

function squareThrow(){
  if(!falling){
      return;
  }
  if(ball.position().left<=0 ){
    if(wall){
      ball.css("left",20);
      ballSpeedX=-ballSpeedX
    }else{
      ball.css("left",($(window).width()-ball.width()));
    }
  }else if((ball.position().left+ball.width())>=($(window).width()-5)){
     if(wall){
        ball.css("left",($(window).width()-ball.width())-20);
        ballSpeedX=-ballSpeedX
     }else{
      ball.css("left",20);
    }
  }


  if(ballSpeedX<3 && ballSpeedX>-3){
    return;
  }
  if(ballSpeedX<0){
    ballSpeedX+=xGravity
    
  }else{
     ballSpeedX-=xGravity
     
  }
 var posx=ball.position().left+ballSpeedX
  ball.css("left",posx);
}

function returnLimitGround(){
  var groundPos=$("#top").height()+$("#top").position().top;
  return groundPos;
}

var currentXpos;
var newXpos;

function startDragging (event, ui){
     falling=false;
}
function stopDragging (event, ui){
     ballSpeedY=0
     falling=true;
}
function currentDragging(event, ui){
    //$("#status").html("dragging");
    newXpos=ball.position().left;
    ballSpeedX= newXpos-currentXpos;
    if(ballSpeedX>60){
      ballSpeedX=60
    }
    currentXpos=newXpos;
}



