var timer;
var wrap_box;
var facing = 1;
function start_hover_counter() {
  $('#wagon').stop();
  if (timer) clearTimeout(timer);
  (function(me) {
     timer = setTimeout(function() {
       timer = null;
       var d = $(me).attr('delta');
       if (!d) d = 0; else d = parseInt(d);
       var o = $(me).offset();
       var xo = $('#wagon').offset();
       var cp = xo.left;
       var np = (o.left - 35) - d;
       if ((np < cp && facing > 0) || (np > cp && facing < 0)) {
	 $('#wagon').stop().animate({
	   left: cp+74,
	   width: 2,
	   height: 76
	 }, 'fast', 'easeOutQuad', function() {
	   $('#wagon').each(function() {
	     if (np < cp) {
	       facing = -1;
	       this.src='images/wagon2.gif';
	     } else {
	       facing = 1;
	       this.src='images/wagon1.gif';
	     }
	     this.onload=function() {
	       $(this).animate({
		 left: cp,
		 width: 148,
		 height: 76
	       }, 'fast', 'easeOutQuad').animate({
		 left: np
	       }, 'slow', 'easeOutQuad');
	     };
	   });
	 });
       } else {
	 $('#wagon').stop().animate({
	   left: np
	 }, 'slow', 'easeOutQuad');
       }
     }, 100);
   })(this);
}
$(document).ready(function() {
  $('#wrap').each(function () {
    wrap_box = $(this).offset();
  });
  $('#wagon').each(function() {
    var o = $(this).offset();
    this.style.position = 'absolute';
    this.style.top = '21px'; // margin from css padding (20px) + border
    this.style.left = o.left+'px';
  });
  $('#nav a').each(function () {
    this.onmouseover = this.onmouseenter = start_hover_counter;
    // check this when we get a domain name xxx
    if (this.href == location.href) this.onmouseover();
  });
  window.onresize = function() {
    var old_left = wrap_box.left;
    $('#wrap').each(function () {
      wrap_box = $(this).offset();
    });
    $('#wagon').each(function() {
      var o = $(this).offset();
      var d = wrap_box.left - old_left;
      var x = o.left + d;
      this.style.left = x + 'px';
    });
  };
});
