﻿/*!  Douglass.cn | (c) 2011, 2020 BC network technology co., LTD | QQ: 156890583  
*/
var Slide_zhy = function (ele, opt) {
    this.$element = ele,
        this.piclist = [],
        this.defaults = {
            minwidth: 800,
            autoheight: true,
            bg_show: false,
            Timer: null,
            window_w: $(window).width(),
            loading: false,
            slider_w: null,
            slider_h: null,
            arrow: false,			//是否有箭头
            arrowshow: true,
            arrow_left: "._slider_prev",
            arrow_right: "._slider_next",
            activeindex: 0,
            last_index: 0,
            animate: false,
            fullscreen: false,  	 	//全屏和非全屏
            fullscreen_min_w: 800,
            fullscreen_h: null,
            mainpic: '.mainpic',
            affect: 'scrollx', 		//效果  有scrollx|scrolly|fade|none
            speed: 1200, 			//动画速度
            space: 6000, 			//时间间隔
            auto: true, 			//自动滚动
            trigger: 'mouseover', 	//触发事件 注意用mouseover代替hover
            conbox: '.conbox', 		//内容容器id或class
            ctag: '.Slide_', 			//内容标签 默认为<a>
            switcher: '.switcher', 	//切换触发器id或class
            stag: 'a', 			//切换器标签 默认为a
            current: 'cur', 			//当前切换器样式名称
            rand: false, 			//是否随机指定默认幻灯图片
            $conbox: null,
            $contents: null,
            $switcher: null,
            $stag: null,
            resize: {},
            contentslen: 0,
			callback:function(){}

        }
    this.options = $.extend({}, this.defaults, opt)
   
    this.init();
};
Slide_zhy.prototype = {
    init: function () {
        var _this = this,
            minheight = _this.$element.css("min-height"),
            maxheight = _this.$element.css("max-height"),
            html = "";
        _this.options.$conbox = _this.$element.find(_this.options.conbox);
        _this.options.$contents = _this.$element.find(_this.options.ctag);
        _this.options.contentslen = _this.options.$contents.length;
        if (typeof minheight != "undefined") { _this.options.$contents.css({ "min-height": minheight }); }
        if (typeof maxheight != "undefined") { _this.options.$contents.css({ "max-height": maxheight }); }

        if (this.$element.find(this.options.switcher).length > 0) {


        } else {
            for (var i = 1; i <= _this.options.contentslen; i++) { i == 1 ? html += "<a href='javascript:;' class='cur'></a>" : html += "<a href='javascript:;'></a>"; }
            _this.options.$conbox.after('<div class="' + _this.options.switcher.replace(".", "") + '">' + html + '</div>')

        }

        _this.options.$switcher = _this.$element.find(_this.options.switcher)
        _this.options.$stag = _this.options.$switcher.find(_this.options.stag)

        this.$element.on(_this.options.trigger, _this.options.$stag.selector, function () {
            _this._pause();
            _this.options.activeindex = $(this).index();
            _this._slide();
            _this._continue()
        })


        this.$element.on("mouseenter", function () { _this._pause(); });
        this.$element.on("mouseleave", function () { _this._continue(); });

        _this.options.loading ? _this._loading() : "";
        _this.options.bg_show ? _this.bg_show() : "";
        //随机
        if (_this.options.rand) { _this.options.activeindex = Math.floor(Math.random() * _this.options.contentslen); _this._slide(); }
        if (_this.options.affect == 'fade' || _this.options.affect == 'fade_animate') {
            $.each(_this.options.$contents, function (k, v) {
                (k === 0) ? $(this).css({ 'position': 'absolute', 'z-index': 9 }) : $(this).css({ 'position': 'absolute', 'z-index': 1, 'opacity': 0 });
            });
        }
        if (_this.options.arrow) { _this._arrow(); }
        _this.options.animate ? _this.animate_star(_this.options.$contents.eq(0)) : false;
        _this.options.fullscreen ? _this._fullscreen() : _this._set_slider_wh();
        _this.options.auto ? _this.options.Timer = setInterval(function () { _this._slide() }, _this.options.space) : _this.options.Timer = null;
    },
    _loading: function () {
        var _this = this,
            imglist = [];
        _this.options.$contents.find(_this.options.mainpic).each(function (index, element) {
            imglist.push($(this).attr('src'))
        });
        if (imglist.length > 0) {
            _this._loadingpic(imglist, function (loading_oklist) { _this.options.$conbox.fadeIn(); })
        }

    },
    _loadingpic: function (urllist, callback) {
        var _this = this,
            piclist = [];
        $.each(urllist, function (index, val) {
            var img_url = val,
                imgobj = {},
                img = new Image();
            img.onload = function () {
                var imgwidth = img.width
                var imgheight = img.height
            };
            img.src = img_url;
            var check = function () {
                if (img.width > 0 || img.height > 0) {
                    clearInterval(set);
                    imgobj = {
                        imgurl: img_url,
                        imgbili: (img.height / img.width).toFixed(2),
                        imgwidth: img.width,
                        imgheight: img.height
                    }
                    piclist.push(imgobj)
                    _this.piclist = piclist;

                    if (piclist.length == urllist.length) {
                        return callback(piclist);
                    } else {
                        $(window).resize();
                        return callback(piclist);

                    }
                }
            };
            var set = setInterval(check, 100);
        })
    },
    animate_star: function (a) {
        this.clearanimate(a.parent());
        var b = a.find(".ani");
        for (i = 0; i < b.length; i++) {
            b[i].style.visibility = "visible"
            effect = b[i].attributes["animate-effect"] ? b[i].attributes["animate-effect"].value : ""
            if (effect.indexOf("|") != -1) {
                effect = effect.split("|")[0]
            }

            if (b[i].className.indexOf(effect) == -1) {
                b[i].className = b[i].className + " " + effect + " " + "animated"
            } else {
                b[i].className = b[i].className + "animated"
            }
            style = b[i].attributes["style"].value
            duration = b[i].attributes["animate-duration"] ? b[i].attributes["animate-duration"].value : ""

            if (duration.indexOf("|") != -1) {
                duration = duration.split("|")[0]
            }
            duration && (style = style + "animation-duration:" + duration + ";-webkit-animation-duration:" + duration + ";")
            delay = b[i].attributes["animate-delay"] ? b[i].attributes["animate-delay"].value : ""
            if (delay.indexOf("|") != -1) {
                delay = delay.split("|")[0]
            }

            delay && (style = style + "animation-delay:" + delay + ";-webkit-animation-delay:" + delay + ";")
            b[i].setAttribute("style", style)
        }

    },
    clearanimate: function (obj) {
        for (allBoxes = obj.find(".ani"), i = 0; i < allBoxes.length; i++) {
            allBoxes[i].attributes["animate-style-cache"] && allBoxes[i].setAttribute("style", allBoxes[i].attributes["animate-style-cache"].value)
            allBoxes[i].style.visibility = "hidden"
            allBoxes[i].className = allBoxes[i].className.replace("animated", " ")
            allBoxes[i].attributes["animate-effect"] && (effect = allBoxes[i].attributes["animate-effect"].value, effect.indexOf("|") == -1 ? false : effect = effect.split("|")[0], allBoxes[i].className = allBoxes[i].className.replace(effect, " "))
        }
    },
    _arrow: function () {
        var _this = this;
        _this.$element.append('<a href="javascript:;" class="' + _this.options.arrow_left.replace(".", "") + '"><span></span></a> <a href="javascript:;" class="' + _this.options.arrow_right.replace(".", "") + '"><span></span></a> ')
        _this.$element.find(_this.options.arrow_left).bind("click", function () {
            var index = _this.options.$switcher.find("." + _this.options.current).index(),
                length = _this.options.contentslen,
                focusindex = length - 1;
            if (index != 0) { focusindex = index - 1; }

            _this.options.$stag.eq(focusindex).trigger(_this.options.trigger);
        });
        _this.$element.find(_this.options.arrow_right).bind("click", function () {
            var index = _this.options.$switcher.find("." + _this.options.current).index(),
                length = _this.options.contentslen,
                focusindex = 0;
            if (index != length - 1) { focusindex = index + 1; }
            _this.options.$stag.eq(focusindex).trigger(_this.options.trigger);
        });
    },
    //设置幻灯片宽和高
    _set_slider_wh: function () {
        var _this = this;
        if (_this.options.slider_w != null) {
            _this.options.$contents.css({ "width": _this.options.slider_w })
        }
        if (_this.options.slider_h != null) {
            _this.options.$contents.css({ "height": _this.options.slider_h })
        }
    },
    _pause: function () {
        var _this = this;
        clearInterval(_this.options.Timer);
    },
    _slide: function () {
        var _this = this;
        if (_this.options.activeindex >= _this.options.contentslen) { _this.options.activeindex = 0; }
        _this.options.$stag.removeClass(_this.options.current).eq(_this.options.activeindex).addClass(_this.options.current);
        switch (_this.options.affect) {
            case 'scrollx':
                var Content_w = _this.options.$contents.outerWidth()
                _this.options.$conbox.width(_this.options.contentslen * Content_w);
                _this.options.$conbox.stop(true, false).animate({ left: -Content_w * _this.options.activeindex }, { duration: _this.options.speed, easing: 'easeOutCirc' });
                break;
            case 'scrolly':
                var Content_h = _this.options.$contents.outerHeight()

                _this.options.$contents.css({ display: 'block' });
                _this.options.$conbox.stop(true, false).animate({ top: -Content_h * index + 'px' }, _this.options.speed);
                break;
            case 'fade_animate':
				_this.options.callback(_this.options.activeindex);
                _this.options.animate ? _this.animate_star(_this.options.$contents.eq(_this.options.activeindex)) : false;
                _this.options.$contents.eq(_this.options.last_index).stop(true, false).animate({ 'opacity': 0 }, _this.options.speed / 2).css('z-index', 1)
                    .end()
                    .eq(_this.options.activeindex).css('z-index', 9).stop().animate({ 'opacity': 1 }, _this.options.speed / 2, function () {

						

                    })
                break;
            case 'fade':
                _this.options.$contents.eq(_this.options.last_index).stop(true, false).animate({ 'opacity': 0 }, _this.options.speed / 2).css('z-index', 1)
                    .end()
                    .eq(_this.options.activeindex).css('z-index', 9).stop().animate({ 'opacity': 1 }, _this.options.speed / 2)
                break;
            case 'none':
                _this.options.$contents.hide().eq(index).show();
                break;
        }
        _this.options.last_index = _this.options.activeindex;
        _this.options.activeindex++;


    },

    _continue: function () {
        var _this = this;
        if (_this.options.auto) {
            clearInterval(_this.options.Timer);
            _this.options.Timer = setInterval(function () { _this._slide() }, _this.options.space);
        }
    },
    bg_show: function () {
        var _this = this;


        _this.options.$contents.each(function (index, element) {
            var $img = $(element).find(_this.options.mainpic),
                src = "";
            if ($img.length > 0) {
                src = $img.attr('src')
                $img.css({ "visibility": "hidden" });
                $(element).css({ "background": "url('" + src + "')", "background-position": "center center", "background-size": "cover" });
            }
        });
    },
    hasScrollbar: function () {
        return document.body.scrollHeight > (window.innerHeight || document.documentElement.clientHeight);
    },

    _fullscreen: function () {
        var _this = this,
            count = 0;

        _this.$element.css({ "min-width": _this.options.fullscreen_min_w })
        var resizetime = null,
            window_w = _this.options.window_w,
            minwidth = _this.options.minwidth;

        var banner_h = _this.$element.outerHeight()

        if (typeof (banner_h) != "undefined") {
            _this.$element.css({ "height": banner_h })
            _this.options.$contents.css({ "width": window_w, "height": banner_h })
        }

        if (_this.hasScrollbar()) { window_w += 17; }


        window_w <= minwidth ? window_w = minwidth : window_w;

        _this.options.$contents.find(_this.options.mainpic).each(function (index, element) {
            var imgself = $(this),
                img_url = imgself.attr("src"),
                img = new Image();

            img.onload = function () {
                var imgwidth = img.width
                var imgheight = img.height
                imgwidth = imgwidth / (imgheight / banner_h)
                imgself.css({ "position": "relative", "left": "50%", "margin-left": "-" + imgwidth / 2 + "px" })
            };
            img.src = img_url;

            var check = function () {
                if (img.width > 0 || img.height > 0 || count > 50) { clearInterval(set); }
                count++
            };
            var set = setInterval(check, 100);
        });


        $(window).bind("resize.slider", function () {
            clearTimeout(resizetime)
            resizetime = setTimeout(function () {
                var window_w = $(window).width();

                if (_this.hasScrollbar()) { window_w += 17; }
                if (_this.piclist.length == 0) { return; }
                if (window_w >= minwidth) {
                    if (window_w < 1920 && _this.options.autoheight) {
                        _this.$element.css("height", window_w * _this.piclist[0].imgbili)
                        _this.options.$contents.css("height", window_w * _this.piclist[0].imgbili)
                    } else {
                        _this.$element.css("height", _this.piclist[0].imgheight)
                        _this.options.$contents.css("height", _this.piclist[0].imgheight)
                    }
                }
                var active = _this.options.activeindex;
                if (window_w <= minwidth) { window_w = minwidth; }
                if (_this.options.affect == 'scrollx') {
                    if (active != 0) { active--; }
                    _this.options.$conbox.css({ "width": _this.options.contentslen * window_w, "left": -window_w * active });
                }
                _this.options.$contents.css("width", window_w);

            }, 20)
        })


    },
    remove: function () {
    },
    getData: function () {
        return this
    }

}


$.fn.Slide_zhy = function (params) {
    var self = this;
    var l = self.length;
    self.each(function (index, element) {
        var $elem = $(element);
        var instance = $elem.data('Slide_zhy');

        if (!instance) {

            if (typeof params === 'object' || !params) {
                $elem.data('Slide_zhy', new Slide_zhy($elem, params));

            }
        } else {

            if (params == "getData") {
                return instance[params].apply(instance, Array.prototype.slice.call(arguments, 1));
            } else if (params == "remove") {
                $elem.removeData('Slide_zhy');
                //instance[params].apply(instance, Array.prototype.slice.call(arguments, 1));		
                // destroy | focusTo | zoomIn | zoomOut | moveRight| moveLeft | moveUp | moveDown | Reset | addLandmark | removeLandmark | attachLandmark | refreshAllLandmarks
            } else if (instance[params]) {
                instance[params].apply(instance, Array.prototype.slice.call(arguments, 1));
            }
        }

    });

    if (params !== "getZoomData") { return this; }

}