/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


$(document).ready(function(){

  animator = function() {

    var lanterns = $('.lantern');
    var mousex = 0;
    var preCalcPi = Math.PI / 180; // Save some CPU cycles by precalculating this

    // Initialise animation properties and
    // Attach event to each lantern
    lanterns.each(function() {
      $(this).data( 'animprops', {
        animating: false,
        currentRotation: 0,
        direction: 0,
        velocity: 0,
        acceleration: 0
      });
      $(this).mousemove(function( event ) {

        // work out the mouse velocity
        var newMousex = event.pageX;
        var xVelocity = newMousex - mousex;

        mousex = newMousex;

        var props = $(this).data( 'animprops' );

        if (xVelocity < 0 && props.velocity < 2) props.velocity += 0.3;
        if (xVelocity > 0 && props.velocity > -2) props.velocity -= 0.3;
        props.animating = true;
      })
    });

    return {
      go : function() {
        lanterns.each(function() {

          var props = $(this).data('animprops');

          if (props.animating) {

            // Add any wind to the velocity
            if (props.wind != 0) {
              if (props.wind < 0) {
                props.velocity -= 0.1;
                props.wind ++;
              }
              else {
                props.velocity += 0.1;
                props.wind --;
              }
            }

            // First, add the acceleration to the movement
            props.currentRotation += props.velocity;

            // Change the velocity according to the acceleration
            // The deceleration is sin(current angle)
            var acceleration = Math.sin(preCalcPi * props.currentRotation);

            props.velocity -= acceleration;

            // Some air resistance to slow things down semi randomly
            if (props.velocity < 0) props.velocity += 0.002;
            if (props.velocity > 0) props.velocity -= 0.002;

            var newRotation = Math.round(props.currentRotation * 10) / 10;
            $(this).css('-webkit-transform', 'rotate(' + newRotation + 'deg)');
            $(this).css('-moz-transform', 'rotate(' + newRotation + 'deg)');

            // Turn animation off it is has stopped
            if (newRotation == 0 && (Math.round(props.velocity * 10) / 10) == 0) {
              props.animating = 0;
            }
          }
        });
      },

      wind : function() {

        t2 = setTimeout( 'animator.wind()', Math.round(Math.random() * 5000)) ;

        lanterns.each(function() {
          var props = $(this).data('animprops');
          if (Math.abs(props.velocity) < 0.2) {
            props.wind = Math.round(Math.random() *7) - 7;
            props.animating = true;
          }
        });
      }
    };

  }();

  t = setInterval( 'animator.go()', 30) ;
  animator.wind();

});
