setTimeout(suspensionBall, 500);

function suspensionBall() {
  var startEvt, moveEvt, endEvt

  if ('ontouchstart' in window) {
    startEvt = 'touchstart'
    moveEvt = 'touchmove'
    endEvt = 'touchend'
  } else {
    startEvt = 'mousedown'
    moveEvt = 'mousemove'
    endEvt = 'mouseup'
  }

  var drag = document.getElementById("al_ball")
  if(!drag){
    return false
  }
  drag.style.position = 'absolute'
  drag.style.cursor = 'move'

  var isClick = true
  var disX, disY, left, top, starX, starY

  drag.addEventListener(startEvt, function (e) {
    e.preventDefault()
    var e = e || window.event
    isClick = true

    starX = e.touches ? e.touches[0].clientX : e.clientX
    starY = e.touches ? e.touches[0].clientY : e.clientY

    disX = starX - drag.offsetLeft
    disY = starY - drag.offsetTop

    document.addEventListener(moveEvt, moveFun)
    document.addEventListener(endEvt, endFun)
  })

  var globalLeft
  function moveFun(e) {
    var e = e || window.event
    isClick = false
    left = (e.touches ? e.touches[0].clientX : e.clientX) - disX
    top = (e.touches ? e.touches[0].clientY : e.clientY) - disY

    if (left < 0) {
      left = 0
    } else if (left > document.documentElement.clientWidth - drag.offsetWidth) {
      left = document.documentElement.clientWidth - drag.offsetWidth
    }

    if (top < 0) {
      top = 0
    } else if (top > document.documentElement.clientHeight - drag.offsetHeight) {
      top = document.documentElement.clientHeight - drag.offsetHeight
    }
    drag.style.left = left + 'px'
    drag.style.top = top + 'px'
    globalLeft = left
  }

  function endFun(e) {
    document.removeEventListener(moveEvt, moveFun)
    document.removeEventListener(endEvt, endFun)
    
    if(isClick){
        showAl()
    } else {
        var clientWidthHalf = e.target.clientWidth / 2,
        windowWidthHalf = document.body.clientWidth / 2,
        clientLeft = globalLeft + clientWidthHalf
        //console.log(clientLeft, windowWidthHalf)
        if(clientLeft < windowWidthHalf){
            $("#al_ball").animate({
               left: 0
            });
        } else {
            $("#al_ball").animate({
               left: windowWidthHalf * 2 - clientWidthHalf * 2,
               right: 0
            });
        }
    }
  }
}