// init vars
var windowWidth        = 0;
var glassWidth         = 0;
var lastTargetPosition = 0;
var lockTarget         = 0;
var currentPosition    = 0;

// init window
function initSlideWindow(window, glass) {
  windowWidth = parseInt($(window).getStyle('width').replace(/px$/g, ''));
  glassWidth  = parseInt($(glass).getStyle('width').replace(/px$/g, ''));
}

// slideWindow
function slideWindow(id, targetPosition) {
  // first slidWindow request
  if (targetPosition == 'right') {
    targetPosition = lastTargetPosition - windowWidth;
  } else if (targetPosition == 'left') {
    targetPosition = lastTargetPosition + windowWidth;
  }
  
  // lock is set?
  if (lockTarget != 0 && lockTarget != targetPosition) {
    // return
    return false;
  } else {
    // set lock
    lockTarget = targetPosition;
  }
  
  // set currentPosition
  currentPosition = parseInt($(id).getStyle('marginLeft').replace(/px$/g, ''));
  
  // close enough to stop?
  if (Math.abs(targetPosition - currentPosition) < 2) {
    // set currentPosition to targetPosition
    $(id).setStyle({'marginLeft':targetPosition + 'px'});
    
    // unset lock
    lockTarget = 0;
    
    // past boundaries - slide in from other side
    if (currentPosition > targetPosition && Math.abs(targetPosition) > glassWidth) {
      // move all the way to the right
      $(id).setStyle({'marginLeft':windowWidth + 'px'});
      
      // slide into first position
      slideWindow(id, 0);
    } else if (currentPosition < targetPosition && parseInt(currentPosition) >= 0) {
      // move all the way to the left
      $(id).setStyle({'marginLeft':(-1 * (glassWidth)) + 'px'});
      
      // slide into last position
      slideWindow(id, -1 * (glassWidth) + (glassWidth % windowWidth));
    }
    
    // return
    return true;
  }
  
  // store last targetPosition
  lastTargetPosition = targetPosition;
  
  // move from currentPosition closer to targetPosition
  if (currentPosition < targetPosition) {
    // move right
    $(id).setStyle({'marginLeft':currentPosition + (Math.floor((targetPosition - currentPosition) / 2)) + 'px'});
    
    // call self recursively
    setTimeout("slideWindow('" + id + "', " + targetPosition + ")", 32);
  } else if (currentPosition > targetPosition) {
    // move left
    $(id).setStyle({'marginLeft':currentPosition - (Math.floor((currentPosition - targetPosition) / 2)) + 'px'});
    
    // call self recursively
    setTimeout("slideWindow('" + id + "', " + targetPosition + ")", 32);
  }
}