/*******************************************************************************
                            Shake Shake version 1.0
********************************************************************************
Author:   Kendall Conrad of Angelwatt.com
Created:  2008-12-31
Modified: 2009-01-01
Description:
License: This work is licensed under a Creative Commons Attribution-Share Alike
  3.0 United States License http://creativecommons.org/licenses/by-sa/3.0/us/

Arguments:
- elm:    [req] HTML node
- delta:  [opt, 2] int, pixels to move with each step
- max:    [opt, 5] int, max pixels to move in a direction from start
- shakes: [opt, 3] int, how many movements before stopping
- speed:  [opt, 10] int, milliseconds between animation steps, smaller is faster

Example Usage:
var textField = document.getElementById('masked-input');
ShakeShake({ elm: textField, delta: 3, max: 9 });
*******************************************************************************/
function ShakeShake(args)
{
  var elm  = args['elm'],
    delta  = args['delta']  || 2,
    max    = args['max']    || 5,
    shakes = args['shakes'] || 3,
    speed  = args['speed']  || 10,
    pos = [0,0], count = 0, timer = null,
    origPos  = elm.style.position,
    origTop  = elm.style.top,
    origLeft = elm.style.left;
  Shake();
  function Shake() { elm.style.position = 'relative'; UpLeft(); }
  function UpLeft() {
    if (pos[0] <= (max*-1)) {
      if (count++ >= shakes) { Done(); return; }
      DownRight(); return;
    }
    pos[0] = pos[1] -= delta; SetPos();
    timer = setTimeout(function(){ UpLeft(); }, speed);
  }
  function DownRight() {
    if (pos[0] >= max) {
      if (count++ >= shakes) { Done(); return; }
      UpLeft(); return;
    }
    pos[0] = pos[1] += delta; SetPos();
    timer = setTimeout(function(){ DownRight(); }, speed);
  }
  function SetPos() { elm.style.top=pos[0]+'px'; elm.style.left=pos[1]+'px'; }
  function Done() {
    count = pos[0] = pos[1] = 0; SetPos();
    elm.style.position = origPos  || 'static';
    elm.style.top      = origTop  || 'auto';
    elm.style.left     = origLeft || 'auto';
  }
}
