// Global variables
var ctx; // graphics context of the canvas
var msec; // date.getTime() at the last frame
var cursors; // an array of cursor objects
var speed=100; // pixels/sec
var corners=5; // number of corners
var delay=1; // delay between frames (in msec)

// Extra global variable to measure the frame rate
var msecFirst;
var frames = 0;

window.addEventListener("load", function(){
  try {
    /* Hide the status bar */
    setTimeout(function() { window.scrollTo(0, 1); }, 10);

    /* To prevent scrolling, call WidgetPad.noscroll(true); */
    WidgetPad.noscroll(true);

    var date = new Date;
    msec = date.getTime();
    msecFirst = msec;
    var canvas = document.getElementById('canvas');
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    ctx = canvas.getContext('2d');
    cursors = [];
    for (i=0; i<corners*2; i++) {
       var deg = i * (Math.PI+1) / corners;
       cursors[i] = new Cursor(window.innerWidth/2, window.innerHeight/2, speed*Math.sin(deg), speed*Math.cos(deg));
    }
    setTimeout(drawFrame, delay);
  }
  catch (e) {
    WidgetPad.error(e);
  }
}, false);

function Cursor(x,y,dx,dy) {
    this.x = x;
    this.y = y;
    this.dx = dx;
    this.dy = dy;
}

Cursor.prototype.move = function(elasped) {
    with (this) {
      x += dx * elasped;
      y += dy * elasped;
      if (x>window.innerWidth) { x=window.innerWidth*2-x; dx=-dx; }
      if (x<0) { x=-x; dx=-dx; }
      if (y>window.innerHeight) { y=window.innerHeight*2-y; dy=-dy; }
      if (y<0) { y=-y; dy=-dy; }
    }
};
 
function drawFrame() {
  try {
    // Draw
    ctx.clearRect(0,0,window.innerWidth,window.innerHeight);
    ctx.strokeStyle = "rgb(255,0,0)";
    ctx.fillStyle = "rgba(255,0,0,0.5)";
    ctx.lineWidth = 3.0;
    ctx.beginPath();
    ctx.moveTo(cursors[0].x, cursors[0].y);
    for (i=0; i<cursors.length; i+=2) {
      var c1 = cursors[i+1];
      var c2 = cursors[(i+2) % cursors.length];
      ctx.quadraticCurveTo(c1.x,c1.y,c2.x,c2.y);
    }
    ctx.fill();
    ctx.stroke();

    // Calculate the time between this frame and the last frame
    var date = new Date;
    var elasped = (date.getTime() - msec) / 1000;
    msec = date.getTime();

    // Move all the cursors
    for (i in cursors) {
      cursors[i].move(elasped);
    }
    
    // Output the frame rate for each 100 frame
    frames++;
    if (frames % 100 == 0) {
       var span = document.getElementById('fps');
       span.innerHTML = Math.floor(frames/(msec-msecFirst)*1000*100+100)/100 + " fps";
    }
    setTimeout(drawFrame, delay);
  } catch (e) {
    WidgetPad.error(e);
  }
}
