$(function(e) {

    function init(e) {

        function checkImg() {

            function showImg(e) {
                e.show();
                imgbox.removeClass("loading");
            }

            var thisimg = $(this)
              , border = parseInt(imgbox.css("borderLeftWidth"))
              , w = main_w - border * 2
              , h = main_h - border * 2
              , this_w = thisimg.width()
              , this_h = thisimg.height();

            if (this_w == imgbox.width() && this_w <= w && this_h == imgbox.height() && this_h <= h) {
                showImg(thisimg);
                return;
            }

            if (this_w > w || this_h > h) {
                //s_h,s_w高度，宽度上限
                var s_h = h < this_h ? h : this_h
                  , s_w = w < this_w ? w : this_w;
                if (s_h / this_h <= s_w / this_w) {
                    thisimg.width(this_w * s_h / this_h);
                    thisimg.height(s_h);
                } else {
                    thisimg.width(s_w);
                    thisimg.height(this_h * s_w / this_w);
                }
            }
            imgbox.animate({
                width: thisimg.width(),
                height: thisimg.height(),
                marginTop: -(thisimg.height() / 2) - border,
                marginLeft: -(thisimg.width() / 2) - border
            }, 200, function() {
                showImg(thisimg);
            })
        }
        
        if (e){
            e.preventDefault();
        }
        //被点击的a标签
        var a = $(this)
          , imgurl = a.attr("href");
        if (!imgurl){
            return;
        }
        var newimg = $(new Image).hide();//创建一个新的img元素并隐藏
        $("#zoom .previous, #zoom .next").show();//显示切换按钮
        if (a.hasClass("zoom"))//如果a标签包含zoom类名，隐藏切换按钮
            $("#zoom .previous, #zoom .next").hide();
        if (!state) {
            state = true;
            bg_div.show();
            $("body").addClass("zoomed");
        }

        imgbox.html(newimg).delay(500).addClass("loading");
        newimg.load(checkImg).attr("src", imgurl);
        active_a = a;
    }

    //close
    function closePanel(e) {
        if (e)
            e.preventDefault();
        state = false;
        active_a = null;
        bg_div.hide();
        $("body").removeClass("zoomed");
        imgbox.empty();
    }

    //上一张
    function prevImg() {
        var li = active_a.parent("div").parent("div");
        if (li.index() == 0){//如果前面没有了，跳转到最后一个
            li = $(".gallery>div:last-child");
        }
        li.prev().find("a").trigger("click");//触发上一个点击事件
    }

    //下一张
    function nextImg() {
        var li = active_a.parent("div").parent("div");
        if (li.index() == $(".gallery>div").length-1)
            li = $(".gallery>div:first-child");
        li.next().find("a").trigger("click");//触发下一个点击事件
    }

    $("body").append('<div id="zoom"><a class="close"></a><a href="#previous" class="previous"></a><a href="#next" class="next"></a><div class="content loading"></div></div>');
    var bg_div = $("#zoom").hide()
      , imgbox = $("#zoom .content")
      , state = false   //当前显示状态
      , active_a = null //活跃状态的a标签
      , main_w = $(window).width()
      , main_h = $(window).height();

    //只有一张图时，不显示prev和next按钮
    if ($(".gallery .store-content-slide a").length == 1)
        $(".gallery .store-content-slide a")[0].addClass("zoom");

    $(".zoom, .gallery .store-content-slide a").on("click", init)

    $("#zoom .close").on("click", closePanel);

    $("#zoom .previous").on("click", prevImg);

    $("#zoom .next").on("click", nextImg);

    $(window).on("resize", function (){
        main_w = $(window).width();
        main_h = $(window).height();
    });
    //关闭
    bg_div.on("click", function(e) {
        e.preventDefault();
        if ($(e.target).attr("id") == "zoom")//js中事件是会冒泡的，所以this是可以变化的，但event.target不会变化，它永远是直接接受事件的目标DOM元素；
            closePanel();
    });
    //禁止鼠标滚轮事件
    $(window).on("mousewheel DOMMouseScroll", function(e) {
        if (!active_a)
            return;
        e.stopPropagation();//事实上stoppropagation和cancelBubble的作用是一样的，都是用来阻止浏览器默认的事件冒泡行为。
        e.preventDefault();//通知 Web 浏览器不要执行与事件关联的默认动作（如果存在这样的动作）
        e.cancelBubble = false;//设置或获取当前事件是否要在事件句柄中向上冒泡
    })
    //键盘事件
    $(document).keydown(function(e) {
        if (!active_a)
            return;
        if (e.which == 38 || e.which == 40)
            e.preventDefault();
        if (e.which == 27)
            closePanel();
        if (e.which == 37 && !active_a.hasClass("zoom"))
            prevImg();
        if (e.which == 39 && !active_a.hasClass("zoom"))
            nextImg();
    });
});
