(function($) {
    var win = window;
    function ScrollTo(opts) {
        this.opts = $.extend({}, ScrollTo.DEFAULATS, opts);
        this.$el = $("html, body");
    }
    ScrollTo.DEFAULATS = {
        dest: 0,
        speed: 800
    };
    ScrollTo.prototype.move = function() {
        var opts = this.opts,
            dest = opts.dest;
        if ($(win).scrollTop() !== dest) {
            if (!this.$el.is(":animated")) {
                this.$el.animate({
                    scrollTop: dest
                }, opts.speed);
            }
        }
    };
    ScrollTo.prototype.go = function() {
        var dest = this.opts.dest;
        if ($(win).scrollTop() !== dest) {
            this.$el.scrollTop(dest);
        }
    };
    function BackTop(el, opts) {
        this.opts = $.extend({}, BackTop.DEFAULTS, opts);
        this.$el = $(el);
        this.scroll = new ScrollTo({
            dest: 0,
            speed: this.opts.dest
        });
        if (this.opts.mode === "move") {
            this.$el.on("click", $.proxy(this._move, this));
        } else {
            this.$el.on("click", $.proxy(this._go, this));
        }
        $(win).on("scroll.backtop", $.proxy(this._checkPosition, this)).trigger("scroll.backtop");
    }
    BackTop.DEFAULTS = {
        mode: "move",
        pos: $(win).height()
    };
    BackTop.prototype._move = function() {
        this.scroll.move();
    };
    BackTop.prototype._go = function() {
        this.scroll.go();
    };
    BackTop.prototype._checkPosition = function() {
        var $el = this.$el;
        if ($(win).scrollTop() > this.opts.pos) {
            $el.fadeIn();
        } else {
            $el.fadeOut();
        }
    };
    $.fn.backtop = function(opts) {
        return this.each(function() {
            new BackTop(this, opts);
        });
    };
    $.fn.lazyload = function(opts) {
        var defaults = {
            event: "scroll",
            attr: "data-src",
            container: win,
            callback: $.noop
        };
        var params = $.extend({}, defaults, opts);
        var container = $(params.container);
        params.cache = [];
        $(this).each(function() {
            var node = this.nodeName.toLowerCase(),
                url = $(this).attr(params["attr"]);
            var data = {
                obj: $(this),
                tag: node,
                url: url
            };
            params.cache.push(data);
        });
        var callback = function(call) {
            if ($.isFunction(params.callback)) {
                params.callback.call(call);
            }
        };
        var loading = function() {
            var contHeight = container.outerHeight();
            var contWidth = container.outerWidth();
            var contopm, conleft;
            if (container.get(0) === win) {
                contop = $(win).scrollTop();
                conleft = $(win).scrollLeft();
            } else {
                contop = container.offset().top;
                conleft = container.offset().left;
            }
            $.each(params.cache, function(i, data) {
                var o = data.obj,
                    tag = data.tag,
                    url = data.url,
                    post, posb, posl, posr;
                if (o) {
                    post = o.offset().top - (contop + contHeight);
                    posb = o.offset().top + o.height() - contop;
                    posl = o.offset().left - (conleft + contWidth);
                    posr = o.offset().left + o.width() - conleft;
                    if ((post < 0 && posb > 0) && (posl < 0 && posr > 0)) {
                        if (url) {
                            if (tag === "img") {
                                callback(o.attr("src", url));
                            } else {
                                callback(o.css("background-image", "url(" + url + ")"));
                            }
                        } else {
                            callback(o);
                        }
                        data.obj = null;
                    }
                }
            });
        };
        loading();
        container.bind("scroll.loadingimg", loading);
    };
    $.fn.tabs = function(options) {
        $.fn.tabs.defaults = {
            eventName: "hover",
            className: "active",
            effect: "fade",
            auto: false,
            time: 1000,
            delayTime: 1000,
            startFun: null,
            endFun: null,
            easing: "linear",
            prev: null,
            next: null,
            iNow: 0
        };
        var params = $.extend({}, $.fn.tabs.defaults, options),
            _this = this;
        return this.each(function() {
            var effect = params.effect;
            var target = $(this);
            var navs = target.find(".nav li");
            var contents = target.find(".content");
            var iBefore = 0,
                iNow = parseInt(params.iNow),
                contentsLen = contents.length,
                timer = null;
            if( effect == "leftMarquee" ){
                for(var i=0; i<contentsLen; i++){
                    target.append( contents.eq(i).clone() );
                }
                contents = target.find(".content");
            }
            contentsLen = contents.length - 1;
            var targetTop = target.offset().top;
            var targetBottom = target.offset().top + target.height();
            var eventName = params.eventName;
            var delayTime = parseInt(params.delayTime);
            var interTime = parseInt(params.interTime);
            var easing = params.easing;
            var autoPlay = params.autoPlay;
            var className = params.className;
            var prevBtn = $(params.prev);
            var nextBtn = $(params.next);
            var offsetWidth = contents.eq(0).outerWidth();
            var doStartFun = function() { if ($.isFunction(params.startFun)) { params.startFun(iNow, contents.eq(iNow)); } iBefore = iNow; };
            var doEndFun = function() { if ($.isFunction(params.endFun)) { params.endFun(iBefore, contents.eq(iBefore)); } };
            var reset = function(){ contents.eq(iNow).addClass(className).siblings(".contents").removeClass(className); navs.eq(iNow).addClass(className).siblings().removeClass(className); };
            var doPlay = function(init) {
                if( !init ){
                    doEndFun();
                }
                switch(effect){
                    case "fade":
                        contents.stop(true,true).eq(iNow).animate({
                            opacity:"show"
                        }, delayTime, easing, function(){
                            doStartFun();
                        }).siblings(".content").hide();
                        break;
                    case "left":
                        target.stop(true,true).animate({
                            left: -iNow * offsetWidth - (iNow + 1) * 25
                        }, delayTime);
                        break;
                    case "leftMarquee":
                        var calcLeft = function(num){ return  -num * offsetWidth - (num + 1) * 25; };
                        if( iNow == 0 ){
                            target.css("left", calcLeft(4));
                            iNow = 3;
                        }
                        target.stop(true, true).animate({
                            left: calcLeft(iNow)
                        }, delayTime, easing, function(){
                            if( iNow == 1 ){
                                iNow = contentsLen - 1;
                                target.css({ left: calcLeft(iNow) });
                            }else if( iNow == contentsLen - 1 ){
                                iNow = 1;
                                target.css({ left: calcLeft(iNow) });
                            }
                            target.allow = false;
                        });
                        break;
                    case "custom":
                        contents.stop(true,true).eq(iNow).animate({
                            opacity:"show"
                        }, delayTime, easing, function(){
                            doStartFun();
                        }).siblings(".content").stop(true,true).animate({opacity:"hide"},delayTime,easing);
                        break;
                }
                reset();
            };
            doPlay(true);
            var play = function(){
                clearInterval(timer);
                timer = setInterval(function() {
                    if (iNow >= contentsLen) {
                        iNow = 0;
                    } else {
                        iNow++;
                    }
                    doPlay();
                }, interTime);
            };
            if( eventName == 'hover' ){
                navs.hover(function(){
                    clearInterval(timer);
                    iNow = $(this).index();
                    if (iBefore === iNow) return;
                    doPlay();
                }, function(){
                    if (params.auto) {
                        play();
                    }
                });
                contents.hover(function() {
                    clearInterval(timer);
                    iNow = $(this).index();
                    if (iBefore === iNow) return;
                    doPlay();
                }, function() {
                    if (params.auto) {
                        play();
                    }
                });
            }else{
                navs.click(function(){
                    clearInterval(timer);
                    iNow = $(this).index();
                    if (iBefore === iNow) return;
                    doPlay();
                }).on("mouseover", function(){
                    if (params.auto) {
                        play();
                    }
                });
            }
            if( prevBtn.length && nextBtn.length ){
                prevBtn.on("click", function(){
                    if( !target.allow ){
                        target.allow = true;
                        clearInterval(timer);
                        iNow--;
                        if( iNow < 0 ){
                            iNow = contentsLen;
                        }
                        doPlay();
                    }
                });
                nextBtn.on("click", function(){
                    if( !target.allow ){
                        target.allow = true;
                        clearInterval(timer);
                        iNow++;
                        if( iNow > contentsLen){
                            iNow = 0;
                        }
                        doPlay();
                    }
                });
                target.hover(function(){
                    clearInterval(timer);
                }, function(){
                    if (params.auto) {
                        play();
                    }
                });
            }
            if (params.auto) {
                $(win).on("scroll", function(){
                    var height = $(this).height(),
                        scrollTop = $(this).scrollTop() + height;
                    if(targetTop > scrollTop || targetBottom + height < scrollTop){
                        clearInterval(timer);
                    }else{
                        play();
                    }
                }).trigger("scroll");
            }
        });
    };
    $.fn.fixed = function(opts){
        var defaults = {
            top: 0,
            left: 0
        };
        $.extend(defaults, opts);
        return this.each(function(){
            var $this = $(this),
                top = $this.offset().top,
                fixedTop = defaults.top;
                fixedLeft = defaults.left;
            $(win).scroll(function(){
                var scrollTop = $(this).scrollTop();
                if( top - scrollTop <= fixedTop ){
                    $this.css({
                        position: "relative",
                        top: scrollTop - top + fixedTop,
                    });
                }else{
                    $this.css({
                        position: "static"
                    });
                }
            });
        });
    };
    $["template"] = function(tmpl, data) {
        return (template(tmpl, data));
    };
    $["tmpl"] = function(tmpl, data) {
        return $(template(tmpl, data));
    };
    var template = function(str, data) {
        if (!data)
            data = {};
        return tmpl(str, data);
    };
    (function() {
        var cache = {};
        this.tmpl = function tmpl(str, data) {
            var fn = !/\W/.test(str) ?
            cache[str] = cache[str] ||
            tmpl(document.getElementById(str).innerHTML)
            :
            new Function("obj",
                "var p=[],print=function(){ p.push.apply(p,arguments);};" +
                "with(obj){p.push('" + str.replace(/[\r\t\n]/g, " ")
                    .replace(/'(?=[^%]*%>)/g, "\t")
                    .split("'").join("\\'")
                    .split("\t").join("'").replace(/<%=(.+?)%>/g, "',$1,'")
                    .split("<%").join("');")
                    .split("%>").join("p.push('") + "');}return p.join('');");
            return data ? fn(data) : fn;
        };
    })();
})(jQuery);
var imgReady = (function() {
    var list = [],
        timer = null;
    var queue = function() {
        for (var i = 0; i < list.length; i++) {
            list[i].end ? list.splice(i--, 1) : list[i]();
        }!list.length && stop();
    };
    var stop = function() {
        clearInterval(timer);
        timer = null;
    };
    return function(url, ready, error) {
        var onready = {},
            width,
            height,
            newWidth,
            newHeight,
            img = new Image();
        img.src = url;
        if (img.complete) {
            ready.call(img);
            return;
        }
        width = img.width;
        height = img.height;
        img.onerror = function() {
            error && error.call(img);
            onready.end = true;
            img = img.onload = img.onerror = null;
        }
        var onready = function() {
            newWidth = img.width;
            newHeight = img.height;
            if (newWidth !== width || newHeight !== height ||
                newWidth * newHeight > 1024
            ) {
                ready.call(img);
                onready.end = true;
            };
        }
        onready();
        img.onload = function() {
            !onready.end && onready();
            img = img.onload = img.onerror = null;
        };
        if (!onready.end) {
            list.push(onready);
            if (timer === null) {
                timer = setInterval(queue, 40);
            };
        }
    }
})();
