/**
 * @fileoverview Giant Interective Group, Inc. Javascript Library v#version.
 * 该Javascript UI库是基于jQuery的扩展。
 * @version 1.0.0, #date 2009-04-01
 * @author  Zhangkai
 * Depend on jQuery 1.3.x
 */
(function($) {
    var opts = null;
    var datas = null;
    var autoInterval = null;
    var currentPicture;
    $.fn.slideShow = function(options) {
        opts = $.extend({},
        $.fn.slideShow.defaults, options);
        if(opts.data&&opts.data.length>0){
            _init();
        }else
        {
            alert("该相册不存在照片");
        }
    };
    function _init() {
        $("body").append(opts.overlayTemp+opts.domTemp);
        $(".giant-ui-slideShowOverlay").css({
            width: _getPageSize()[0] + "px",
            height: _getPageSize()[1] + "px",
            opacity: opts.overlayOpcity
        });
        $(".giant-ui-slideShow").css({
            left: (_getPageSize()[0] - 200) / 2 + "px",
            top: $("body").scrollTop()+$(document).scrollTop() + opts.topPix + "px"
        });
        _getData();
    }
    function _getData() {
	  if (opts.data) {
        if (opts.dataType == "json") {
            datas = eval(opts.data);
        } else if (opts.dataType == "xml") {
         //   datas = $.fn.slideShow.xmlToJson(optsdata);
        }
		currentPicture = new Picture(datas[opts.startIndex].title, datas[opts.startIndex].remark, opts.startIndex, datas[opts.startIndex].imageSrc);
        currentPicture.show();
        _eventBind();
        isFirst = false;
		}
    }
     /**
      *Picture类
      *@private
      *@param {String} title 图片标题
      *@param {String} remark 图片描述
      *@param {String} currentIndex 当前图片索引
      *@param {String} imageSrc 图片路径
      */
    function Picture(title, remark, currentIndex, imageSrc) {
        this.title = title;
        this.remark = remark;
        this.currentIndex = currentIndex;
        this.imageSrc = imageSrc;
        this.dataLength = datas.length;
        this.nextIndex = currentIndex < this.dataLength - 1 ? currentIndex + 1 : 0;
        this.prevIndex = currentIndex == 0 ? this.dataLength - 1 : currentIndex - 1;
        this.auto = null;
    }
     /**
    * 返回当前图的下一张图对象。
    * @returns {Picture}返回Picture的一个对象
    */
    Picture.prototype.getNext = function() {
        return new Picture(datas[this.nextIndex].title, datas[this.nextIndex].remark, this.nextIndex, datas[this.nextIndex].imageSrc);
    };
    /**
    * 返回当前图的上一张图对象。
    * @returns {Picture}返回Picture的一个对象
    */
    Picture.prototype.getPrev = function() {
        return new Picture(datas[this.prevIndex].title, datas[this.prevIndex].remark, this.prevIndex, datas[this.prevIndex].imageSrc);
    };
    /**
    * 返回当前相册的最后一张图对象。
    * @returns {Picture}返回Picture的一个对象
    */
    Picture.prototype.getLast= function(){
        return new Picture(datas[this.dataLength-1].title, datas[this.dataLength-1].remark, this.dataLength-1, datas[this.dataLength-1].imageSrc);
    }
    /**
    * 返回当前相册的第一张图对象。
    * @returns {Picture}返回Picture的一个对象
    */
    Picture.prototype.getFirst= function(){
        return new Picture(datas[0].title, datas[0].remark, 0, datas[0].imageSrc);
    }
    /**
    * 检测当前图像是否为该相册的第一张图像。
    * @returns {Boolean}
    */
    Picture.prototype.isFirst = function(){
        if(this.currentIndex ==0){
            return true;
        }
        return false;
    }
    /**
    * 检测当前图像是否为该相册的最后一张图像。
    * @returns {Boolean}
    */
    Picture.prototype.isLast = function(){
        if(this.currentIndex ==this.dataLength-1){
            return true;
        }
        return false;
    }
    /**
     *显示图片动画。
     */
    Picture.prototype.show = function() {
        //若loading时间大于500毫秒，则出现loading图片
        var isLoading = true;
        var timeOuter = setTimeout(function() {
            if (isLoading){
				$(".giant-ui-slideShow .loading").show();
				$(".giant-ui-slideShow .slideShowImage").hide();
			}
        },
        500);
        var myImg = new Image();
        var _this = this;
        isLoading = true;
        myImg.onload = function() {
            isLoading = false;
            $(".giant-ui-slideShow .loading").hide();
			$(".giant-ui-slideShow .slideShowImage").show();
            _resizeContainer(myImg.width, myImg.height);
            $(".giant-ui-slideShow .slideShowImage").attr("src", myImg.src);
            $(".giant-ui-slideShow .imageDataContainer h3").html(_this.title);
            $(".giant-ui-slideShow .imageDataContainer .numberDisplay").html((_this.currentIndex + 1) + "/" + _this.dataLength );
            $(".giant-ui-slideShow .imageDataContainer .remark").html(_this.remark);
            myImg.onload = function() {};
        };
        myImg.onerror = function() {
            myImg.src = opts.defaultImage;
        }
        //src地址的设置放在onload之后，防止IEbug
        myImg.src = this.imageSrc;
    }
     /**
    * 图片自动播放。
    */
    Picture.prototype.autoPlay = function() {
        autoInterval = setInterval(function() {
            currentPicture = currentPicture.getNext();
            currentPicture.show();
        },
        opts.autoPlaySpeed);
    };
    /**
    * 停止图片自动播放。
    */
    Picture.prototype.stopAutoPlay = function() {
        if (autoInterval) {
            clearInterval(autoInterval);
        }
    };
    /**
     * @private
     * 根据图片宽度和高度重设容器的大小
     *@param {Number} width 图片真实宽度
     *@param {Number} height 图片真实高度
     */
    function _resizeContainer(width, height) {
        var vWidth, vHeight;
        if (width > opts.maxWidth) {
            vWidth = opts.maxWidth;
            vHeight = (opts.maxWidth / width) * height;
        } else {
            vWidth = width;
            vHeight = height;
        }
        if (vHeight > opts.maxHeight) {
            vHeight = opts.maxHeight;
            vWidth = (opts.maxHeight / height) * width;
        }
        //若前后两张图片的大小一样，则不执行动画
        $(".giant-ui-slideShow .imageContainer .hoverNav").hide();
        if (parseInt(vWidth) != $(".giant-ui-slideShow .slideShowImage").width() || parseInt(vHeight) != $(".giant-ui-slideShow .slideShowImage").height()) {
            $(".giant-ui-slideShow .slideShowImage").animate({
                width: vWidth + "px",
                height: vHeight + "px"
            },opts.pictureShowSpeed,function() {
                //图片
                $(".giant-ui-slideShow .imageContainer .hoverNav").width($(this).width()).height($(this).height());
                $(".giant-ui-slideShow .imageContainer .hoverNav span").css({"width":$(this).width() / 2+"px","height":$(this).height()+"px"});
                $(".giant-ui-slideShow .imageContainer .hoverNav").show();
            });
            $(".giant-ui-slideShow").animate({
                left: (_getPageSize()[0] - vWidth) / 2 + "px"
            },
            opts.pictureShowSpeed);
        }
        else{
            $(".giant-ui-slideShow .imageContainer .hoverNav").show();
        }
    }
    /**
     * @private
     *按钮和键盘事件绑定
     */
    function _eventBind() {
        $(".giant-ui-slideShow .buttonContainer .next,.giant-ui-slideShow .imageContainer .nextLink").bind("click",function() {
            //停止自动播放
            opts.autoPlay = false;
            currentPicture.stopAutoPlay();
            currentPicture = currentPicture.getNext();
            currentPicture.show();

        });
        $(".giant-ui-slideShow .buttonContainer .prev,.giant-ui-slideShow .imageContainer .prevLink").bind("click",function() {
            //停止自动播放
            opts.autoPlay = false;
            currentPicture.stopAutoPlay();
            currentPicture = currentPicture.getPrev();
            currentPicture.show();
        });
        $(".giant-ui-slideShow .buttonContainer .play").bind("click",function() {
            if (opts.autoPlay) {
                opts.autoPlay = false;
                $(this).attr("class","play_hover");
                currentPicture.stopAutoPlay();
            } else {
                opts.autoPlay = true;
                $(this).attr("class","pause_hover");
                currentPicture.autoPlay();
            }
        });
         $(".giant-ui-slideShow .buttonContainer .last").bind("click",function(){
             //停止自动播放
            opts.autoPlay = false;
            currentPicture.stopAutoPlay();
            currentPicture = currentPicture.getLast();
            currentPicture.show();
         });
         $(".giant-ui-slideShow .buttonContainer .first").bind("click",function(){
             //停止自动播放
            opts.autoPlay = false;
            currentPicture.stopAutoPlay();
            currentPicture = currentPicture.getFirst();
            currentPicture.show();
         });
        $(".giant-ui-slideShow .buttonContainer span").hover(
            function(){
                $(this).attr("class",$(this).attr("class")+"_hover");
            },
            function(){
                $(this).attr("class",$(this).attr("class").replace("_hover",""));
            }
        );
        $(".giant-ui-slideShow .imageContainer .close").bind("click",function() {
            _stopAll();
        });
        //延迟一秒为overlay绑定点击事件，以防止误操作。
        setTimeout(function(){
            $(".giant-ui-slideShowOverlay").bind("click",function(){
             _stopAll();
        });
        },1000);
    
        //键盘事件
        $(document).bind("keyup",function(event) {
            switch (event.keyCode) {
            case opts.nextKeyCode:
                $(".giant-ui-slideShow .buttonContainer .next").trigger("click");
                break;
            case opts.prevKeyCode:
                $(".giant-ui-slideShow .buttonContainer .prev").trigger("click");
                break;
            case opts.closeKeyCode:
                _stopAll();
            }
        });
        //滚轮事件
        /*
        var mousewheel =document.all?"mousewheel":"DOMMouseScroll";  
        $(".giant-ui-slideShow").bind(mousewheel,function(event){
            var zoom =0;
            if (event.wheelDelta) {
                zoom = event.wheelDelta > 0 ? 0.95:1.05;
            } else if (event.detail) {
                zoom = event.detail > 0 ? 1.1 : 0.9;
            }
            $(".giant-ui-slideShow .slideShowImage").width($(".giant-ui-slideShow .slideShowImage").width()*zoom),$(".giant-ui-slideShow .slideShowImage").height($(".giant-ui-slideShow .slideShowImage").height()*zoom);
        });  
        */
        
        
    }
    /**
     *@private
     *私有方法，停止图片幻灯。
     */
    function _stopAll() {
        //注销键盘事件
        $(window).unbind("keypress");
        $('.giant-ui-slideShowOverlay').remove();
        $('.giant-ui-slideShow').fadeOut(function() {
            $('.giant-ui-slideShow').remove();
        });
         currentPicture.stopAutoPlay();
    }
    /**
     *@private
     *私有方法，获取当前文档的高度和宽度 
     */
    function _getPageSize() {
        var xSize, ySize;
        ySize = Math.max($(window).height(), $("body").outerHeight(true));
        xSize = Math.max($(window).width(), $("body").outerWidth(true));
        return [xSize,ySize];
    }
    /**
     * 默认参数
     * @overlayOpcity 背景遮罩层的不透明读，1为不透明，0为全透明，默认为0.8
     * @topPix  幻灯与窗口顶部的距离，默认为50，单位为像素
     * @startIndex 从第几张图片开始播放幻灯片，默认为0，即第一张图片开始
     * @maxWidth 图片展示的最大宽度，若宽于这个宽度，这会等比例缩小，默认值为800 单位为像素
     * @maxHeight 图片展示的最大宽度，若宽于这个宽度，这会等比例缩小，默认值为500 单位为像素
     * @pictureShowSpeed 图片变形展示的时间长度，默认为500，单位为毫秒
     * @autoPlaySpeed 自动播放图片是，图片轮换速度，默认为3000，单位为毫秒
     * @autoPlay 是否默认自动播放，默认为false
     * @nextKeyCode 控制下一张图片的keyCode,默认为78，即n键
     * @prevKeyCode 控制下一张图片的keyCode,默认为80，即p键
     * @closeKeyCode 关闭图片幻灯的快捷键，默认为27，即esc键
     * @defaultImage 在图片出错时的默认图片，默认为"images/error.gif"
     */
    $.fn.slideShow.defaults = {
        overlayOpcity: 0.8,
        topPix: 50,
        startIndex: 0,
        maxWidth: 1000,
        maxHeight: 1000,
        pictureShowSpeed: 500,
        autoPlaySpeed: 3000,
        autoPlay: false,
        nextKeyCode: 78,
        prevKeyCode: 80,
        closeKeyCode: 27,
        defaultImage: "include/slides/images/error.gif",
        dataType: "json",
        data: null,
        overlayTemp:"<div class=\"giant-ui-slideShowOverlay\"><iframe frameborder=\"0\" src=\"include/slides/images/overlay.html\" \/></div>",
        domTemp: "<div class=\"giant-ui-slideShow\">"  + "<div class=\"imageContainer\">" + "<img class=\"slideShowImage\">" + "<div class=\"hoverNav\">" + "<span title=\"Prev\"  class=\"prevLink\"></span>" + "<span title=\"Next\" class=\"nextLink\"></span>" + "</div>" + "<div class=\"loading\">" + "<img src=\"include/slides/images/loading.gif\">" + "</div>" + "</div>" + "<div class=\"imageDataContainer\">" + "<h3 style=\"height: 15px;\"></h3>" + "<span class=\"numberDisplay\"></span>" + "<div class=\"remark\"></div>" + "</div>" + "<div class=\"buttonContainer\">" + "<span title=\"First\" class=\"first\"></span><span title=\"Prev\" class=\"prev\"></span><span class=\"play\"></span><span title=\"Next\" class=\"next\"></span><span title=\"Last\" class=\"last\"></span>" + "</div></div>"
    };
})(jQuery);