/*
 Front Search
 * */

$(function() {
    
    var $tblist = $(".notice-list"),
        $tbparent = $tblist.parent(),
        $win = $(window),
        gridsize = $(".notice-item").width() || 160,
        $popin = null;
    
    function removePopin() {
        if ($popin) {
            $popin.remove();
            $popin = null;
        }
    }
    
    function movePopin() {
        if ($popin) {
            var $img = $popin.find(".notice-image"),
                $refli = $tblist.find("li[data-notice-id=" + $popin.attr("data-notice-id") + "]"),
                $refimg = $refli.find(".notice-image"),
                $md = $popin.find(".notice-metadata"),
                refo = $refimg.offset(),
                refw = $refimg.width(),
                winw = $win.width(),
                x = refo.left + refw / 2;
            $popin.css({
                top: refo.top - 11,
                width: refw + 220
            })
            if (x < winw / 2) {
                $img.css({
                    float: "left"
                });
                $md.css({
                    "margin-left": refw + 10,
                    "margin-right": 0
                });
                $popin.css({
                    right: "none",
                    left: refo.left - 11
                });
            } else {
                $img.css({
                    float: "right"
                });
                $md.css({
                    "margin-left": 0,
                    "margin-right": refw + 10
                });
                $popin.css({
                    left: "none",
                    right: winw - refo.left - refw - 11
                });
            }
        }
    }
    
    $tblist.find(".notice-item").mouseenter(function() {
        var $this = $(this);
        removePopin();
        if (!$this.find(".notice-image")[0].width) {
            return;
        }
        $popin = $('<div class="notice-popin"></div>').append($this.find(".notice-contents").clone());
        $popin.attr("data-notice-id",$this.attr("data-notice-id"));
        $popin.find(".notice-image").css("margin", 0);
        $("body").append($popin);
        movePopin();
        $popin.mouseleave(removePopin);
    });
    
    function adaptGrid() {
        $tblist.css({
            padding: "0 " + Math.floor($tbparent.width() % gridsize / 2) + "px"
        });
    }
    
    $tblist.find(".notice-image").load(function() {
        var iw = this.width,
            ih = this.height,
            scale = gridsize / Math.min(iw, ih),
            nw = scale * iw,
            nh = scale * ih;
        $(this).css({
            width: nw + "px",
            height: nh + "px",
            "margin-top": (gridsize - nh) / 2 + "px",
            "margin-left": (gridsize - nw) / 2 + "px"
        });
    });
    
    $win.resize(function() {
        adaptGrid();
        movePopin();
    });
    
    adaptGrid();
    
    
});
