/**
 * jQuery.adGallery
 * @extends jquery.1.6.2
 * @author: afei
 * @email clover.org@gmail.com
 * @site www.clovery.org
 * @version 0.1
 * @date 2011-07-20
 * 
 * jQuery('elem').adGallery()
 *
 */
;(function($) {
    var defaults = {  /** 默认参数 */
        startIndex          : 0,               // 默认从第一张图片开始
        autoPlay            : true,              // 自动播放
        duration            : 5000,              // 5秒切换一次
        animateTime         : 300,
        direction           : "top",            // 默认垂直，可用left
        event               : "mouseover",          // 切换触发事件 
        sheet               : 'img',                // 幻灯片外层元素
        thumb               : 'span',               // 触发器外层元素
        thumbNav            : false,             // 是否显示数字切换按钮
        adNav               : false,                // 是否显示前一张、后一张按钮
        sheetWrap           : '.ad-sheet-wrap', // 幻灯片容器 
        thumbWrap           : '.ad-thumb-wrap', // 触发器容器
        sheetCon            : '.ad-sheet-con',   // 幻灯片包裹层
        activeThumbClass    : 'selected',
        activeSheetClass    : 'ad-active',
        onStart             : function() {},
        onComplete          : function() {},
        lazyLoadImg         : false,        
        lazyClass           : '.lazy-img',
        fade                : false
    };
    
    $.adGallery = function(adGalleryCon, options) {
        adGalleryCon = $(adGalleryCon);
        if (adGalleryCon.length === 0) return;
        var that = this 
            , settings = $.extend({}, defaults, options || {})
            , adCon = adGalleryCon
            , sheetWrap = $(settings.sheetWrap, adCon)
            , thumbWrap = $(settings.thumbWrap, adCon);
        
        this.adCon = adCon;
        this.sheetWrap = sheetWrap;
        this.thumbWrap = thumbWrap;
        this.sheetCon = $(settings.sheetCon, sheetWrap);
        this.sheetData = $(settings.sheet, this.sheetCon);
        this.sheetWidth = 0;
        this.sheetHeight = 0;
        this.thumbData = [];
            
        this.settings = settings; 
               
        this.initialize();    
               
        return this;        
    };
    
    
    $.fn.adGallery = function(options) {
        return this.each(function() {
            $(this).data('adGallery', new $.adGallery(this, options));
        });
    }
    

    $.adGallery.fn = $.adGallery.prototype = {
        version: '0.1.0',
        
        initialize: function() {
            var settings = this.settings
                , sheetData = this.sheetData
                , sheetCount = sheetData.length;
            
            this.dir = settings.direction;
            this.curIndex = settings.startIndex > sheetCount ? sheetCount - 1 : settings.startIndex;
            this.oldIndex = 0;
            this.timer = null;
            
            this.initSheet();
            
            this.bindHover(this.sheetWrap);

            if (settings['thumbNav'] || this.thumbWrap.length) this.initThumb();
            
            if (settings['adNav']) this.createAdNav();        
                    
            if (settings['autoPlay']) this.autoPlay();          
        },        
        
        /**
         * 初始化幻灯片容器
         */
        initSheet: function() {
            var settings = this.settings
                , sheetWrap = this.sheetWrap 
                , sheetCon = this.sheetCon
                , sheet = $(this.sheetData[0])
                , sheetWidth = sheet.width() || sheetWrap.width() || settings.sheetWidth
                , sheetHeight = sheet.height() || sheetWrap.height() || settings.sheetHeight
                , wrapWidth = sheetWidth - 
                    (parseInt(sheetWrap.css('padding-left') || 0) + parseInt(sheetWrap.css('padding-right') || 0) 
                    + parseInt(sheetWrap.css('border-left') || 0) + parseInt(sheetWrap.css('border-right') || 0));

            if (settings.fade) {
                sheetWrap.css({"position": "relative", "overflow": "hidden", "width": wrapWidth + "px", "height": sheetHeight + "px"});
                $(settings.sheet, sheetCon).css({
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    display: 'none'
                });
            } else {
                sheetWrap.css({
                    'position': 'relative'
                    , 'overflow': 'hidden'
                    , 'width': wrapWidth + 'px'
                    , 'height': sheetHeight + 'px'
                });
                
                sheetCon.css({"position": "absolute"}); 
                
                $(settings.sheet, sheetCon).css({"width": sheetWidth + "px", "height": sheetHeight + "px", "overflow": "hidden"});
                
                if ('left' === this.dir) {
                    sheetCon.css({"width": (sheetWidth * this.sheetData.length) + 'px', "left": (- this.curIndex * sheetWidth) + 'px'});
                    $(settings.sheet, sheetCon).css({"float": "left"});
                } else {
                    sheetCon.css('top', (- this.curIndex * sheetHeight) + 'px');
                }
            }

            this.sheetWidth = sheetWidth;
            this.sheetHeight = sheetHeight;
            
            settings['lazyLoadImg'] ? this._loadActiveImg() : '';
            
            $(this.sheetData[this.curIndex]).css('display', 'block').addClass('ad-active');       
        },
        
        /**
         * 初始化触发器
         */
        initThumb: function() {
            var thumbWrap = this.thumbWrap
                , settings = this.settings;
                
            if (1 === thumbWrap.length) {
                var thumbs = $(settings.thumb, thumbWrap);          
                this.bindThumbEvent(thumbs.length === 0 ? thumbWrap.children() : thumbs);          
            } else if (!!settings['thumbNav']) {
                this.createThumbNav();
            }
            
            $(this.thumbData[this.curIndex]).addClass(settings.activeThumbClass);
        },    
        
        /**
         * 创建数字触发器切换导航
         */
        createThumbNav: function() {
            var that = this
                , thumbTpl = $('<span></span>')
                , thumbData = []
                , tmpDiv = $('<div class="ad-thumb-con"></div>')
                , thumbWrap = $('<div class="' + this.settings['thumbWrap'].replace('.', '') + '"></div>');
            
            for (var i = 0, len = this.sheetData.length; i < len; i++) {
                var thumb = thumbTpl.clone();
                thumb.text(i + 1);
                tmpDiv.append(thumb);
                thumbData.push(thumb);
            }
            thumbWrap.append(tmpDiv);
            
            this.thumbWrap = thumbWrap;            
            this.adCon.append(thumbWrap);
            this.bindThumbEvent(thumbData);            
        },
        
        autoPlay: function() {
            var that = this;
            this.timer = setInterval(function() { that.next(); }, this.settings.duration);
        },
        
        stopPlay: function() {
            clearInterval(this.timer);
            this.timer = null;
        },               
        
        /**
         * 绑定数字触发器切换事件
         */
        bindThumbEvent: function(thumbData) {
            var that = this;
            
            $.each(thumbData, function(i, o) {
                var obj = $(o);
                that.thumbData.push(obj);
 
                obj.bind(that.settings.event, function() {   
                    that.stopPlay();
                    that.select(i);  
                    return false;
                });
            });  
            
            this.bindHover(this.thumbWrap);
        },
        
        bindHover: function(obj) {
            var that = this; 
            
            if (!this.settings.autoPlay) return;

            $(obj).mouseover(function() {
                that.stopPlay();
            }).mouseout(function() {
                that.autoPlay();
            });
        },
        
        /**
         * 切换指定索引的图片
         */
        select: function(index) {
            var that = this
                , settings = this.settings
                , curSheet = this.sheetData[index]
                , oldSheet = this.sheetData[this.curIndex]
                , animateFirstArg
                , callback = function() {
                    if (settings.lazyLoadImg) {
                        this._loadActiveImg(curSheet);
                    }
                    if (settings.onComplete) { settings.onComplete(curSheet); }
                    $(oldSheet).removeClass('ad-active');
                };   
                
                
            if (this.thumbData.length) this.selectedThumb(index);
                        
            // executive callback function if trigger trigger
            if (settings.onStart) settings.onStart(that, curSheet);                       
            
            $(curSheet).addClass('ad-active');            
            
            if (this.settings.fade) {
                $(oldSheet).removeClass('ad-active').fadeOut();
                $(curSheet).fadeIn();
            } else {                
                if ('top' === this.dir) {
                    animateFirstArg = {
                        top     : -index * this.sheetHeight + 'px'
                    };
                } else if ('left' === this.dir) {
                    animateFirstArg = {
                        left    : -index * this.sheetWidth + 'px'
                    };
                }
            }           
            
            this.sheetCon.stop().animate(
                animateFirstArg
                , settings.animateTime
                , function() { callback.call(that); }
            );              
            that.curIndex = index; 
        },             
        
        /**
         * 设置当前thumb
         */
        selectedThumb: function(index) {
            var thumbData = this.thumbData;
                        
            this.oldIndex = this.curIndex;
                       
            thumbData[this.oldIndex].removeClass(this.settings.activeThumbClass);
            thumbData[index].addClass(this.settings.activeThumbClass);
        },
        
        /**
         * 上一张
         */
        prev: function() {
            var num = this.curIndex;
            num--;
            if (num < 0) {
                num = this.sheetData.length - 1;
            }
            this.select(num);     
        },
        
        /**
         * 下一张
         */
        next: function() {
            var num = this.curIndex;         
            num++;
            if (num >= this.sheetData.length) {
                num = 0;
            }
     
            this.select(num);
        },        
        
        /**
         * 创建导航
         */
        createAdNav: function() {
            var that = this,
                adPrev = $('.ad-nav-pre', this.adCon).length == 1 ? $('.ad-nav-pre', this.adCon) : $('<div class="ad-nav-pre">Prev</div>'),
                adNext = $('.ad-nav-next', this.adCon).length == 1 ? $('.ad-nav-next', this.adCon) : $('<div class="ad-nav-next">Next</div>');

            adPrev.click(function() {
                that.stopPlay();
                that.prev();
            });       
            
            adNext.click(function() {
                that.stopPlay();
                that.next();
            });
            
            if (!$('.ad-nav-pre', this.adCon).length == 1 && !$('.ad-nav-next', this.adCon).length == 1) this.adCon.append(adPrev, adNext);            
        },
        
        /**
         *
         */
        lazyLoadImg : function(container) {            
            var con = container && $(container) || $(this.sheetData[this.curIndex])
                , num = 0
                , elems = $(this.settings.lazyClass, con)
            
            if (0 === elems.length || con.hasClass(this.settings.lazyClass)) {
                elems = $('img[data-src]', con);
            }
            
            if ( 0 === elems.length || con.hasClass( 'ad-img-loaded' ) ) { 
                this.sheetWrap.removeClass('loading'); 
                return;
            }
            
            
            elems.each(function(i, v) {
                var obj = $(v);
                
                if (!obj.hasClass('completed')) {                    
                    obj
                      .attr('src', obj.attr('data-src'))                      
                      .bind('load', function() {
                        obj
                          .addClass('completed')
                          .hide()
                          .fadeIn()                  
                          .removeAttr('data-src');
                        num += 1;
                        if (num === elems.length) con.addClass('ad-img-loaded');
                      });
                }                
            });            
            
        },
        
        _loadActiveImg: function(curSheet) {
            curSheet = curSheet || this.sheetData[this.curIndex];
            var activeArea = $('.ad-active', $(curSheet));
            if (activeArea.length !== 0) {
                this.lazyLoadImg(activeArea);
            } else {
                this.lazyLoadImg(curSheet);
            }        
        
        }    
        
    };            

})(jQuery);
