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

    var waterFlow = function(opts){
        var defOpts = {
            column1 : 0,
            column2 : 0
        }

        //扩展options
        this.options = $.extend(defOpts, opts);

        this.container = $(".m-waterFlow");

        this.config = {
            colCounts : 2,          //当前列数
            colArray : [0,0,0,0],    //列数组
            isLoading : false
        };

        //当前分页开始
        this.pageNum = 0;
        // this.tag = (function(){
        //   var paramList = window.location.href.split('php?')[1];
        //   var paramArray = paramList.split('&');
        //   var paramJson = {};
        //   for( var i = 0 ; i < paramArray.length ; i++ ){
        //     var tem = paramArray[i].split('=') ;
        //     paramJson[tem[0]] = tem[1];
        //   }

        //   // console.log( paramJson );
        //   return paramJson.tg;
        //       // console.log( paramArray );
        // })()
        /*图库*/
        this.tag = (function(){
          var paramList = window.location.href.split('php?')[1];
          var paramArray = paramList.split('&');
          var paramJson = {};
          for( var i = 0 ; i < paramArray.length ; i++ ){
            var tem = paramArray[i].split('=') ;
            paramJson[tem[0]] = tem[1];
          }

          // console.log( paramJson );
          return paramJson.tag;
              // console.log( paramArray );
        })()

        //初始化事件监听
        this.listenEvent();

        //触发resize
        $(window).trigger('orientationchange');
    }


    //瀑布流事件监听
    waterFlow.prototype.listenEvent = function(){
        var _ts = this,
            _opts = _ts.options,
            _config = _ts.config;

        //计时器对象
        var _stObj = {};

        //瀑布流重绘
        $(window).on('orientationchange', function(){
            clearTimeout(_stObj.stWindow);
            _stObj.stWindow = setTimeout(function(){
                var _width = $(window).width();

                //定义宽度与对应列数
                //目前最多四列
                if(_width < 600){
                    _config.colCounts = 2;
                }else if(_width >= 600 && _width < 960){
                    _config.colCounts = 3;
                }else {
                    _config.colCounts = 4;
                }

                //重置列数组
                _ts.config.colArray = [0,0,0,0];

                //渲染瀑布流
                _ts.render();

            },200);
        });

        var loadmore = function(){
            clearTimeout(_stObj.stScroll);
            _stObj.stScroll = setTimeout(function(){
                //禁止重复读取
                if(!_config.isLoading){
                    if($(window).scrollTop() + 10 > $("body").get(0).scrollHeight - $(window).height()){
                        $.ajax({
                            type:'get',
                            url: 'http://tu.duowan.com/index.php?r=api/wap',
                            data: {
                                offset: _ts.pageNum * 10,
                                tg: _ts.tag
                            },
                            dataType: 'json',
                            success: function(data){
                                // console.log( data );
                                // alert(3333);
                                if( data.hasMore == 1 ) {
                                    _ts.push( data.tmpHtml );
                                    _ts.pageNum ++;
                                }
                                else{
                                    $(".m-loading").html("");
                                    $(window).off('scroll', loadmore);
                                }
                            }
                        })

                    }
                }else{
                    event.stopPropagation();
                }
            }, 200);
        }

        //滑动加载&插入更多
        $(window).on('scroll', loadmore);
    }

    //渲染瀑布流
    waterFlow.prototype.render = function(){
        var _ts = this,
            _opts = _ts.options,
            _config = _ts.config,
            _itemList = _ts.container.find('.item-con');

        //锁定
        _config.isLoading = true;

        var _st = null,
            m = 0,
            n = _itemList.length,

        _st = setTimeout(function(){
            _item = _itemList.eq(m),
            _img = _item.find("img");

            if(m >= n){
                _config.isLoading = false;
                return;
            }

            if(_item.attr('data-render')){
                m += 1;
            }else if(_img.get(0).height > 0){
                //根据列数设置图片块的宽度
                _item.css({"width": 100/_config.colCounts+"%"}).attr("data-render","true");

                //每列第一张处理
                if(m < _config.colCounts){
                    _item.css({
                        "top" : 0,
                        "left" : 100/_config.colCounts * m + "%"
                    });
                    _config.colArray[m] += _item.height();
                }

                //每列第二张之后的处理
                if(m > (_config.colCounts - 1)){
                    var _colIndex = 0,
                        _temp = _config.colArray[0];

                    //遍历当前序列对应数组
                    //向高度最小的数组中插值
                    for(var i = 0, j = _config.colCounts-1; i < j; i++){
                        if(_temp < _config.colArray[i+1]){
                            _temp = _config.colArray[i];
                        }else{
                            _colIndex = i+1;
                            _temp = _config.colArray[i+1];
                        }
                    }

                    //根据数组序列写入top, left等值
                    _item.css({
                        "top" : _config.colArray[_colIndex],
                        "left" : 100/_config.colCounts * (_colIndex) + "%"
                    });

                    //把当前数据块的高度加入到当前数组中
                    _config.colArray[_colIndex] += _item.height();
                }

                //插值完成后显示当前数据块
                _item.css({"visibility":"visible"});
                _ts.container.css({"height": Math.max.apply(null, _config.colArray)});
                m += 1;
            }else{
                m -= 1;
            }
            setTimeout(arguments.callee, 20);
        },20);
    }

    //瀑布流插入更多接口
    waterFlow.prototype.push = function(data){

        // console.log( typeof data );
        var _ts = this,
            _opts = _ts.options,
            _config = _ts.config,
            _data = $(data).clone()

        //根据String生成
        if(typeof data == 'string'){
            _data.appendTo('.m-waterFlow');
            setTimeout(function(){
                _ts.render();
            },800);
        }
        //根据JSON生成
        else if(typeof data == 'object'){

        }
    }

    $.fn.waterFlow = function (opts){
        return new waterFlow(opts);
    }

    /* fx_method */
    ;(function($, undefined){
      var document = window.document, docElem = document.documentElement,
        origShow = $.fn.show, origHide = $.fn.hide, origToggle = $.fn.toggle

      function anim(el, speed, opacity, scale, callback) {
        if (typeof speed == 'function' && !callback) callback = speed, speed = undefined
        var props = { opacity: opacity }
        if (scale) {
          props.scale = scale
          el.css($.fx.cssPrefix + 'transform-origin', '0 0')
        }
        return el.animate(props, speed, null, callback)
      }

      function hide(el, speed, scale, callback) {
        return anim(el, speed, 0, scale, function(){
          origHide.call($(this))
          callback && callback.call(this)
        })
      }

      $.fn.toggle = function(speed, callback) {
        if (speed === undefined || typeof speed == 'boolean')
          return origToggle.call(this, speed)
        else return this.each(function(){
          var el = $(this)
          el[el.css('display') == 'none' ? 'show' : 'hide'](speed, callback)
        })
      }

      $.fn.fadeTo = function(speed, opacity, callback) {
        return anim(this, speed, opacity, null, callback)
      }

      $.fn.fadeIn = function(speed, callback) {
        var target = this.css('opacity')
        if (target > 0) this.css('opacity', 0)
        else target = 1
        return origShow.call(this).fadeTo(speed, target, callback)
      }

      $.fn.fadeOut = function(speed, callback) {
        return hide(this, speed, null, callback)
      }

      $.fn.fadeToggle = function(speed, callback) {
        return this.each(function(){
          var el = $(this)
          el[
            (el.css('opacity') == 0 || el.css('display') == 'none') ? 'fadeIn' : 'fadeOut'
          ](speed, callback)
        })
      }

    })($)

    /* 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) }
      })
    })($)

    $(function(){
        var transform = $.fx.cssPrefix + 'transform',
            transitionEnd = $.fx.transitionEnd;

        //返回顶部按钮
        LegoMobi.initScrollTop();

        //返回键
        $(".m-menu__back").on("click", function(){
            history.back();
        });

        //顶部导航栏切换
        $(".m-header").on("touchstart", ".m-menu--toggle", function(){
            $(this).toggleClass('cur');
            var _nav = $('.m-header__nav');
            if(!_nav.hasClass('nav-toggle')){
                _nav.show();
                setTimeout(function(){
                    _nav.addClass('nav-toggle');
                },20);
            }else{
                _nav.removeClass('nav-toggle');
                setTimeout(function(){
                    _nav.hide();
                },300);
            }
        });

        //瀑布流
        $(".m-waterFlow").waterFlow({});

        var _imgWrap = $('.m-img__wrap'),
            _galleryWrap = $(".wrapper");

        //瀑布流查看详细图片插件，调用绑定
        // $(".m-gallery").on("click", ".item-base", function(){
        //     _imgWrap.fadeIn(400, function() {

        //         //隐藏瀑布流
        //         _galleryWrap.hide();
        //         // _galleryWrap.css({"visibility":"hidden"});

        //         //渲染幻灯片图库
        //         if (imgSrc.picInfo){
        //             var slider = Swipe($("#slider"), imgSrc.picInfo, {
        //                 continuous: false
        //             });
        //         }

        //     });
        //     return false;
        // });

        //隐藏幻灯片图库
        _imgWrap.on("click", ".m-img__back",function(){
            _imgWrap.fadeOut(400, function() {
                _galleryWrap.show();
                // _galleryWrap.css({"visibility":"visible"});
            });
        });
    });

    // 仿jquery slideDown下拉效果
    $.fn.slideDown = function (duration) {
      // 获取本来位置样式
      var position = this.css('position');
      // 确认元素处于显示状态
      this.show();
      // 让元素不可见
      this.css({
        position: 'absolute',
        visibility: 'hidden'
      });
      // 获取元素高度
      var height = this.height();
      // 设置元素高度为0，可见
      this.css({
        position: position,
        visibility: 'visible',
        overflow: 'hidden',
        height: 0
      });
      // 元素下拉动画
      this.animate({
        height: height
      }, duration);
    };
    // 仿jquery slideUp收起效果
    $.fn.slideUp = function (duration) {
      // 获取本来位置样式
      var position = this.css('position');
      // 确认元素处于显示状态
      this.show();
      // 获取元素高度
      var height = this.height();
      // 元素收到动画
      this.animate({
        height: 0
      }, duration , function(){
          // 恢复元素高度，但不可见
          $(this).css({
            height: height,
            position: position,
            display: 'none',
            visibility: 'hidden',
            overflow: 'hidden',
          });
      });
    };
    (function(){
        //首屏幻灯片初始化
        var slider = new Slider("#NormalSlider");
        slider.normal();
        // 选中面板事件
        $('#moreType').tap(function(event) {
          if($('.other-type').css('display') === 'none'){
              $('.other-type').slideDown(300);
          }else{
              $('.other-type').slideUp(200);
          }
        });
        // 点击选中类别
        $('.m-type').on('tap', 'a', function(event) {
          $('.m-type').find('a').removeClass('on');
          $(this).addClass('on');
        });
    })();

});

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) {//下个图集
                imgItemTemp += '<div style="width:' + slideWidth + 'px"><div class="next-album"><p>本图集已经浏览完毕</p></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().first().remove();
            $container.append(imgItemTemp);

        }

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

        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) {

        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');
                };
            }
        });

    }

    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);
        }

        $topBar.find('.m-img__title').html(title);

        $topBar.find('.m-img_num').html(slideIndex+1 + '/' + slideLength);
        if (imgSrc[slideIndex].title !== imgSrc[slideIndex].add_intro) {
            $('#imgInfo').html('<p>' + imgSrc[slideIndex].add_intro + '</p>').css('display','show');
        }else {
            $('#imgInfo').css('display','none');
        }

    }


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

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

        if(isShowTapbar){
            $("#topBar, #imgInfo, #imgControl").css('visibility', 'hidden');
            $container[0].setAttribute('data-topbar', 'false');
        }else {
            $("#topBar, #imgInfo, #imgControl").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
                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
                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();
}