if (typeof ABLE == "undefined" || !ABLE) {
    var ABLE = {};
}

ABLE.currentTouch = {};

ABLE.init = function(params){
  this.wrapper = document.getElementById(params.wrapper);
  $.extend(jQuery.browser,{SafariMobile : navigator.userAgent.toLowerCase().match(/iP(hone|ad)/i)});
  
  /* more touching! */
  
  this.currentPos = 0;
  this.movePos = 0;
  this.tempPos = 0;
  this.direction = 0;
  this.yMovement = false;
  this.xMovement = false;
  this.threshold = params.threshold;
  
  this.move = function(speed){
    var that = this;
    var itemLength = -1 * that.galleryItems.length * that.itemWidth;
    if(speed < 0){
      that.currentPos = that.currentPos + that.itemWidth;
      if(that.currentPos > 0){
        that.currentPos = 0;
      }
    }
    else {
      that.currentPos = that.currentPos - that.itemWidth;
      if(that.currentPos <= itemLength){
        that.currentPos = itemLength + that.itemWidth;
      }
    }
  };
  
  this.bindTouches = function(){
    var that = this;
    that.wrapper.addEventListener('touchstart', function(e) {
      var touch = e.touches[0];
      ABLE.currentTouch.startX = touch.screenX;
      ABLE.currentTouch.startY = touch.screenY;
    },false);
    that.wrapper.addEventListener('touchmove', function(e) {
      var touch = e.touches[0];
      var begin = ABLE.currentTouch.startX;
      var beginY = ABLE.currentTouch.startY;
      var updown = Math.abs(touch.screenY - beginY);
      var leftright = Math.abs(touch.screenX - ABLE.currentTouch.startX);
      that.movePos = that.currentPos + touch.screenX - begin;
      if(updown >= that.threshold){
        that.yMovement = true;
      }
        else {
          if(that.tempPos > that.movePos){
            that.direction = 1;
          }
          else {
            that.direction = -1;
          }
          if(leftright >= that.threshold){
          var indicationMovement = (that.currentPos - that.threshold)*that.direction;
            $('#'+params.wrapper).css('-webkitTransitionDuration','2s');
            $('#'+params.wrapper).css('-webkitTransform', 'translate3d('+indicationMovement+'px,0,0)');
          }
        }
        that.tempPos = that.movePos;
      },false);
      that.wrapper.addEventListener('touchend', function(e) {
      var touch = e.changedTouches[0];
      var page = parseFloat(params.current) + parseInt(that.direction);
      var leftright = Math.abs(touch.screenX - ABLE.currentTouch.startX);
        ABLE.currentTouch.endX = touch.screenX;
        ABLE.currentTouch.endY = touch.screenY;
        if(leftright >= that.threshold){
          if(that.direction === 1){
            window.location = params.right;
          }
          else {
            window.location = params.left;            
          }
        }
      }, false);
  };
  $(function(){
    if($.browser.SafariMobile){
      ABLE.bindTouches();
    }
  });
}
