/*!
 * jQuery Element Wiggler
 *
 * Copyright 2010, Andrew Hite
 * Date: Thu May 27
 */
$(function(){
  $.fn.wiggler = function(options){
    options = jQuery.extend({
      degrees: 2,
      speed: 250
    }, options);
    
    $(this).each(function(){
      $(this).data('playAnimation', true);
            
      $(this)
        .mouseenter(function(){
          $(this).data('playAnimation', true);
          rotateRight(this);
        })
        .mouseleave(function(){
          $(this).data('playAnimation', false);
          resetRotation(this)
        });
    });
    
    function rotateRight(element){
      $(element).animate({ rotate: options.degrees + 'deg' }, {
        duration: (options.speed / 2),
        queue: false,
        complete: function(){
          if($(this).data('playAnimation')){
            rotateLeft(this);
          }
        }
      });
    }
    
    function rotateLeft(element){
      $(element).animate({ rotate: '-' + options.degrees + 'deg' }, {
        duration: (options.speed / 2),
        queue: false,
        complete: function(){
          if($(this).data('playAnimation')){
            rotateRight(this);
          }
        }
      })
    }
    
    function resetRotation(element){
      $(element).animate({ rotate: '0deg' }, {
        duration: (options.speed / 2),
        queue: false
      });
    }
  }
});
