$(function() {
  $(window).on('pageshow', function() {
    $('#page-change-overlay').remove();
  });
  $('form.quixote').on('submit', function() {
    var overlay = $('<div id="page-change-overlay"></div>').appendTo('body');
    $('<div class="la-ball-running-dots"><div></div><div></div><div></div><div></div><div></div></div>'
     ).appendTo(overlay);
    overlay[0].offsetHeight;
    overlay.toggleClass('on');
    return true;
  });

  /* swipe support, this is complicated by bugs in Android 4
   * https://code.google.com/p/android/issues/detail?id=19827#makechanges
   */
  var swipeInfo = Object();
  $('form.quixote').on('touchstart', function(e) {
    swipeInfo.startX = e.originalEvent.changedTouches[0].pageX;
    swipeInfo.startY = e.originalEvent.changedTouches[0].pageY;
    swipeInfo.startTime = new Date().getTime();
  }).on('touchmove', function(e) {
    var touchobj = e.originalEvent.changedTouches[0];
    var distX = touchobj.pageX - swipeInfo.startX;
    var distY = touchobj.pageY - swipeInfo.startY;
    if (Math.abs(distX) < 20 && Math.abs(distY) > 10) {
       return;
    }
    e.preventDefault();
  }).on('touchend', function(e) {
    var touchobj = e.originalEvent.changedTouches[0];
    var dist = touchobj.pageX - swipeInfo.startX;
    if (dist==0) {
       $(e.target).trigger('focus');
       return;
    }
    var elapsedTime = new Date().getTime() - swipeInfo.startTime;
    var allowedTime = 500;
    var threshold = 150;
    var gotSwipe = (elapsedTime <= allowedTime && Math.abs(dist) >= threshold &&
                    Math.abs(touchobj.pageY - swipeInfo.startY) <= 100);
    if (gotSwipe) {
      if (dist < 0) {
         $('input[name=submit]').click();
      } else {
         if ($('input[name=previous]').length) {
           $('input[name=previous]').click();
         } else {
           $('input[name=cancel]').click();
         }
      }
      e.preventDefault();
    }
  });
  $('#main-content-wrapper').delegate('div.categories-list > ul > li > a', 'click', function() {
    if (! $(this).parent().hasClass('on')) {
      $(this).parents('div.categories-list').find('li').removeClass('on');
    }
    $(this).parent().toggleClass('on');
    return false;
  });
});
