/**
 * 商品详情图片放大器
 *
 *  imgItem --缩小版的框
 *  showBox      --正常状态的框
 *  zoomBox   --放大的框的盒子
 *  zoomMask      --放大的区域（黑色遮罩）
 *  zoomItem   --放大的框
 *
 * var obj = new ImageMagnifier('.imgItem', '.showBox','.zoomBox','.zoomMask','.zoomItem','activeClass').init();
 */
function ImageMagnifier(imgItem, showBox, zoomBox, zoomMask, zoomItem, activeClass) {
    this.showBox = showBox;
    this.zoomBox = zoomBox;
    this.imgItem = imgItem;
    this.zoomMask = zoomMask;
    this.zoomItem = zoomItem;
    this.activeClass = activeClass;
}
ImageMagnifier.prototype = {
    init: function () {
        var that = this;
        that.start();
        this.showHover();
        this.smallImgHover();
        this.showMove();
    },
    start: function () {
        var that = this;
        $(that.imgItem ).eq(0).addClass(that.activeClass);
    },
    showHover: function () {
        var that = this;
        $(that.showBox).hover(function(){
            $(that.zoomBox).show();
            $(that.zoomMask).show();
        },function(){
            $(that.zoomBox).hide();
            $(that.zoomMask).hide();
        });
    },
    smallImgHover: function () {
        var that = this;
        $('body').on("mouseover", that.imgItem, function(){
            var src=$(this).find('img').attr("src");
            if($(this).hasClass(that.activeClass)){
	    		return;
	    	}
            $(this).addClass(that.activeClass).siblings().removeClass(that.activeClass);
            $(that.showBox + '>img').attr("src",src);
            $(that.zoomItem+ '>img').attr("src",src);
        });
    },
    showMove:function(){
        var that = this;
        $('body').on("mousemove", that.showBox, function(e){
            var bigx=$(this).offset().left;
            var bigy=$(this).offset().top;
            var x= e.clientX;
            var y= e.clientY;
            var scrollx=$(window).scrollLeft();
            var scrolly=$(window).scrollTop();
            var ox=x+scrollx-bigx-$(that.zoomMask).width()/2;
            var oy=y+scrolly-bigy-$(that.zoomMask).height()/2;
            if(ox<=0){
                ox=0
            }
            if(ox>$(that.showBox).width()-$(that.zoomMask).width()){
                ox=$(that.showBox).width()-$(that.zoomMask).width();
            }
            if(oy<=0){
                oy=0
            }
            if(oy>$(that.showBox).height()-$(that.zoomMask).height()){
                oy=$(that.showBox).height()-$(that.zoomMask).height();
            }
            $(that.zoomMask).css({left:ox});
            $(that.zoomMask).css({top:oy});
            var bei=$(that.showBox).width()/$(that.zoomMask).width();
            $(that.zoomItem+ '>img').css(
                { marginLeft:-bei*ox,
                    marginTop:-bei*oy
                })
        });
    }
};
