﻿/*
* you-may jQuery advertisement Plugin
* version: 1.0 (08-APR-2009)
* @requires jQuery v1.3.2 or later
* 
*/

; (function($) {

    //跟随浮动    
    $.fn.followScroll = function(options) {
        var followScroll = this;

        options = $.extend({
            target: window,
            animate: false,
            scrollAnimateDuration: 800
        }, options || {});

        //初始偏移
        var iOffset = followScroll.offset();
        var oScrollTop = $(document).scrollTop();

        $(options.target).scroll(function() {

            //当前偏移
            var cOffset = followScroll.offset();

            var scrollTopOffset = $(document).scrollTop() - oScrollTop;

            //最终上方偏移=（初始偏移高度+滚动的高度）
            var finalTop = cOffset.top + scrollTopOffset;
            oScrollTop = $(document).scrollTop();

            if (options.animate && options.scrollAnimateDuration) {

                followScroll.animate({
                    top: finalTop
                }, {
                    duration: options.scrollAnimateDuration,
                    queue: false
                });

            } else {
                followScroll.css({ top: finalTop });
            }
        });
    }

    //弹出广告
    $.fn.popup = function(options) {

        var popup = this;

        options = $.extend({
            isDraggable: true,
            animate: true,
            hideAnimate: {
                opacity: 'hide'
            },
            hideAnimateOptions: {
                duration: 900
            },
            showAnimate: {
                opacity: 'show'
            },
            showAnimateOptions: {
                duration: 900
            },
            popupInitializeCss: {
                "position": "absolute",
                "display": "none",
                "z-index": "999",
                top: $(window).height() - popup.outerHeight() + $(document).scrollTop(),
                left: $(window).width() - popup.outerWidth() + $(document).scrollLeft()
            }, draggableOptions: {
                containment: "document",
                axis: 'x'
            }

        }, options || {});

        popup.css(options.popupInitializeCss);

        $(window).resize(function() {
            popup.css({
                left: $(window).width() - popup.outerWidth() + $(document).scrollLeft(),
                top: $(window).height() - popup.outerHeight() + $(document).scrollTop()
            });
        });

        if (options.isDraggable)
            popup.draggable(options.draggableOptions);

        if (options.animate && options.showAnimate) {
            popup.animate(options.showAnimate, options.showAnimateOptions);
        } else {
            popup.show();
        }

        popup.followScroll(options.followScrollOptions);
    }

    //循环碰撞广告
    $.fn.round = function(options) {
        var round = this;

        options = $.extend({
            box: window,
            isDraggable: false,
            roundDuration: 3000,
            moveDuration: 50,
            roundInitializeCss: {
                "position": "absolute",
                "z-index": "998"
            },
            followScrollOptions: {
                animate: false
            },
            draggableOptions: {
                containment: "document",
                axis: 'y'
            }

        }, options || {});

        round.css(options.roundInitializeCss);

        if (options.isDraggable)
            round.draggable(options.draggableOptions);

        var box = $(options.box);

        round.css({
            left: $(document).scrollLeft(),
            top: $(document).scrollTop()
        });

        var maxHorizontal = box.width() - round.outerWidth();

        var maxVertical = box.height() - round.outerHeight();

        $(window).resize(function() {
            maxHorizontal = box.width() - round.outerWidth();
            maxVertical = box.height() - round.outerHeight();
        });

        var vDirection = true;
        var hDirection = true;

        var intervalId = null;

        var intervalMove = function() {

            intervalId = setInterval(function() {
                //当前偏移
                var cOffset = round.offset();

                var sTop = $(document).scrollTop();
                var sLeft = $(document).scrollLeft();

                //最终左偏移
                var finalLeft = cOffset.left;
                if (cOffset.left >= maxHorizontal + sLeft) {
                    hDirection = false;
                } else if (cOffset.left <= sLeft) {
                    hDirection = true;
                }
                if (hDirection) finalLeft++; else finalLeft--;

                //最终右偏移
                var finalTop = cOffset.top;
                if (cOffset.top >= maxVertical + sTop) {
                    vDirection = false;
                } else if (cOffset.top <= sTop) {
                    vDirection = true;
                }
                if (vDirection) finalTop++; else finalTop--;

                round.css({
                    left: finalLeft,
                    top: finalTop
                });

            }, options.moveDuration);
        }

        intervalMove();

        round.mouseover(function() {
            clearInterval(intervalId);
        });

        round.mouseout(function() {
            intervalMove();
        });

        round.followScroll(options.followScrollOptions);
    }

    //监狱栏广告
    $.fn.prison = function(options) {

        var prison = this;

        //初始化
        initPrison(prison, options);

        var triggers = this.find(".prison-lattice");
        var images = this.find(".prison-image");
        var firstImage = images.eq(0);
        var currentIntervalId;
        //切换方向，true为往右
        var direction = true;

        var index = 0;
        var count = images.size();

        //获取当前显示图片，默认为第一张
        var getCurrent = function() {
            return images.eq(index);
        };

        //获取下一张要显示的图片
        var getNextImage = function(current) {
            return images.eq(direction ? index + 1 : index - 1);
        };

        var cutoverImage = function(target) {
            getCurrent().hide();
            target.show();

            index = images.index(target.get(0));
            if ((direction === false && index == 0) ||
                (direction === true && index == count - 1))
                direction = !direction;
        };

        //定时切换图片方法
        var intervalCutover = function() {
            var intervalId = setInterval(function() {
                cutoverImage(getNextImage());
            }, options.cutoverDelay);

            currentIntervalId = intervalId;
        };

        var getImageByTrigger = function(trigger) {
            return $(trigger).prev();
        };

        intervalCutover();

        images.mouseover(function() {
            var self = $(this);

            clearInterval(currentIntervalId);

            cutoverImage(self);

            return false;
        });

        images.mouseout(function() {
            intervalCutover();
        });

        triggers.mouseover(function() {
            var self = $(this);

            clearInterval(currentIntervalId);

            cutoverImage(getImageByTrigger(self));

            return false;
        });

        triggers.mouseout(function() {
            intervalCutover();
        });
    };

    //初始化监狱广告插件参数
    function initPrison(self, options) {
        options = $.extend({
            cutoverDelay: 2000,
            latticeColors: ["#FE8E0A", "#CE8E0A", "#AE8E0A",
                 "#BE8E0A", "#EE8E0A", "#1E8E0A", "#2E8E0A",
                 "#3E8E0A", "#4E8E0A", "#5E8E0A", "#6E8E0A",
                 "#7E8E0A"]
        }, options || {});

        var lattices = self.find(".prison-lattice");
        lattices.each(function(index) {

            var color = options.latticeColors[
                    index % options.latticeColors.length];
            $(this).css("background-color", color);
        });

        var images = self.find(".prison-image");
        images.not(":first").hide();
    }

    //滚动广告
    $.fn.roll = function(options) {

        var roll = this;

        options = $.extend({
            delay: 3000,
            animateDuration: 1000,
            rollCount: 1,
            rollItem: ".roll-item"
        }, options || {});

        var animateDuration = options.animateDuration;
        var delay = options.delay;
        var rollCount = options.rollCount;
        var displayCount = options.displayCount;

        var rollItems = roll.find(options.rollItem);

        var getBlockHeight = function(index) {
            var temp = 0;
            var addSelfHeight = function() {
                temp += $(this).height();
            }

            if (index == null) {
                rollItems.each(addSelfHeight);
            } else {
                rollItems.slice(0, index).each(addSelfHeight);
            }
            return temp;
        }

        var blockHeight = getBlockHeight();

        //如果内容高度少于块的高度则不需要滚动
        if (blockHeight <= roll.innerHeight()) {
            var whiteHeight = roll.innerHeight() - blockHeight;
            
            roll.append("<ul class='roll-item' style='height:" + whiteHeight + "px'></ul>");

            rollItems = roll.find(options.rollItem);
        }

        //克隆一份 实现循环滚动效果
        roll.append(rollItems.clone());

        var currentIndex = 0;

        var rollInterval = function() {

            if (currentIndex == rollItems.size()) {
                currentIndex = 0;
                roll.scrollTop(0);
            }

            var nextIndex = currentIndex + 1;

            roll.animate({
                scrollTop: getBlockHeight(nextIndex * rollCount)
            }, animateDuration);

            currentIndex++;
        }

        var intervalId = setInterval(rollInterval, delay);

        roll.mouseover(function() {
            clearInterval(intervalId);
        });

        roll.mouseout(function() {
            intervalId = setInterval(rollInterval, delay);
        });
    };


})(jQuery);
