seajs.use(['mobi/zepto/1.1.3/zepto','mobi/mo/1.0.0/mo' , 'mobi/scroll/1.0.0/scroll'],function($, LegoMobi , scroll){

    /* touch */
    ;(function($){
      var touch = {},
        touchTimeout, tapTimeout, swipeTimeout, longTapTimeout,
        longTapDelay = 750,
        gesture

      function swipeDirection(x1, x2, y1, y2) {
        return Math.abs(x1 - x2) >=
          Math.abs(y1 - y2) ? (x1 - x2 > 0 ? 'Left' : 'Right') : (y1 - y2 > 0 ? 'Up' : 'Down')
      }

      function longTap() {
        longTapTimeout = null
        if (touch.last) {
          touch.el.trigger('longTap')
          touch = {}
        }
      }

      function cancelLongTap() {
        if (longTapTimeout) clearTimeout(longTapTimeout)
        longTapTimeout = null
      }

      function cancelAll() {
        if (touchTimeout) clearTimeout(touchTimeout)
        if (tapTimeout) clearTimeout(tapTimeout)
        if (swipeTimeout) clearTimeout(swipeTimeout)
        if (longTapTimeout) clearTimeout(longTapTimeout)
        touchTimeout = tapTimeout = swipeTimeout = longTapTimeout = null
        touch = {}
      }

      function isPrimaryTouch(event){
        return (event.pointerType == 'touch' ||
          event.pointerType == event.MSPOINTER_TYPE_TOUCH)
          && event.isPrimary
      }

      function isPointerEventType(e, type){
        return (e.type == 'pointer'+type ||
          e.type.toLowerCase() == 'mspointer'+type)
      }

      $(document).ready(function(){
        var now, delta, deltaX = 0, deltaY = 0, firstTouch, _isPointerType

        if ('MSGesture' in window) {
          gesture = new MSGesture()
          gesture.target = document.body
        }

        $(document)
          .bind('MSGestureEnd', function(e){
            var swipeDirectionFromVelocity =
              e.velocityX > 1 ? 'Right' : e.velocityX < -1 ? 'Left' : e.velocityY > 1 ? 'Down' : e.velocityY < -1 ? 'Up' : null;
            if (swipeDirectionFromVelocity) {
              touch.el.trigger('swipe')
              touch.el.trigger('swipe'+ swipeDirectionFromVelocity)
            }
          })
          .on('touchstart MSPointerDown pointerdown', function(e){
            if((_isPointerType = isPointerEventType(e, 'down')) &&
              !isPrimaryTouch(e)) return
            firstTouch = _isPointerType ? e : e.touches[0]
            if (e.touches && e.touches.length === 1 && touch.x2) {
              // Clear out touch movement data if we have it sticking around
              // This can occur if touchcancel doesn't fire due to preventDefault, etc.
              touch.x2 = undefined
              touch.y2 = undefined
            }
            now = Date.now()
            delta = now - (touch.last || now)
            touch.el = $('tagName' in firstTouch.target ?
              firstTouch.target : firstTouch.target.parentNode)
            touchTimeout && clearTimeout(touchTimeout)
            touch.x1 = firstTouch.pageX
            touch.y1 = firstTouch.pageY
            if (delta > 0 && delta <= 250) touch.isDoubleTap = true
            touch.last = now
            longTapTimeout = setTimeout(longTap, longTapDelay)
            // adds the current touch contact for IE gesture recognition
            if (gesture && _isPointerType) gesture.addPointer(e.pointerId);
          })
          .on('touchmove MSPointerMove pointermove', function(e){
            if((_isPointerType = isPointerEventType(e, 'move')) &&
              !isPrimaryTouch(e)) return
            firstTouch = _isPointerType ? e : e.touches[0]
            cancelLongTap()
            touch.x2 = firstTouch.pageX
            touch.y2 = firstTouch.pageY

            deltaX += Math.abs(touch.x1 - touch.x2)
            deltaY += Math.abs(touch.y1 - touch.y2)
          })
          .on('touchend MSPointerUp pointerup', function(e){
            if((_isPointerType = isPointerEventType(e, 'up')) &&
              !isPrimaryTouch(e)) return
            cancelLongTap()

            // swipe
            if ((touch.x2 && Math.abs(touch.x1 - touch.x2) > 30) ||
                (touch.y2 && Math.abs(touch.y1 - touch.y2) > 30))

              swipeTimeout = setTimeout(function() {
                touch.el.trigger('swipe')
                touch.el.trigger('swipe' + (swipeDirection(touch.x1, touch.x2, touch.y1, touch.y2)))
                touch = {}
              }, 0)

            // normal tap
            else if ('last' in touch)
              // don't fire tap when delta position changed by more than 30 pixels,
              // for instance when moving to a point and back to origin
              if (deltaX < 30 && deltaY < 30) {
                // delay by one tick so we can cancel the 'tap' event if 'scroll' fires
                // ('tap' fires before 'scroll')
                tapTimeout = setTimeout(function() {

                  // trigger universal 'tap' with the option to cancelTouch()
                  // (cancelTouch cancels processing of single vs double taps for faster 'tap' response)
                  var event = $.Event('tap')
                  event.cancelTouch = cancelAll
                  touch.el.trigger(event)

                  // trigger double tap immediately
                  if (touch.isDoubleTap) {
                    if (touch.el) touch.el.trigger('doubleTap')
                    touch = {}
                  }

                  // trigger single tap after 250ms of inactivity
                  else {
                    touchTimeout = setTimeout(function(){
                      touchTimeout = null
                      if (touch.el) touch.el.trigger('singleTap')
                      touch = {}
                    }, 250)
                  }
                }, 0)
              } else {
                touch = {}
              }
              deltaX = deltaY = 0

          })
          // when the browser window loses focus,
          // for example when a modal dialog is shown,
          // cancel all ongoing events
          .on('touchcancel MSPointerCancel pointercancel', cancelAll)

        // scrolling the window indicates intention of the user
        // to scroll, not tap or swipe, so cancel all ongoing events
        $(window).on('scroll', cancelAll)
      })

      ;['swipe', 'swipeLeft', 'swipeRight', 'swipeUp', 'swipeDown',
        'doubleTap', 'tap', 'singleTap', 'longTap'].forEach(function(eventName){
        $.fn[eventName] = function(callback){ return this.on(eventName, callback) }
      })
    })($)

    /* Action */
    $(function(){
        if (imgSrc.picInfo){
            var slider = Swipe(document.getElementById('slider'), imgSrc.picInfo, {
                continuous: false
            });
        }
    });

    // 滚动条
    scroll(('#infoContent'),{
        // 滚动条
        scrollbars: true,
        // 鼠标是否可以滚动
        mouseWheel: true,
        // 滚动条是否可以收缩
        shrinkScrollbars: 'scale',
    });

function Swipe(container, imgSrc, options) {

    var noop = function() {}; // simple no operation function
    var offloadFn = function(fn) {
        setTimeout(fn || noop, 0)
    }; // offload a functions execution

    // quit if no root element
    if (!container) return;

    var $container = $(container).children(),
        options = options || {},
        slideIndex = parseInt(options.startSlide, 10) || 0,
        slideSpeed = options.speed || 300,
        slideWidth,
        slideHeight,
        slideLength,
        containerTouch,
        isSlideMove = false,
        isScale = false,
        touchTimeout = null;

    $container[0].setAttribute('data-topbar', 'true');
   
    function setup() {

        var imgItemTemp = '';

        slideLength = imgSrc.length;
        containerTouch = {};
     //   $container[0].style= '';
        // determine width of each slide
        //slideWidth = $container.width();
        slideWidth = document.body.getBoundingClientRect().width || document.body.offsetWidth;

        //console.log(slideWidth);

        if (slideIndex - 1 < 0) {
            imgItemTemp += '<div style="width:' + slideWidth + 'px"><div style="height:10px"></div></div>';
        }else {
            imgItemTemp += '<div style="width:' + slideWidth + 'px"><img  data-loadimg="false" src="http://assets.dwstatic.com/project/mobidwartcle/img/loading.gif" data-imgIndex="' + (slideIndex - 1) + '"></div>';
        }

        imgItemTemp += '<div style="width:' + slideWidth + 'px"><img  data-loadimg="false" src="http://assets.dwstatic.com/project/mobidwartcle/img/loading.gif" data-imgIndex="' + slideIndex + '"></div>';

        if (slideIndex + 1 > slideLength) {
            imgItemTemp += '<div style="width:' + slideWidth + 'px"><div style="height:10px"></div></div>';
        } else if (slideIndex + 1 == slideLength) {
            imgItemTemp += '<div style="width:' + slideWidth + 'px"><div style="height:10px;font-size:30">last</div></div>';
        } else {
            imgItemTemp += '<div style="width:' + slideWidth + 'px"><img data-loadimg="false" src="http://assets.dwstatic.com/project/mobidwartcle/img/loading.gif" data-imgIndex="' + (slideIndex + 1) + '"></div>';
        }

        $container.html(imgItemTemp);

        $container.css({
            'width': 3 * slideWidth,
            'visibility': 'visible'
        });

        showTitle();
        loadImg($container.find('img'));

        translate($container, -slideWidth + 'px, 0', 1, 0, function(){
            $container.on('touchstart', containerStart);
            $container.on('touchmove', containerMove);
            $container.on('touchend', slideMove);
        });  

    }


    function circle(direction) {

        var imgItemTemp = '';
        //console.log('circle');
        slideIndex = slideIndex + direction;

        if(direction == -1) {
            if (slideIndex - 1 < 0) {
                imgItemTemp += '<div style="width:' + slideWidth + 'px"><div style="height:10px"></div></div>';
            }else {
                imgItemTemp += '<div style="width:' + slideWidth + 'px"><img  data-loadimg="false" src="http://assets.dwstatic.com/project/mobidwartcle/img/loading.gif" data-imgIndex="' + (slideIndex - 1) + '"></div>';
            }

            $container.children().last().remove();
            $container.prepend(imgItemTemp);

        }

        if(direction == 1) {
            if (slideIndex + 1 > slideLength) {
                imgItemTemp += '<div style="width:' + slideWidth + 'px"><div style="height:10px"></div></div>';
            } else if (slideIndex + 1 == slideLength) {//下个图集
                var lastPage = document.getElementById('rec-imgs').outerHTML;
                // console.log(lastPage);
                imgItemTemp += '<div style="width:' + slideWidth + 'px"><div class="next-album">'+ lastPage +'</div>';
                // imgItemTemp += lastPage;
            } else {
                imgItemTemp += '<div style="width:' + slideWidth + 'px"><img data-loadimg="false" src="http://assets.dwstatic.com/project/mobidwartcle/img/loading.gif" data-imgIndex="' + (slideIndex + 1) + '"></div>';
            }

            $container.children().first().remove();
            $container.append(imgItemTemp);

            if($('.next-album').find('#rec-imgs').length > 0 && $('.next-album').find('#rec-imgs').height() <=0){
                $('.next-album').find('#rec-imgs').show();
                setTimeout(function(){
                    var wraHeight = ($(window).height() - $('.next-album').find('#rec-imgs').height())/2-20;
                    if($('.next-album').find('#rec-imgs').height()>0){
                        $('.next-album').find('#rec-imgs').css({
                            'marginTop': wraHeight + 'px',
                            'visibility': 'visible',
                        });
                    }
                }, 1000);
            }
        }

        showTitle();
        loadImg($container.find('img[data-loadimg]'));
        translate($container, -slideWidth + 'px, 0', 1, 0, function(){
            //console.log('reset');
            $container.on('touchstart', containerStart);
            $container.on('touchmove', containerMove);
            $container.on('touchend', slideMove);
        });  
    }

    function loadImg(imgDom) {

        var docWidth = $(document).width();
        var docHeight = $(document).height();

        imgDom.each(function(index){
            var img = new Image(),
                self = this,
                isLoad = this.getAttribute('data-loadimg') != 'false',
                imgIndex = this.getAttribute('data-imgIndex'),
                url = imgSrc[imgIndex].url;

            if(!isLoad) {
                img.src = url;
                img.onload = function(){ 
                    self.src = url;
                    self.setAttribute('data-loadimg', 'true');
                    var imgWidth = img.width;
                    var imgHeight = img.height;
                    var thisHeight = docWidth / imgWidth * imgHeight;
                    if(thisHeight < docHeight /1.5){
                        console.log();
                        var mt = (docHeight - $('.img-info-n').height()-thisHeight)/2+$('#topBar').height()/2;
                        self.style.marginTop = mt + 'px';
                    }


                };
            }
        });
        
    }

    function showTitle() {
        var $topBar = $("#topBar"),
            title = imgSrc[slideIndex] && imgSrc[slideIndex].title;

        if (title === undefined) return false;

        if( /\d[)）]$/.test(title)) {
            title = title.substr(0, title.length-1) + '/' + slideLength + title.substr(title.length-1);
        }

        // 标题
        if(title.length > 15){
            title = title.substring(0,15) + '...';    
        }
        
        $('.img-info-title').text(title);
        // $topBar.find('.m-img__title').html(title);

        // 当前画页
        var img_num = '<span>' + (slideIndex+1) + '</span>/' + slideLength;
        $('.m-img_num').html(img_num);

        // if (imgSrc[slideIndex].title !== imgSrc[slideIndex].add_intro) {
        //     $('#imgInfo').html('<p>' + imgSrc[slideIndex].add_intro + '</p>').css('display','show');
        // }else {
        //     $('#imgInfo').css('display','none');
        // }
        // 内容
        $('#imgInfoContent').text(imgSrc[slideIndex].add_intro);

    }
   
    
    $container.on('singleTap', function(event){
        //console.log('singleTap');

        var isShowTapbar = $container[0].getAttribute('data-topbar') == 'true';

        if(isShowTapbar){
            $("#topBar, #imgInfo, #imgControl , .img-info-n").css('visibility', 'hidden');
            $container[0].setAttribute('data-topbar', 'false');
        }else {
            $("#topBar, #imgInfo, #imgControl , .img-info-n").css('visibility', 'visible');
            $container[0].setAttribute('data-topbar', 'true');
        }
        
    });

    $container.on('doubleTap', function(event){
        //console.log('doubleTap');
        clearTimeout(touchTimeout);
        zoomImg(event);
    });

    

    // $container.on('touchend', function(event){
          
    // });

    function translate(ele, dist, scale, speed, callback) {

        isSlideMove = true;
        //console.log(dist);
        ele.animate({
            translate: dist,
            scale: scale
        }, 
        speed,
        'ease-out', 
        function (){
            isSlideMove = false;
            callback && callback();
        });

    }

    function containerStart(event) {
        //console.log('touchstart');

        clearTimeout(touchTimeout);
        if (isSlideMove) return;
        
        containerTouch = {};

        var touches = event.touches[0],
            style = window.getComputedStyle(this);

        containerTouch.matrix = new WebKitCSSMatrix(style.webkitTransform);
            
        containerTouch.start = {
            x: touches.pageX
        };
    }

    function containerMove(event) {

        event.preventDefault();
        clearTimeout(touchTimeout);
        if (isSlideMove) return;

        var touches = event.touches[0],
            self = this,
            width;

        containerTouch.delta = {
            x: touches.pageX - containerTouch.start.x
        }

        width = containerTouch.matrix.m41 + containerTouch.delta.x;

        this.style.webkitTransform =
        this.style.msTransform =
            this.style.MozTransform =
            this.style.OTransform = 'translateX(' + width + 'px)';

        // touchTimeout = setTimeout(function(){
        //     slideMove(self, event);
        // }, 100); 
    }

    function scaleStart(event) {
        //console.log('touchstart');

        clearTimeout(touchTimeout);
        if (isSlideMove) return;

        containerTouch = {};

        var touches = event.touches[0],
            style = window.getComputedStyle(this);

        containerTouch.matrix = new WebKitCSSMatrix(style.webkitTransform);

        var height = $(this).height() - document.body.getBoundingClientRect().height || document.body.offsetHeight;
        containerTouch.maxY = height > 0 ?  height/2 : 0;
            
        containerTouch.start = {
            x: touches.pageX,
            y: touches.pageY
        };
    }

    function scaleMove(event) {

        event.preventDefault();
        clearTimeout(touchTimeout);
        if (isSlideMove) return;

        var touches = event.touches[0],
            self = this,
            width,
            height;

        containerTouch.delta = {
            x: touches.pageX - containerTouch.start.x,
            y: touches.pageY - containerTouch.start.y
        }

        width = containerTouch.matrix.m41 + containerTouch.delta.x;
        height = containerTouch.matrix.m42 + containerTouch.delta.y;
        
        if (containerTouch.maxY  === 0) {
            height = 0;
        }else if (Math.abs(height) - containerTouch.maxY >= 0) {
            //scaleTouch.delta.y = scaleTouch.delta.y < 0 ? -scaleTouch.y : scaleTouch.y;
            height = height < 0 ? -scontainerTouch.maxY : containerTouch.maxY;
        }

        this.style.webkitTransform = 
        this.style.msTransform =
            this.style.MozTransform =
            this.style.OTransform = 'translate(' + width + 'px, ' + height + 'px)' + ' scale(2)';

        // touchTimeout = setTimeout(function(){

        //     scaleSlide(self, event);
        // }, 100); 
    }

    function scaleSlide(event){

        var dist,
            isNext = slideIndex > 0 && slideIndex < (slideLength - 1),
            width;

        if (isSlideMove) return;

        var style = window.getComputedStyle(this),
            matrix = new WebKitCSSMatrix(style.webkitTransform);

        var confine = $(this).width() - slideWidth < 0 ? 0 : ($(this).width() - slideWidth)/2;

    //    var confine = ($(this).width() - slideWidth)/2 + slideWidth * 1/6;

        if ( Math.abs(matrix.m41) - confine > 0 ) {

            if (matrix.m41 > 0 && slideIndex > 0 && Math.abs(matrix.m41) - confine - slideWidth/6 > 0 ) { // slide left
                dist = '0, 0';
           //     slideIndex -= 1;
                translate($container, dist, 1, slideSpeed, function(){
                    circle(-1);
                });

                this.style.webkitTransform = 
                this.style.msTransform =
                    this.style.MozTransform =
                    this.style.OTransform = 'translate(0px,  0px) scale(1)';

                //console.log('right');
            }else if ( matrix.m41 <= 0 && slideIndex < slideLength && Math.abs(matrix.m41) - confine - slideWidth/6 > 0 ) { // slide right
                dist = -2 * slideWidth + 'px, 0';
          //      slideIndex += 1;
                translate($container, dist, 1, slideSpeed, function(){
                    circle(1);
                });

                this.style.webkitTransform = 
                this.style.msTransform =
                    this.style.MozTransform =
                    this.style.OTransform = 'translate(0px,  0px) scale(1)';

                //console.log('left');
            }else { // back

                width = matrix.m41 >= 0 ? confine : -confine;
                dist = width + 'px, ' + matrix.m42 + 'px';

                translate($(this), dist, 2, slideSpeed);

                //console.log('back');
            }
            
        }
    }

    function slideMove(event) {
        
        var dist,
            isNext = slideIndex > 0 && slideIndex < (slideLength - 1);

        if (isSlideMove) return;

        if (containerTouch.delta && Math.abs(containerTouch.delta.x) - slideWidth * 1/6 > 0 ) {

            if (containerTouch.delta.x > 0 && slideIndex > 0) { // slide right
                if(slideIndex - 1 <= slideLength){
                    $('.m-img__title').hide();
                    $('.m-img__com').show();
                    $('.img-info-n').show();
                }else{
                    $('.m-img__title').show();
                    $('.m-img__com').hide();
                    $('.img-info-n').hide();
                }
                dist = '0, 0';
             //   slideIndex -= 1;
                $(this).off('touchstart');
                $(this).off('touchmove');
                $(this).off('touchend');
                translate($(this), dist, 1, slideSpeed, function(){
                    circle(-1);
                });
            }else if ( containerTouch.delta.x <= 0 && slideIndex < slideLength ) { // slide left
                if(slideIndex + 1 >= slideLength){
                    $('.m-img__title').show();
                    $('.m-img__com').hide();
                    $('.img-info-n').hide();
                }else{
                    $('.m-img__title').hide();
                    $('.m-img__com').show();
                    $('.img-info-n').show();
                }
                dist = -2 * slideWidth + 'px, 0';
              //  slideIndex += 1;
                $(this).off('touchstart');
                $(this).off('touchmove');
                $(this).off('touchend');
                translate($(this), dist, 1, slideSpeed, function(){
                    circle(1);
                });
            }else { // back
                dist = -slideWidth + 'px, 0';
                translate($(this), dist, 1, slideSpeed);
            }
            
        }else { // back
            dist = -slideWidth + 'px, 0';
            translate($(this), dist, 1, slideSpeed);
        }
    }

    function zoomImg(event) {

        //console.log('zoomImg');
        var $scaleEle = $container.children().eq(1).children(),
            isImgLoad = $scaleEle[0].getAttribute('data-loadimg') == "true";

        if(isScale && isImgLoad) {

            $scaleEle.off('touchstart');
            $scaleEle.off('touchmove');
            $scaleEle.off('touchend');

            translate($scaleEle, '0, 0', 1, slideSpeed, function() {
                $container.on('touchstart', containerStart);
                $container.on('touchmove', containerMove);
                $container.on('touchend', slideMove);
            });
            isScale = false;

        } else if(isImgLoad){//放大

            $container.off('touchstart');
            $container.off('touchmove');
            $container.off('touchend');

            translate($scaleEle, '0, 0', 2, slideSpeed, function(){
                $scaleEle.on('touchstart', scaleStart);
                $scaleEle.on('touchmove', scaleMove);
                $scaleEle.on('touchend', scaleSlide);
            });
            isScale = true;

        }

    }

    $(window).on('resize', function(){
 //       setTimeout(function(){
            setup();
  //      }, 1000)
        
    });
    // trigger setup
    setup();  
}



});