
/*! modernizr 3.6.0 (Custom Build) | MIT *
 * https://modernizr.com/download/?-audio-canvas-cssgrid_cssgridlegacy-flexbox-inputtypes-svg-video-setclasses !*/
!function (e, t, n) { function o(e, t) { return typeof e === t } function a() { var e, t, n, a, r, s, i; for (var l in C) if (C.hasOwnProperty(l)) { if (e = [], t = C[l], t.name && (e.push(t.name.toLowerCase()), t.options && t.options.aliases && t.options.aliases.length)) for (n = 0; n < t.options.aliases.length; n++)e.push(t.options.aliases[n].toLowerCase()); for (a = o(t.fn, "function") ? t.fn() : t.fn, r = 0; r < e.length; r++)s = e[r], i = s.split("."), 1 === i.length ? Modernizr[i[0]] = a : (!Modernizr[i[0]] || Modernizr[i[0]] instanceof Boolean || (Modernizr[i[0]] = Boolean(Modernizr[i[0]])), Modernizr[i[0]][i[1]] = a), w.push((a ? "" : "no-") + i.join("-")) } } function r(e) { var t = b.className, n = Modernizr._config.classPrefix || ""; if (x && (t = t.baseVal), Modernizr._config.enableJSClass) { var o = new RegExp("(^|\\s)" + n + "no-js(\\s|$)"); t = t.replace(o, "$1" + n + "js$2") } Modernizr._config.enableClasses && (t += " " + n + e.join(" " + n), x ? b.className.baseVal = t : b.className = t) } function s() { return "function" != typeof t.createElement ? t.createElement(arguments[0]) : x ? t.createElementNS.call(t, "http://www.w3.org/2000/svg", arguments[0]) : t.createElement.apply(t, arguments) } function i(e, t) { return !!~("" + e).indexOf(t) } function l(e) { return e.replace(/([a-z])-([a-z])/g, function (e, t, n) { return t + n.toUpperCase() }).replace(/^-/, "") } function c(e, t) { return function () { return e.apply(t, arguments) } } function u(e, t, n) { var a; for (var r in e) if (e[r] in t) return n === !1 ? e[r] : (a = t[e[r]], o(a, "function") ? c(a, n || t) : a); return !1 } function d(e) { return e.replace(/([A-Z])/g, function (e, t) { return "-" + t.toLowerCase() }).replace(/^ms-/, "-ms-") } function p(t, n, o) { var a; if ("getComputedStyle" in e) { a = getComputedStyle.call(e, t, n); var r = e.console; if (null !== a) o && (a = a.getPropertyValue(o)); else if (r) { var s = r.error ? "error" : "log"; r[s].call(r, "getComputedStyle returning null, its possible modernizr test results are inaccurate") } } else a = !n && t.currentStyle && t.currentStyle[o]; return a } function f() { var e = t.body; return e || (e = s(x ? "svg" : "body"), e.fake = !0), e } function y(e, n, o, a) { var r, i, l, c, u = "modernizr", d = s("div"), p = f(); if (parseInt(o, 10)) for (; o--;)l = s("div"), l.id = a ? a[o] : u + (o + 1), d.appendChild(l); return r = s("style"), r.type = "text/css", r.id = "s" + u, (p.fake ? p : d).appendChild(r), p.appendChild(d), r.styleSheet ? r.styleSheet.cssText = e : r.appendChild(t.createTextNode(e)), d.id = u, p.fake && (p.style.background = "", p.style.overflow = "hidden", c = b.style.overflow, b.style.overflow = "hidden", b.appendChild(p)), i = n(d, e), p.fake ? (p.parentNode.removeChild(p), b.style.overflow = c, b.offsetHeight) : d.parentNode.removeChild(d), !!i } function m(t, o) { var a = t.length; if ("CSS" in e && "supports" in e.CSS) { for (; a--;)if (e.CSS.supports(d(t[a]), o)) return !0; return !1 } if ("CSSSupportsRule" in e) { for (var r = []; a--;)r.push("(" + d(t[a]) + ":" + o + ")"); return r = r.join(" or "), y("@supports (" + r + ") { #modernizr { position: absolute; } }", function (e) { return "absolute" == p(e, null, "position") }) } return n } function v(e, t, a, r) { function c() { d && (delete z.style, delete z.modElem) } if (r = o(r, "undefined") ? !1 : r, !o(a, "undefined")) { var u = m(e, a); if (!o(u, "undefined")) return u } for (var d, p, f, y, v, g = ["modernizr", "tspan", "samp"]; !z.style && g.length;)d = !0, z.modElem = s(g.shift()), z.style = z.modElem.style; for (f = e.length, p = 0; f > p; p++)if (y = e[p], v = z.style[y], i(y, "-") && (y = l(y)), z.style[y] !== n) { if (r || o(a, "undefined")) return c(), "pfx" == t ? y : !0; try { z.style[y] = a } catch (h) { } if (z.style[y] != v) return c(), "pfx" == t ? y : !0 } return c(), !1 } function g(e, t, n, a, r) { var s = e.charAt(0).toUpperCase() + e.slice(1), i = (e + " " + $.join(s + " ") + s).split(" "); return o(t, "string") || o(t, "undefined") ? v(i, t, a, r) : (i = (e + " " + k.join(s + " ") + s).split(" "), u(i, t, n)) } function h(e, t, o) { return g(e, n, n, t, o) } var w = [], C = [], T = { _version: "3.6.0", _config: { classPrefix: "", enableClasses: !0, enableJSClass: !0, usePrefixes: !0 }, _q: [], on: function (e, t) { var n = this; setTimeout(function () { t(n[e]) }, 0) }, addTest: function (e, t, n) { C.push({ name: e, fn: t, options: n }) }, addAsyncTest: function (e) { C.push({ name: null, fn: e }) } }, Modernizr = function () { }; Modernizr.prototype = T, Modernizr = new Modernizr, Modernizr.addTest("svg", !!t.createElementNS && !!t.createElementNS("http://www.w3.org/2000/svg", "svg").createSVGRect); var b = t.documentElement, x = "svg" === b.nodeName.toLowerCase(); Modernizr.addTest("audio", function () { var e = s("audio"), t = !1; try { t = !!e.canPlayType, t && (t = Boolean(t), t.ogg = e.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ""), t.mp3 = e.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, ""), t.opus = e.canPlayType('audio/ogg; codecs="opus"') || e.canPlayType('audio/webm; codecs="opus"').replace(/^no$/, ""), t.wav = e.canPlayType('audio/wav; codecs="1"').replace(/^no$/, ""), t.m4a = (e.canPlayType("audio/x-m4a;") || e.canPlayType("audio/aac;")).replace(/^no$/, "")) } catch (n) { } return t }), Modernizr.addTest("canvas", function () { var e = s("canvas"); return !(!e.getContext || !e.getContext("2d")) }), Modernizr.addTest("video", function () { var e = s("video"), t = !1; try { t = !!e.canPlayType, t && (t = Boolean(t), t.ogg = e.canPlayType('video/ogg; codecs="theora"').replace(/^no$/, ""), t.h264 = e.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/, ""), t.webm = e.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/, ""), t.vp9 = e.canPlayType('video/webm; codecs="vp9"').replace(/^no$/, ""), t.hls = e.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/, "")) } catch (n) { } return t }); var P = s("input"), S = "search tel url email datetime date month week time datetime-local number range color".split(" "), _ = {}; Modernizr.inputtypes = function (e) { for (var o, a, r, s = e.length, i = "1)", l = 0; s > l; l++)P.setAttribute("type", o = e[l]), r = "text" !== P.type && "style" in P, r && (P.value = i, P.style.cssText = "position:absolute;visibility:hidden;", /^range$/.test(o) && P.style.WebkitAppearance !== n ? (b.appendChild(P), a = t.defaultView, r = a.getComputedStyle && "textfield" !== a.getComputedStyle(P, null).WebkitAppearance && 0 !== P.offsetHeight, b.removeChild(P)) : /^(search|tel)$/.test(o) || (r = /^(url|email)$/.test(o) ? P.checkValidity && P.checkValidity() === !1 : P.value != i)), _[e[l]] = !!r; return _ }(S); var E = "Moz O ms Webkit", $ = T._config.usePrefixes ? E.split(" ") : []; T._cssomPrefixes = $; var k = T._config.usePrefixes ? E.toLowerCase().split(" ") : []; T._domPrefixes = k; var N = { elem: s("modernizr") }; Modernizr._q.push(function () { delete N.elem }); var z = { style: N.elem.style }; Modernizr._q.unshift(function () { delete z.style }), T.testAllProps = g, T.testAllProps = h, Modernizr.addTest("cssgridlegacy", h("grid-columns", "10px", !0)), Modernizr.addTest("cssgrid", h("grid-template-rows", "none", !0)), Modernizr.addTest("flexbox", h("flexBasis", "1px", !0)), a(), r(w), delete T.addTest, delete T.addAsyncTest; for (var A = 0; A < Modernizr._q.length; A++)Modernizr._q[A](); e.Modernizr = Modernizr }(window, document);
(function () {
    var agent = navigator.userAgent;
    window.OS_ANDROID = /Android/.test(agent);
    window.OS_IOS = /OS ([_\d]+) like Mac OS X/.test(agent);
    window.DEVICE_IPHONE = /\(iPhone;/.test(agent); // iPhone
    window.DEVICE_IPAD = /\(iPad;/.test(agent);
})();

/*** Localization */
var lang = {
    ko: {
        dialog: {
            title: '알림',
            ok: '확인',
            cancel: '취소'
        },
        clipboard: {
            confirm: '이 글의 URL 주소를 클립보드에 복사하시겠습니까?',
            message: '이 글의 URL 주소입니다. Ctrl+C를 눌러 클립보드로 복사하세요.'
        }
    },
    en: {
        dialog: {
            title: 'Notice',
            ok: 'OK',
            cancel: 'Cancel'
        },
        clipboard: {
            confirm: 'Do you want to copy the URL address of this article to your clipboard?',
            message: 'This is the URL address of this article. Press Ctrl+C to copy to the clipboard.'
        }
    }
};
var locale = document.getElementsByTagName("html")[0].getAttribute("lang");
var commonMsg = lang[locale];

var idvUserinfo = (function () {
    function UserInfo() {
        if (!(this instanceof UserInfo)) return new UserInfo();
        this.init();
    }
    UserInfo.prototype.init = function () {
        var ua = navigator.userAgent;
        /** for Desktop */
        this.CHROME = UserInfo.parseVers("Chrome");
        this.SAFARI = UserInfo.parseVers("Safari");
        this.FIREFOX = UserInfo.parseVers("Firefox");
        this.WEBKIT = UserInfo.parseVers("AppleWebKit");
        this.OPERA = UserInfo.parseVers("Opera") || UserInfo.parseVers("OPR"); // 최근에 Opera가 새로이 업데이트 되면서 userAgent가 바뀜. (마치 크롬처럼...)
        this.TRIDENT = UserInfo.parseVers("Trident");
        this.MSIE = checkTridentForIE(this.TRIDENT); // MSIE
        this.LINUX = /\(Linux;/.test(ua);             // Lunux
        /** for Mobile devices */
        this.ANDROID = UserInfo.parseVers2("Android");
        this.MACINTOSH = /\(Macintosh;/.test(ua); // Macintosh
        this.MAC_OS = checkMacOS();              // Mac OS X
        this.IPHONE = /\(iPhone;/.test(ua);    // iPhone
        this.IPAD = /\(iPad;/.test(ua);      // iPad
        this.I_OS = checkIOS();                // iOS
        /** CSS3 supportability */
        this.CSS = {
            transform: UserInfo.testCss("transform"),
            transition: UserInfo.testCss("transition"),
            backgroundSize: UserInfo.testCss("backgroundSize"),
            blendMode: UserInfo.testCss("mixBlendMode"),
            bgBlendMode: UserInfo.testCss("backgroundBlendMode")
        };
        /** HTML5 supportability */
        this.HTML5 = {
            video: typeof (document.createElement("video"))["play"] == "function",
            canvas: typeof (document.createElement("canvas"))["getContext"] == "function"
        };
        /** AnimationFrame supportability */
        var af = window.requestAnimationFrame ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame ||
            window.msRequestAnimationFrame ||
            window.oRequestAnimationFrame;
        this.animationFrame = !!af;
    };
    UserInfo.parseVers = function (name) {
        var reg = new RegExp(name + "\\/(\\d[\\d\\.]+)");
        var match = navigator.userAgent.match(reg);
        if (match) return match[1];
        return null;
    };
    UserInfo.parseVers2 = function (name) {
        var reg = new RegExp(name + " (\\d[\\d\\.]+)");
        var match = navigator.userAgent.match(reg);
        if (match) return match[1];
        return null;
    };
    UserInfo.testCss = function (prop) {
        var flag = false;
        var vendors = ["webkit", "moz", "ms", "o"];
        if (prop && typeof prop == "string") {
            var div = document.createElement("div");
            if (prop in div.style) {
                flag = true;
            } else {
                var cased = prop.substr(0, 1).toUpperCase() + prop.substr(1); // text transform : "background" -> "Background"
                for (var k = 0; k < vendors.length; k++) {
                    if ((vendors[k] + cased) in div.style) {
                        flag = true;
                        break;
                    }
                }
            }
            div = null;
        }
        return flag;
    };
    function checkTridentForIE(trident) {
        var rRv = /; rv:([\d\.]+)$/;
        var rMSIE = /MSIE ([\d\.]+)/i;
        var ua = navigator.userAgent.match(/^[^\(]+\(([^\(]+)\)/)[1];
        if (rMSIE.test(ua)) return ua.match(rMSIE)[1];        // pattern is "MSIE x.x"
        if (trident && rRv.test(ua)) return ua.match(rRv)[1]; // pattern is "vr:x.x"
        return null; // unknown pattern
    }
    function checkMacOS() {
        var match = navigator.userAgent.match(/Mac OS X ([_\d]+)/);
        if (!match) return null;
        return match[1].replace(/_/g, ".");
    }
    function checkIOS() {
        var match = navigator.userAgent.match(/OS ([_\d]+) like Mac OS X/);
        if (!match) return null;
        return match[1].replace(/_/g, ".");
    }
    return UserInfo();
})();
(function () {
    if (!idvUserinfo.MSIE) return;
    var IE = parseInt(idvUserinfo.MSIE);
    document.documentElement.className = document.documentElement.className + " msie msie" + IE;

    if (IE >= 9) document.documentElement.className = document.documentElement.className + " msest";
})();

function GetIEVersion() {
    var sAgent = window.navigator.userAgent;
    var Idx = sAgent.indexOf("MSIE");
    if (Idx > 0)
        return parseInt(sAgent.substring(Idx + 5, sAgent.indexOf(".", Idx)));
    else if (!!navigator.userAgent.match(/Trident\/7\./))
        return 11;
    else
        return 99; //It is not IE
}
if (GetIEVersion() === 9) {
    $("body").addClass("ie9");
}
if (GetIEVersion() <= 8) {
    $("body").addClass("ie8");
}

// 파라미터 받아오기
function getParameter(strParamName) {
    var arrResult = null;
    if (strParamName) {
        arrResult = location.search.match(new RegExp("[&?]" + strParamName + "=(.*?)(&|$)"));
    }
    return arrResult && arrResult[1] ? arrResult[1] : null;
}

$(function () {
    var CreateShare = function (element, options) {
        this.init(element, options)
    };
    CreateShare.prototype.init = function (element, options) {
        this.element = $(element);
        this.options = options;
        this.bindInEvents();
    };
    CreateShare.prototype.bindInEvents = function () {
        var Sharelink = this.element;
        var target = this.element.data('target');
        var obj = this.element.next();
        var opt = obj.data('id');
        var Closelink = this.element.next().find("[data-target=ui-close]");
        Sharelink.on("click", function () {
            if (target === opt) {
                if (obj.css("display") === "none") {
                    Sharelink.addClass('ov');
                    obj.show().delay(150).animate({ 'opacity': '1' }, 300, 'easeOutCubic');
                } else {
                    Sharelink.removeClass('ov');
                    obj.hide().delay(150).animate({ 'opacity': '0' }, 300, 'easeOutCubic');
                }
            }
        });
        Closelink.on("click", function () {
            Sharelink.removeClass('ov');
            obj.hide().delay(150).animate({ 'opacity': '0' }, 300, 'easeOutCubic');
        });
    };
    function checkSharePlugin(option) {
        var $this = $(this);
        var data = $this.data('target');
        var options = $.extend({}, $this.data(), typeof option === 'object' && option);
        $this.data('target', (data = new CreateShare(this, options)));
        if (typeof option === 'string') data[option]()
    }
    $.fn.checkShare = checkSharePlugin;
    $("[data-target=\"ui-open\"]").each(function () {
        var $this = $(this);   //버튼
        var option = $this.data();
        checkSharePlugin.call($this, option);
    });
    // $(window).on("load", function () {

    // });

});
// kakao 공유하기 스크립트 로드 
function loadScript(url) {
    return new Promise(function (resolve, reject) {
        var script = document.createElement('script');
        script.src = url;

        script.onload = function () {
            resolve();
        };

        script.onerror = function () {
            reject(new Error('스크립트 로드 실패: ' + url));
        };

        document.head.appendChild(script);
    });
}
loadScript('https://developers.kakao.com/sdk/js/kakao.min.js')
    .then(function () {

    })
    .catch(function (error) {
        // 로드 실패 시 실행할 코드
        console.error(error);
    });
// kakao 공유하기 스크립트 로드  e
//sns공유 시작
function snswindowOpen() {
    var nUrl; var nWidth; var nHeight; var nLeft; var nTop; var nScroll;
    nUrl = arguments[0];
    nWidth = arguments[1];
    nHeight = arguments[2];
    nScroll = (arguments.length > 3 ? arguments[3] : "no");
    nLeft = (arguments.length > 4 ? arguments[4] : (screen.width / 2 - nWidth / 2));
    nTop = (arguments.length > 5 ? arguments[5] : (screen.height / 2 - nHeight / 2));
    winopen = window.open(nUrl, 'SNS', "left=" + nLeft + ",top=" + nTop + ",width=" + nWidth + ",height=" + nHeight + ",scrollbars=" + nScroll + ",toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=no");
}
$(document).ready(function () {
    $("[data-button='sns_share']").on("click", function (e) {
        e.preventDefault();
        var $this = $(this);
        var sns_type = $this.attr('data-service');
        var href = encodeURIComponent(location.href);
        var title = $this.attr('data-title');
        var loc = "";
        var img = $("meta[name='og:image']").attr('content');

        if (!sns_type || !href || !title) return;

        if (sns_type == 'facebook') {
            loc = '//www.facebook.com/sharer/sharer.php?u=' + href + '&t=' + title;
            snswindowOpen(loc, 900, 450, 'no');
        }
        else if (sns_type == 'twitter') {
            loc = '//twitter.com/home?status=' + encodeURIComponent(title) + ' ' + href;
            snswindowOpen(loc, 800, 400, 'yes');
        }
        else if (sns_type == 'pinterest') {

            loc = '//www.pinterest.com/pin/create/button/?url=' + href + '&media=' + img + '&description=' + encodeURIComponent(title);
            snswindowOpen(loc, 900, 550, 'no');
        }
        else if (sns_type == 'kakaostory') {
            loc = 'https://story.kakao.com/share?url=' + href;
            snswindowOpen(loc, 900, 450, 'no');
        }
        else if (sns_type == 'band') {
            loc = 'http://www.band.us/plugin/share?body=' + encodeURIComponent(title) + '%0A' + href;
            snswindowOpen(loc, 800, 400, 'yes');
        }
        else if (sns_type == 'naver') {
            loc = "http://share.naver.com/web/shareView.nhn?url=" + href + "&title=" + encodeURIComponent(title);
            snswindowOpen(loc, 800, 400, 'yes');
        }
        else if (sns_type == 'kakaoTalk') {
            Kakao.init('04ca0ed652b7533b998567020dbc4974');
            Kakao.Link.sendDefault({
                objectType: 'feed',
                content: {
                    title: title,
                    imageUrl: '',
                    link: {
                        mobileWebUrl: window.location.href,
                        webUrl: window.location.href
                    }
                }
            });
            //loc = "http://share.naver.com/web/shareView.nhn?url="+href+"&title="+encodeURIComponent(title);
            //snswindowOpen (loc, 800, 400, 'yes');
        }
        else {
            return false;
        }
        return false;
    });
});

function CopyUrl(event){
    var data =  document.location.href;
    var str = "";
    var IE= false;
    var agent = navigator.userAgent.toLowerCase();

    if ( (navigator.appName == 'Netscape' && agent.indexOf('trident') != -1) || (agent.indexOf("msie") != -1)) {
        IE = true;
    }else{
        IE = false;
    }

    if(document.location.href.indexOf('bbs') > -1 && document.location.href.indexOf('view') > -1){
        if (document.location.href.indexOf('nttId') < 0) {
            str = "?nttId=" + document.searchForm.nttId.value;
        }
        data =  document.location.href + str;
    }

    if (document.querySelectorAll('input[name="copyUrlData"]').length > 0) {
        // 링크 경로 재조합 by ISU
        data = document.location.protocol + "//" + document.location.host + document.location.pathname;
        var params = document.querySelectorAll('input[name="copyUrlData"]')[0].value;
        if (data.indexOf("?") < 0) {
            data += "?";
        } else {
            data += "&";
        }
        data += params;
    }

    if (IE) {
        if(confirm(commonMsg.clipboard.confirm))
            window.clipboardData.setData("Text", data);
    } else {
        temp = prompt(commonMsg.clipboard.message, data);
    }
}


//쿠키저장
function setCookie(name, value, expiredays) {
    var todayDate = new Date();
    todayDate.setDate(todayDate.getDate() + expiredays);
    document.cookie = name + "=" + escape(value) + "; path=/; expires=" + todayDate.toGMTString() + ";"
}
function getCookie(name) {
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0; while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg) {
            var end = document.cookie.indexOf(";", j);
            if (end == -1) end = document.cookie.length;
            return unescape(document.cookie.substring(j, end));
        }
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break;
    }
    return null;
}
/*********팝업관련 자바스크립트 소스****************/
function close_layer(num) {
    document.getElementById(num).style.display = 'none';
    //쿠키굽기
    setCookie(num, 'done', 1);
}
function close_layer2(num) {
    document.getElementById(num).style.display = 'none';
}
function link_target(url, target) {
    if (target == '_blank') {
        window.open(url);
    } else if (target == '_self') {
        location.href = url;
    } else {
        opener.location.href = url;
    }
}
function message() {
    alert("서비스준비중입니다.");
    return false;
}
$(function () {
    var showToggle = function (element, options) {
        $element = $(element);
        this.element = element;
        this.options = options;
        $element.on('click mouseenter', $.proxy(this.show, this));
        $element.on('click.close mouseleave', $.proxy(this.hide, this));
        //$originalinput.on('change',  $.proxy(this.change, this));
    };
    showToggle.prototype.show = function () {
        $target = $(this.options.target);
        $target.show();
    };
    showToggle.prototype.hide = function () {
        $target = $(this.options.target);
        $target.hide();
    };
    function showTogglePlugin(option) {
        var $this = $(this);
        var data = $this.data('button');
        var options = typeof option === 'object' && option;
        $this.data('showToggle', (data = new showToggle(this, options)));
        if (typeof option === 'string') data[option]()
    }
    $.fn.showToggle = showTogglePlugin;
    $(window).on("load", function () {
        $("[data-button=\"showToggle\"]").each(function () {
            var $this = $(this);   //버튼
            var option = $this.data();
            showTogglePlugin.call($this, option);
        });
    });
});
/* mobile select */
function tab_mobile() {
    var window_w = $(window).width();
    tab = $("#tab_moType1");
    tab_li = tab.find(">ul>li");
    tab_on = tab.find(">ul>li.on");
    if (tab.find(">.title").size() == 0) {
        $('<strong class="title"><i class="arrow"></i></strong>').prependTo(tab);
    }
    var tab_tit = tab.find(">.title");
    if (tab_on.size() != 0) {
        tab_tit.html(tab_on.find(">a").clone());
    } else {
        tab_tit.html(tab_li.eq(0).find(">a").clone());
    }
    var tab_btn = tab_tit.find(">a");
    tab_btn.click(function () {
        if (tab_li.eq(0).is(":hidden")) {
            tab_tit.find(">a").addClass("on");
            tab_li.slideDown();
        } else {
            tab_tit.find(">a").removeClass("on");
            tab_li.slideUp();
        }
        return false;
    });
    if (window_w < 768) {
        if (tab.hasClass("mobile")) return false;
        tab.removeClass("pc").addClass("mobile");
    } else {
        if (!tab.hasClass("mobile")) return false;
        tab.removeClass("mobile").addClass("pc");
        tab_li.removeAttr("style");
    }
}

//TabMenu
$(function () {
    var tab = function (element) {
        this.element = $(element);
    };
    tab.prototype.show = function () {
        var $this = this.element,
            $ul = $this.closest("ul"),
            $target,
            $targetGroup,
            selector = $this.attr("href");
        selector = selector && selector.replace(/.*(?=#[^\s]*$)/, ""); // strip for ie7

        if ($this.parent("li").hasClass("active")) {
            return;
        }
        $target = $(selector);
        $targetGroup = $(selector).parent().closest("div");
        this.activate($this.closest("li"), $ul, "> .active", "nav");
        this.activate($target, $targetGroup, ".active");
        //this.activate( $target, $targetGroup, ".tab__body.active");
    };
    tab.prototype.activate = function (element, container, cts, area) {
        var $ov = container.find(cts);
        if ($ov.hasClass("tab__body")) {
            $ov
                .stop()
                .hide()
                .removeClass("active")
                .end();
            element
                .stop()
                .slideDown(500, function () {
                    $(this).addClass("active");
                });
        }
        else if ($ov.hasClass("fade")) {
            $ov
                .stop()
                .hide()
                .removeClass("active")
                .end();
            element
                .stop()
                .fadeIn(300, function () {
                    $(this).addClass("active");
                });
        }
        else {
            $ov
                .removeClass("active")
                .end();
            element
                .addClass("active");
        }
        if (area === "nav") {
            $ov.find("a, button")
                .attr("title", "");
            element.find("a, button")
                .attr("title", "선택됨");
        }
        if (area !== "nav") {
            $ov
                .attr("title", "숨김");
            element
                .attr("title", "열림");
        }
    };
    $(document).on("click", "[data-button='tab']", function (e) {
        if (!$(this).data("url")) {
            e.preventDefault();
            $(this).each(function () {
                var $this, data, option;
                $this = $(this);
                data = $this.data("tab");
                option = "show";
                if (!data) {
                    $this.data("tab", (data = new tab(this)));
                }

                if (typeof option === "string") {
                    data[option]();
                }
                this.options = $this.data();
                if (this.options.dropdown) {
                    Dropdown(); // tab 내  dropdown 실행
                }
            });
        }
    });
});
//Accordion
$(function () {
    var Accordion = function (element, option, options) {
        this.element = $(element);
        this.option = option;
        this.options = options;
    };
    Accordion.prototype.show = function () {
        var $this = this.element,
            selector = $this.attr("href"),
            $target = $(selector);
        if (this.options.arange) {
            this.openToggle(this.options.arange);
            return;
        }
        if ($this.hasClass("ov")) {
            this.disabled($this);
            this.disabled($target, "display");
            return;
        }
        this.activate($this);
        this.activate($target, "display");
    };

    Accordion.prototype.activate = function (element, display) {
        element.addClass("ov").attr("title", "열림");
        if (display) {
            element.show();
            element.attr("title", "열림");
        }
    };
    Accordion.prototype.disabled = function (element, display) {
        element.removeClass("ov").attr("title", "닫힘");
        if (display) {
            element.hide();
            element.attr("title", "숨김");
        }
    };
    Accordion.prototype.openToggle = function (status) {
        var $target = $(this.options).find('[data-accordion]');
        $target.each(function () {
            var ov = $(this).attr("href");
            if (status === "open") {
                $(this).parent().addClass("ov");
                $(this).addClass("ov");
                $(ov)
                    .addClass("ov")
                    .show()
                    .attr("title", "열림");
            } else {
                $(this).parent().removeClass("ov");
                $(this).removeClass("ov");
                $(ov)
                    .removeClass("ov")
                    .hide()
                    .attr("title", "숨김");
            }
        });
    };
    $(document).on("click", "[data-accordion]", function (e) {
        e.preventDefault();
        $(this).each(function () {
            var $this = $(this);
            var data = $this.data("accordion");
            var option = "show";
            var options = $this.data();
            if (!data) {
                $this.data("accordion", (data = new Accordion(this, option, options)));
            }
            if (typeof option === "string") {
                data[option]();
            }
            this.options = $this.data();
        });

    });
});
/// basic tab (WAI-ARIA Roles)
$(document).ready(function () {
    $(".tabpanel:first-of-type").addClass("on").attr("tabindex", "0");
    $(".js-tab").eq(0).addClass("on");
    $(".js-tab").eq(0).find('a').attr("tabindex", "0").attr("aria-selected", "true");
    $(".js-tab a").on("click", function (event) {
        if (event.preventDefault) {
            event.preventDefault()
        } else {
            event.returnValue = false
        }
        var $this = $(this),
            $scope = $this.parents('.ui-tablist'),
            $tabButtons = $scope.find('.js-tab'),
            $ovTab = $tabButtons.filter('.on');
        if ($ovTab[0] !== $this[0]) {
            var $tabPanels = $scope.find('.tabpanel'),
                $ovPanel = $tabPanels.filter('.on');
            $ovTab.removeClass('on');
            $ovTab.children('a').attr('aria-selected', 'false');
            $ovTab.children('a').attr('title', '');
            $this.parent('li').addClass('on');
            $this.attr('aria-selected', 'true');
            $this.attr('title', '선택됨');

            var href = $this.attr("aria-controls");
            $ovPanel.removeClass('on');
            $("[id=" + href + "]").addClass('on');
        }
        event.preventDefault()

    });
});
$(function () {
    $('.ui-tab_scroll').each(function () {
        var $this = $(this),
            $Tab = $this.find('[data-button="scroll"]'),
            moveTarget = $(this).find('.move_point');
        $Tab.on('click', function () {
            var thisIndex = $(this).parent('li').index(),
                movePoint = moveTarget.eq(thisIndex).offset().top,
                wWidth = $(window).width();
            if (wWidth > 1201) {
                movePoint = movePoint - 100
            }
            $('html, body').stop().animate({ scrollTop: movePoint });
        })
    });
});
/* Dialog */
var Common = {};
Common.Dialog = {
    /*** Dialog Id*/
    DialogInfo: {
        titleId: 'common-modal-title',
        okBtnId: 'common-modal-ok-btn',
        cancelBtnId: 'common-modal-cancel-btn',
    },
    /*** Default Item Message*/
    Message: {
        title: commonMsg.dialog.title,
        ok: commonMsg.dialog.ok,
        cancel: commonMsg.dialog.cancel
    },
    createElement: function (elementTag, attributeData, appendElement) {
        // Element 생성
        var elementObj = document.createElement(elementTag);
        // Attrbute 추가
        for (var key in attributeData) {
            //console.log(key, attrbutes[key]);
            elementObj.setAttribute(key, attributeData[key]);
        }
        // Element Append
        if (appendElement) {
            appendElement.appendChild(elementObj);
        }

        return elementObj;
    },

    /**
     * Modal Dialog Make
     */
    makeModalDialog: function (data) {
        // UUID 생성
        var uuid;
        if (typeof (Util) === 'object' && typeof (Util.uuid) === 'function') {
            uuid = Util.uuid();
        } else {
            uuid = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
        }

        // Dialog Id
        data.dialogId = 'common-modal-dialog-' + data.dialogType + '-' + uuid;

        /***************************************************************************/
        // ---------------- Modal Main Div ----------------
        var modalDiv = this.createElement('div'
            , { 'id': data.dialogId, 'class': 'modal modal-confirm fase', 'tabindex': '-1', 'role': 'dialog', 'aria-labelledby': this.DialogInfo.titleId,}
            , document.body);
        var modalDialogDiv = this.createElement('div', { 'class': 'modal__dialog' }, modalDiv);
        var modalContentDiv = this.createElement('div', { 'class': 'modal__body' }, modalDialogDiv);

        // ---------------- Modal Header ----------------
        var modalHeaderDiv = this.createElement('div', { 'class': 'modal__header' }, modalContentDiv);
        // Close Header
        if (data.closeBtn) {
            var modalHeaderCloseBtn = this.createElement('button', { 'type': 'button', 'class': 'close', 'data-dismiss': 'modal' }, modalHeaderDiv);
            modalHeaderCloseBtn.innerHTML = 'x';
        }
        // title
        var modalHeaderTitle = this.createElement('h4', { 'class': 'modal__title', 'id': this.DialogInfo.titleId }, modalHeaderDiv);
        modalHeaderTitle.innerHTML = data.title ? data.title : this.Message.title;
        // ---------------- Modal Body ----------------
        var modalBodyDiv = this.createElement('div', {
            'class': 'modal__content',
            'style': 'word-break: break-all'
        }, modalContentDiv);
        modalBodyDiv.innerHTML = data.content ? data.content : '';

        // ---------------- Modal Footer ----------------
        var modalFooterDiv = this.createElement('div', { 'class': 'modal__footer' }, modalContentDiv);
        // Cancle Button
        if (data.dialogType == 'confirm') {
            var modalFooterCancleBtn = this.createElement('button', { 'type': 'button', 'class': 'btn btn-default', 'data-dismiss': 'modal', 'id': this.DialogInfo.cancelBtnId }, modalFooterDiv);
            modalFooterCancleBtn.innerHTML = this.Message.cancel;
        }
        // Ok Button
        var modalFooterOkAttr = { 'type': 'button', 'class': 'btn btn-primary', 'id': this.DialogInfo.okBtnId };
        if (data.dialogType == 'alert') {
            modalFooterOkAttr['data-dismiss'] = 'modal';
        }
        var modalFooterOkBtn = this.createElement('button', modalFooterOkAttr, modalFooterDiv);
        modalFooterOkBtn.innerHTML = this.Message.ok;
        /***************************************************************************/
        // Modal Default option Setting
        var modalOption = {
            keyboard: true // ESC 키 눌렀을때 모달을 닫음
            , backdrop: 'static' // 모달의 배경을 포함. 클릭 시 모달을 닫지 않을 시 'static'
            , show: false // 초기화 시 모달을 보여줍니다.
        };
        // 사용자 지정 정보 설정
        $.extend(modalOption, data);

        // Jquery Dialog 변수 선언
        var dialog = $('#' + data.dialogId);

        // Bootstrap Modal Setting
        dialog.modal(modalOption);

        // Modal의 hide가 완료된 이후 Event 실행
        dialog.on('hidden.bs.modal', function (e) {
            // Modal Element 제거
            dialog.remove();
            $("html,body").removeClass("modal__open");
        });
        // Confirm 일 경우 확인 버튼 클릭 이벤트 지정
        if (data.dialogType == 'confirm') {
            dialog.find(" #" + this.DialogInfo.okBtnId).on('click', function () {
                // ok button event function 실행
                if (data.ok && typeof (data.ok) === 'function') {
                    dialog.modal('hide');
                    $(this).off('click');
                    $("html,body").removeClass("modal__open");
                    data.ok();
                } else {
                    console.warn('not function ok event. dialogId: ' + data.dialogId);
                }
            });
            dialog.find(" #" + this.DialogInfo.cancelBtnId).on('click', function () {
                // ok button event function 실행
                if (data.cancel && typeof (data.cancel) === 'function') {
                    dialog.modal('hide');
                    $(this).off('click');
                    $("html,body").removeClass("modal__open");
                    data.cancel();
                } else {
                    console.warn('not function ok event. dialogId: ' + data.dialogId);
                }
            });
        }
        if (data.dialogType == 'alert') {
            dialog.find(" #" + this.DialogInfo.okBtnId).on('click', function () {
                // ok button event function 실행
                if (data.ok && typeof (data.ok) === 'function') {
                    dialog.modal('hide');
                    $(this).off('click');
                    $("html,body").removeClass("modal__open");
                    data.ok();
                } else {
                    console.warn('not function ok event. dialogId: ' + data.dialogId);
                }
                    // 접근성 추가
                    var focusTarget = $(data.focus);
                    setTimeout(() => {
                        focusTarget.focus();
                    }, 150);
            });
        }
        // Modal Dialog Show
        dialog.modal('show');
    },
    /**
     * Modal Dialog Show
     */
    show: function (type, data) {
        if (!data) { data = {}; }
        data.dialogType = type ? type : 'alert';
        this.makeModalDialog(data);
    },
    /**
     * Alert Modal Dialog
     * data:
     *  title: Dialog Title Message
     *  content: Dialog Content Message
     *  closeBtn: Header Close Btn(x)
     *
     */
    alert: function (data) {
        // data가 Object 가 아닌 경우 content 로 설정한다.
        if (typeof (data) != 'object') {
            var content = data;
            data = { content: content };
        }
        this.show('alert', data);
    },
    /**
     * data:
     *  title: Dialog Title Message
     *  content: Dialog Content Message
     *  ok: Ok Button Click Event function
     *  closeBtn: Header Close Btn(x)
     *
     */
    confirm: function (data) {
        this.show('confirm', data);
    }
};
$(function () {
    var Modal = function (btn, options) {
        this.options = options;
        this.$body = $(document.body);
        this.$button = $(btn);
        this.href = this.$button.attr("href");
        this.$element = $(this.options.target || (this.href && this.href.replace(/.*(?=#[^\s]+$)/, ""))); //button-target or a href
        //this.$element           = $(this.options.target);
        this.backdropselector = "modal__backdrop";
        this.widthtselector = "modal__body";
        this.heightselector = "modal__content";
        this.isShown = null;

        if (this.options.contentSousrce) {
            this.contentReplace();
        }
    };

    Modal.DEFAULTS = {
        backdrop: true,
        show: true,
        keyboard: true,
        width: 600
    };

    Modal.prototype.show = function () {
        var element = this.$element,
            modalBtn = this.button,
            modalBodyWidth = this.options.width;

        this.isShown = true;
        this.$body.addClass("modal__open");
        $("html").addClass("modal__open");

        //크기 조정 및 보이기
        this.setSize();
        element.show();

        var transition = element.hasClass("fade");
        if (transition) {
            element[0].offsetWidth; // force reflow
        }

        element.addClass("active");

        //모달 뒤 검은 배경
        if (this.options.backdrop) {
            this.backdrop();
        }

        //닫기 버튼
        element.on('click.close', '[data-close=\'modal\']', $.proxy(this.hide, this));

        $(document)  //  모달 포커스 이동
            .off("focusin.modal") // guard against infinite focus loop
            .on("focusin.modal", function (e) {
                if (element[0] !== e.target && !element.has(e.target).length) {
                    element.trigger("focus");
                }
            });

        this.escape();
        //브라우저 리사이즈
        this.resize();
        this.enforceFocus()
    };

    Modal.prototype.enforceFocus = function () {
        $(document)
            .off('focusin.modal') // guard against infinite focus loop
            .on('focusin.modal', $.proxy(function (e) {
                if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
                    this.$element.trigger('focus')
                }
            }, this))
    };


    Modal.prototype.hide = function (e) {
        var element = this.$element,
            backdrop = "." + this.backdropselector,
            modalbtn = this.$button;

        this.isShown = false;

        if (e) e.preventDefault();
        element.hide().removeClass("active");
        $(document.body).removeClass("modal__open");
        $("html").removeClass("modal__open");

        element.find(backdrop).remove();
        modalbtn.trigger("focus");

        this.escape();
        this.resize();

        if (this.options.file) {
            $("#txt").find("a[href='" + this.options.file + "']").focus();
        }

    };
    Modal.prototype.contentReplace = function () {
        //console.log(this.options.contentSousrce);
        $("." + this.heightselector).html(this.options.contentSousrce);
    };
    //검은 배경
    Modal.prototype.backdrop = function () {
        var element = this.$element,
            backdrop = $("<div class='" + this.backdropselector + "'></div>")
                .prependTo(element)
                .css("height", 0)
                .css("height", '100%')
                .on("click", $.proxy(this.hide, this));

    };
    Modal.prototype.adjustBackdrop = function () {
        this.$element.find("." + this.backdropselector)
            .css('height', 0)
            .css('height', this.$element[0].height)
    };
    Modal.prototype.setSize = function (width, height) {
        var element = this.$element,
            modalWidth = this.options.width,
            modalHeight = this.options.height;

        if (modalWidth > $(window).width()) {
            modalWidth = $(window).width() - 50;
        }
        element.find("." + this.widthtselector).css({
            width: modalWidth
        });

        //console.log(modalHeight);
        if (modalHeight) {
            element.find("." + this.heightselector).css({
                height: modalHeight
            });
        }
    };

    Modal.prototype.resize = function () {
        if (this.isShown) {
            $(window).off('resize.modal')
            //$(window).on('resize.modal', $.proxy(this.adjustBackdrop, this))
        } else {
            $(window).off('resize.modal')
        }
    };
    Modal.prototype.escape = function () {
        if (this.isShown && this.options.keyboard) {
            this.$element.on('keyup', $.proxy(function (e) {
                e.which == 27 && this.hide()
            }, this))
        } else if (!this.isShown) {
            this.$element.off('keydown')
        }
    };
    function modalPlugin(option) {
        return this.each(function () {
            var $this = $(this);
            var data = $this.data("modal");
            var href = $this.attr("href");
            var $target = $($this.attr("data-target") || (href && href.replace(/.*(?=#[^\s]+$)/, ""))); // strip for ie7

            var options = $.extend({ remote: !/#/.test(href) && href }, Modal.DEFAULTS, $this.data(), $target.data(), typeof option === 'object' && option);

            if (!data) {
                $this.data("modal", (data = new Modal(this, options)));
            }

            if (typeof option === "string") {
                data[option]()
            }
            else if (options.show) {
                data.show()
            }
        });
    }

    $.fn.madalPop = modalPlugin;

    $(document).on("click.modal", "[data-button='modal']", function (e) {
        e.preventDefault();
        var $this = $(this);   //버튼
        var option = $this.data();

        if ($this.is("button") || $this.is("a")) {
            e.preventDefault();
        }
        modalPlugin.call($this, option);
    });

});
(function ($) {
    var $fileBox = null;
    $(function () {
        inits();
    });
    function inits() {
        $fileBox = $('.form-upload');
        fileLoad();
    }
    function fileLoad() {
        $.each($fileBox, function (idx) {
            var $this = $fileBox.eq(idx),
                $btnUpload = $this.find('[type="file"]'),
                $label = $this.find('[data-button="upload"]');
            $btnUpload.on('change', function () {
                var $target = $(this),
                    fileName = $target.val(),
                    $fileText = $target.siblings('[type="text"]');
                $fileText.val(fileName);
            });
            $btnUpload.on('focusin focusout', function (e) {
                e.type == 'focusin' ?
                    $label.addClass('focus') : $label.removeClass('focus');
            })

        })
    }
})(jQuery);

//chekcbox  전체 선택, 해제
$(function () {
    var checkedall = function (el, options) {
        $element = $(el);
        this.element = el;
        this.options = options;
        this.checkBtn = $element.find('[data-button="select-all"]');  //전체선택 checkbox
        //this.checkItemName = 'input[name=\"' + this.options.checkallname + '\"]';
        this.checkItem = $element.find('[data-button="checkItem"]'); //각 checkbox name
        this.checkItemNum = this.checkItem.length;
        //console.log(this.options.checkallname);
        // alert(this.checkBtn);
        this.checkBtn.on('change', $.proxy(this.changeall, this));
        this.checkItem.on('change', $.proxy(this.changeitem, this));
    };
    checkedall.prototype.changeall = function () {
        this.checkItem.prop('checked', this.checkBtn.prop("checked"));
        var checkItemStatus = $(this.checkItem).is(":checked");
        if (this.options.visibletarget) {
            this.displayTarget(checkItemStatus);
        }
    };
    checkedall.prototype.changeitem = function () {
        this.checkedItem = $(this.element).find(this.checkItemName + ":checked").length;
        //checkItem 체크, 해제 되면
        if (false === this.checkItem.prop("checked")) {
            this.checkBtn.prop('checked', false);
        }
        if (this.checkedItem > 0 && this.checkedItem < this.checkItemNum) { //checkedItem 1개이상 체크되면
            this.checkBtn.prop('checked', false);
            this.targetStatus = true;
        }
        else if (this.checkedItem === this.checkItemNum) { //checkedItem 모두 체크되면
            this.checkBtn.prop('checked', true);
            this.targetStatus = true;
        }
        else {
            this.checkBtn.prop('checked', false);  //checked 없으면
            this.targetStatus = false;
        }

        if (this.options.visibletarget) {
            this.displayTarget(this.targetStatus);
        }
    };


    checkedall.prototype.displayTarget = function (visible) {
        var visibleStatus = $(this.options.visibletarget).is(":visible");
        if (visible === true) {
            if (!visibleStatus) {
                $(this.options.visibletarget).show();
            }
        } else {
            if (visibleStatus) {
                $(this.options.visibletarget).hide();
            }
        }
    };
    function checkAll(option) {
        var $this = $(this);
        var data = $this.data("select");
        var options = typeof option === 'object' && option;
        if (data) $this.data('select', (data = new checkedall(this, options)));
        if (typeof option === 'string') data[option]()
    }
    $(window).on("load", function () {
        $("[data-select=\"checkall\"]").each(function () {
            var $this = $(this);   //버튼
            var option = $this.data();
            checkAll.call($this, option);
        });
    });
});

//kakao map
$(function () {
    var CreateMap = function (element, options) {
        this.init(element, options)
    };
    CreateMap.DEFAULTS = {
        level: 3,
        draggable: true,
        zoomable: true,
        typecontrol: false
    };
    CreateMap.prototype.init = function (element, options) {
        this.element = $(element);
        this.options = options;
        this.addMarker();
    };
    CreateMap.prototype.addMarker = function () {
        var mapContainer = this.element[0],
            mapOption = {
                center: new daum.maps.LatLng(this.options.lat, this.options.lng), // 지도의 중심좌표
                level: this.options.level // 지도의 확대 레벨
            };

        var map = new daum.maps.Map(mapContainer, mapOption); // 지도를 생성합니다

        map.setDraggable(this.options.draggable); //지도  drag 제어
        map.setZoomable(this.options.zoomable);   //지도 확대,축소 제어

        if (this.options.typecontrol) {
            var mapTypeControl = new daum.maps.MapTypeControl();
            map.addControl(mapTypeControl, daum.maps.ControlPosition.TOPRIGHT);

            var zoomControl = new daum.maps.ZoomControl();
            map.addControl(zoomControl, daum.maps.ControlPosition.RIGHT);
        }

        var imageSrc = '/pcms/common/images/marker.png',
            imageSize = new daum.maps.Size(32, 42), // 마커이미지의 크기
            imageOption = { offset: new daum.maps.Point(32, 42) }; // 마커의 좌표와 일치시킬 이미지 안에서의 좌표를 설정

        // 마커가 표시될 위치
        var markerImage = new daum.maps.MarkerImage(imageSrc, imageSize, imageOption),
            markerPosition = new daum.maps.LatLng(this.options.lat, this.options.lng);


        // 마커를 생성
        var marker = new daum.maps.Marker({
            position: markerPosition,
            image: markerImage
        });

        // 마커가 지도 위에 표시되도록 설정
        marker.setMap(map);
        if (this.options.title || this.options.info) {
            var customOverlay = new daum.maps.CustomOverlay({
                position: markerPosition
            });
            var content = document.createElement('div');
            content.className = "ui-map-info";
            var title = document.createElement('div');
            title.className = "ui-map-info__title";
            title.appendChild(document.createTextNode(this.options.title));
            content.appendChild(title);
            if (this.options.info) {
                var info = document.createElement('div');
                info.className = "ui-map-info__content";
                info.appendChild(document.createTextNode(this.options.info));
                content.appendChild(info);

                content.className = "ui-map-info--multi";
            }
            customOverlay.setContent(content);
            customOverlay.setMap(map);
        }
    };
    function checkMapPlugin(option) {
        var $this = $(this);
        var data = $this.data('map');
        //var options = typeof option === 'object' && option;
        var options = $.extend({}, CreateMap.DEFAULTS, $this.data(), typeof option === 'object' && option);
        $this.data('map', (data = new CreateMap(this, options)));
        if (typeof option === 'string') data[option]()
    }
    $.fn.checkMap = checkMapPlugin;
    $("[data-map=\"map\"]").each(function () {
        var $this = $(this);   //버튼
        var option = $this.data();
        checkMapPlugin.call($this, option);
    });
});

/**
 * table swipe
 */


$(function () {
    var tableElement = function (table, options) {
        var setDefault = {
            tabletype: "scroll",
            breakparent: "#txt",
            addheadelement: "add-head",
            addwrapclass: "table-responsive",
            target: window,
            breakpoint: 640,
            breakstatus:false
        };
        this.element = $(table);
        this.options = $.extend({}, setDefault, options);
        this.element.addClass(this.options.tabletype);
        this.$target = $(this.options.target).on("resize", $.proxy(this.tableCheck, this));
        this.tableCheck();
    };

    tableElement.prototype.getState = function () {
        if ($(window).innerWidth() > this.options.breakpoint) {
            return "notRwd";
        } else {
            return "applyRwd";
        }
    };

    tableElement.prototype.getWidth = function () {
        this.element
            .css("width", this.options.breakpoint)
            .closest("." + this.options.addwrapclass).addClass("active")
            .addClass("mobile icon");
        this.options.breakstatus = true;
    };
    tableElement.prototype.removeWidth = function () {
        this.element
            .css("width", "")
            .closest("." + this.options.addwrapclass).removeClass("active")
            .removeClass("mobile icon");
        this.options.breakstatus = false;
    };

    tableElement.prototype.getWrap = function (classname) {
        var wrapElement = this.element,
            wrapClassName = classname,
            addClassTarget;
        if (!wrapClassName) {
            wrapClassName = this.options.addwrapclass;
        }
        addClassTarget = wrapElement.closest("." + wrapClassName);
        if (!addClassTarget[0]) {
            wrapElement.wrap("<div class='" + wrapClassName + "' />");
        }
    };

    tableElement.prototype.getIcon = function () {
        addClassTarget = this.element.closest("." + this.options.addwrapclass);
        var icon = addClassTarget.find('.scrollable-icon')
        if (icon.size() == 0) {
            var scrollIcon = "<span class='scrollable-icon'></span>";
            $(scrollIcon).prependTo(addClassTarget);
        }



        /*
        var hasClassName = this.hasClassName(addClassTarget, this.options.scrollguide);

        if (this.options.scrollguide) {
            var scrollBottomPosition = (this.element.offset().top - $(window).outerHeight()) <= $(window).scrollTop(),
                scrollTopPosition = this.element.offset().top >= $(window).scrollTop();

            if (scrollBottomPosition && scrollTopPosition) {
                if (!hasClassName) {
                    addClassTarget
                        .removeClass("bounceout")
                        .addClass("bouncein " + this.options.scrollguide);
                    bounceTime = setTimeout($.proxy(function () {
                        this.bounceIcon();
                    }, this), 3000);
                }
            } else {
                this.removeIcon()
            }
        }*/


    };
    tableElement.prototype.bounceIcon = function () {
        addClassTarget = this.element.closest("." + this.options.addwrapclass);
        if (this.options.scrollguide) {
            addClassTarget
                .removeClass("bouncein")
                .addClass("bounceout");
        }
    };

    tableElement.prototype.removeIcon = function () {
        if (this.options.scrollguide) {
            addClassTarget = this.element.closest("." + this.options.addwrapclass);
            var hasClassName = this.hasClassName(addClassTarget, this.options.scrollguide);
            if (hasClassName) {
                addClassTarget.removeClass(this.options.scrollguide);
            }

        }
    };

    tableElement.prototype.hasClassName = function (el, className) {
        var name = el.hasClass(className);
        return name;
    };

    tableElement.prototype.getBoard = function () {
        var trs = this.element.find('tr');
        var trsChild;
        var grid = {};
        var cells;
        trs.each(function (index, item) {
            if (!grid[index]) {
                grid[index] = {};
            }
            trsChild = item.childNodes;
            cells = 0;
            for (var j = 0, cntJ = trsChild.length; j < cntJ; j++) {
                grid[index][cells++] = trsChild[j];
            }
            var tds = $(item).find("td");
            tds.addClass(j);
            tds.wrapInner("<span class='tds'></span>")  //셀내용 span 감싸기
        });

        var cellHeader = "";
        for (row in grid) {
            if (row == 0) {
                continue;
            }
            for (cell in grid[row]) {
                if (cell == 0) {
                    continue;
                }
                var cellHeader = $(grid[0][cell]).html();
                var insertCellHeader = "<span class=" + this.options.addheadelement + ">" + cellHeader + "</span>";
                $(insertCellHeader).prependTo(grid[row][cell]);
            }
        }
    };
    tableElement.prototype.getSimple = function () {
        var trs = this.element.find('tr');
        var trsChild;
        var grid = {};
        var cells;
        trs.each(function (index, item) {
            if (!grid[index]) {
                grid[index] = {};
            }
            trsChild = item.childNodes;
            cells = 0;
            for (var j = 0, cntJ = trsChild.length; j < cntJ; j++) {
                grid[index][cells++] = trsChild[j];
            }
            var tds = $(item).find("td");
            tds.wrapInner("<span class='tds'></span>")  //셀내용 span 감싸기
        });
        var cellHeader = "";
        for (row in grid) {
            if (row == 0) {
                continue;
            }
            for (cell in grid[row]) {
                if (cell == 0) {
                    continue;
                }
                var cellHeader = $(grid[0][cell]).html();
                var insertCellHeader = "<span class=" + this.options.addheadelement + ">" + cellHeader + "</span>";
                $(insertCellHeader).prependTo(grid[row][cell]);

            }
        }
    };

    tableElement.prototype.removeBoard = function () {
        this.element.find("." + this.options.addheadelement).remove();
        var tds = this.element.find(".tds");
        tds.contents().unwrap(".tds")
    };

    tableElement.prototype.removeSimple = function () {
        this.element.find("." + this.options.addheadelement).remove();
        var tds = this.element.find(".tds");
        tds.contents().unwrap(".tds")
    };


    tableElement.prototype.tableCheck = function () {
        var tableStatus = this.getState();

        if (this.tableStatus !== tableStatus) {
            this.tableStatus = tableStatus;

            switch (this.options.tabletype) {
                case "bbsTable":
                    if (this.tableStatus === "applyRwd") {
                        this.getBoard();
                        this.element.addClass("mobile");
                    } else {
                        this.removeBoard();
                        this.element.removeClass("mobile");
                    }
                    break;
                case "simpleTable":
                    if (this.tableStatus === "applyRwd") {
                        this.getSimple();
                        this.element.addClass("mobile");
                    } else {
                        this.removeSimple();
                        this.element.removeClass("mobile");
                    }
                    break;
                case "block":
                    if (this.tableStatus === "applyRwd") {
                        this.element.addClass("mobile");
                    } else {
                        this.element.removeClass("mobile");
                    }
                    break;
                default:
                    this.getWrap();
                    if (this.tableStatus === "applyRwd") {
                        this.getWidth();
                        this.getIcon();
                        this.element.addClass("mobile");
                        $(window).on('load', $.proxy(this.getIcon, this));
                        $(".table-responsive").on("click", function (e) {
                            $(this).removeClass("icon");
                            $(this).find('.scrollable-icon').remove('');
                        });
                        setTimeout(function () {
                            $('.table-responsive').removeClass("icon");
                            $('.table-responsive').find('.scrollable-icon').remove('');
                        }, 10000);
                    } else {
                        this.removeWidth();
                        this.element.removeClass("mobile");
                    }
                    break;
            }
        }
    };

    function tableRwd(option) {
        return this.each(function () {
            var $this = $(this);
            var data = $this.data("rwd");
            var options = typeof option === "object" && option;

            if (!data) {
                $this.data("rwd", (data = new tableElement(this, options)));
            }
        });
    }
    $.fn.tableRwd = tableRwd;
    if (navigator.appVersion.indexOf("MSIE 8.") === -1) {
        //alert(navigator.appVersion);
        $(window).on("load", function (e) {
            $("[data-table=\"rwd\"]").each(function () {
                var allTableRwd = $(this);
                var data = allTableRwd.data();
                tableRwd.call(allTableRwd, data);
            });
        });
    }
});



/** Air-Datepicker http://t1m0n.name/air-datepicker/docs/#example-custom-content */

(function (window, $, undefined) {
    (function () {
        var locale = document.getElementsByTagName("html")[0].getAttribute("lang");
        var today = new Date();
        var year = today.getFullYear();
        var month = ('0' + (today.getMonth() + 1)).slice(-2);
        var day = ('0' + today.getDate()).slice(-2);
        var dateString = year + '-' + month + '-' + day;
        var VERSION = '2.2.3',
            pluginName = 'datepicker',
            autoInitSelector = '[data-date="datepicker"] .datepicker-here,.date__icon,.date__input',
            $body, $datepickersContainer,
            containerBuilt = false,
            baseTemplate = '' +
                '<div class="datepicker">' +
                '<i class="datepicker--pointer"></i>' +
                '<nav class="datepicker--nav"></nav>' +
                '<div class="datepicker--content"></div>' +
                '</div>',
            defaults = {
                classes: '',
                inline: false,
                language:locale,
                startDate: new Date(),
                firstDay: '',
                weekends: [6, 0],
                dateFormat: '',
                altField: '',
                altFieldDateFormat: '@',
                toggleSelected: true,
                keyboardNav: true,
                position: 'bottom left',
                offset: 12,
                view: 'days',
                minView: 'days',
                showOtherMonths: true,
                selectOtherMonths: true,
                moveToOtherMonthsOnSelect: true,
                showOtherYears: true,
                selectOtherYears: true,
                moveToOtherYearsOnSelect: true,
                minDate: '',
                maxDate: '',
                disableNavWhenOutOfRange: true,
                multipleDates: false, // Boolean or Number
                multipleDatesSeparator: ',',
                range: false,
                todayButton: true,
                clearButton: false,
                closeButton: true,
                showEvent: 'focus',
                autoClose: true,
                monthsField: 'monthsShort',
                prevHtml: '<svg><path d="M 17,12 l -5,5 l 5,5"></path></svg>',
                nextHtml: '<svg><path d="M 14,12 l 5,5 l -5,5"></path></svg>',
                navTitles: {
                    days: '',
                    months: '',
                    years: ''
                },
                // timepicker
                timepicker: false,
                onlyTimepicker: false,
                dateTimeSeparator: ' ',
                timeFormat: '',
                minHours: 0,
                maxHours: 24,
                minMinutes: 0,
                maxMinutes: 59,
                hoursStep: 1,
                minutesStep: 10,
                // events
                onSelect: '',
                onShow: '',
                onHide: '',
                onChangeMonth: '',
                onChangeYear: '',
                onChangeDecade: '',
                onChangeView: '',
                onRenderCell: ''
            },
            hotKeys = {
                'ctrlRight': [17, 39],
                'ctrlUp': [17, 38],
                'ctrlLeft': [17, 37],
                'ctrlDown': [17, 40],
                'shiftRight': [16, 39],
                'shiftUp': [16, 38],
                'shiftLeft': [16, 37],
                'shiftDown': [16, 40],
                'altUp': [18, 38],
                'altRight': [18, 39],
                'altLeft': [18, 37],
                'altDown': [18, 40],
                'ctrlShiftUp': [16, 17, 38]
            },
            datepicker;

        var Datepicker  = function (el, options) {
            this.el = el;
            this.$el = $(el);
            this.button = $(el).find("button");
            this.isInput = $(el).find("input");
            this.inputField = this.isInput ? this.el : this.el.closest(".date").find('input');

            this.opts = $.extend(true, {}, defaults, options, this.$el.data());
            if ($body == undefined) {
                $body = $('body');
            }
            if (!this.opts.startDate) {
                this.opts.startDate = new Date();
            }
            if (this.el.nodeName == 'INPUT') {
                this.elIsInput = true;
            }
            if (this.opts.altField) {
                this.$altField = typeof this.opts.altField == 'string' ? $(this.opts.altField) : this.opts.altField;
            }
            this.inited = false;
            this.visible = false;
            this.silent = false; // Need to prevent unnecessary rendering
            this.currentDate = this.opts.startDate;
            this.currentView = this.opts.view;
            this._createShortCuts();
            this.selectedDates = [];
            this.views = {};
            this.navTitles = this.opts.navTitles;
            this.keys = [];
            this.minRange = '';
            this.maxRange = '';
            this._prevOnSelectValue = '';

            this.init()
        };
        datepicker = Datepicker;
        datepicker.prototype = {
            VERSION: VERSION,
            viewIndexes: ['days', 'months', 'years'],

            init: function () {
                if (!containerBuilt && !this.opts.inline && this.elIsInput) {
                    this._buildDatepickersContainer();
                }
                this._buildBaseHtml();
                this._defineLocale(this.opts.language);
                this._syncWithMinMaxDates();

                if (this.elIsInput) {
                    if (!this.opts.inline) {
                        this._setPositionClasses(this.opts.position);
                        this._bindEvents()
                    }
                    if (this.opts.keyboardNav && !this.opts.onlyTimepicker) {
                        this._bindKeyboardEvents();
                    }
                    this.$datepicker.on('mousedown', this._onMouseDownDatepicker.bind(this));
                    this.$datepicker.on('mouseup', this._onMouseUpDatepicker.bind(this));
                }

                if (this.opts.classes) {
                    this.$datepicker.addClass(this.opts.classes)
                }

                if (this.opts.timepicker) {
                    this.timepicker = new $.fn.datepicker.Timepicker(this, this.opts);
                    this._bindTimepickerEvents();
                }

                if (this.opts.onlyTimepicker) {
                    this.$datepicker.addClass('-only-timepicker-');
                }

                this.views[this.currentView] = new $.fn.datepicker.Body(this, this.currentView, this.opts);
                this.views[this.currentView].show();
                this.nav = new $.fn.datepicker.Navigation(this, this.opts);
                this.view = this.currentView;
                this.$el.on('clickCell.adp', this._onClickCell.bind(this));
                this.$datepicker.on('mouseenter', '.datepicker--cell', this._onMouseEnterCell.bind(this));
                this.$datepicker.on('mouseleave', '.datepicker--cell', this._onMouseLeaveCell.bind(this));
                this.inited = true;
            },
            _createShortCuts: function () {
                this.minDate = this.opts.minDate ? this.opts.minDate : new Date(-8639999913600000);
                this.maxDate = this.opts.maxDate ? this.opts.maxDate : new Date(8639999913600000);
            },

            _bindEvents : function () {
                this.$el.on(this.opts.showEvent + '.adp', this._onShowEvent.bind(this));
                this.$el.on('mouseup.adp', this._onMouseUpEl.bind(this));
                this.$el.on('blur.adp', this._onBlur.bind(this));
                this.$el.on('keyup.adp', this._onKeyUpGeneral.bind(this));
                $(window).on('resize.adp', this._onResize.bind(this));
                $('body').on('mouseup.adp', this._onMouseUpBody.bind(this));
            },

            _bindKeyboardEvents: function () {
                this.$el.on('keydown.adp', this._onKeyDown.bind(this));
                this.$el.on('keyup.adp', this._onKeyUp.bind(this));
                this.$el.on('hotKey.adp', this._onHotKey.bind(this));
            },

            _bindTimepickerEvents: function () {
                this.$el.on('timeChange.adp', this._onTimeChange.bind(this));
            },

            isWeekend: function (day) {
                return this.opts.weekends.indexOf(day) !== -1;
            },
            _defineLocale: function (lang) {
                if (typeof lang == 'string') {
                    this.loc = $.fn.datepicker.language[lang];
                    if (!this.loc) {
                        //console.warn('Can\'t find language "' + lang + '" in Datepicker.language, will use "ru" instead');
                        this.loc = $.extend(true, {}, $.fn.datepicker.language.en)
                    }
                    this.loc = $.extend(true, {}, $.fn.datepicker.language.en, $.fn.datepicker.language[lang])
                } else {
                    this.loc = $.extend(true, {}, $.fn.datepicker.language.en, lang)
                }
                if (this.opts.navTitles) {
                    this.loc.navTitles = this.opts.navTitles
                }
                if (this.opts.dateFormat) {
                    this.loc.dateFormat = this.opts.dateFormat
                }

                if (this.opts.timeFormat) {
                    this.loc.timeFormat = this.opts.timeFormat
                }

                if (this.opts.firstDay !== '') {
                    this.loc.firstDay = this.opts.firstDay
                }

                if (this.opts.timepicker) {
                    this.loc.dateFormat = [this.loc.dateFormat, this.loc.timeFormat].join(this.opts.dateTimeSeparator);
                }

                if (this.opts.onlyTimepicker) {
                    this.loc.dateFormat = this.loc.timeFormat;
                }

                var boundary = this._getWordBoundaryRegExp;
                if (this.loc.timeFormat.match(boundary('aa')) ||
                    this.loc.timeFormat.match(boundary('AA'))
                ) {
                    this.ampm = true;
                }
            },

            _buildDatepickersContainer: function () {
                containerBuilt = true;
                $body.append('<div class="datepickers-container" id="datepickers-container"></div>');
                $datepickersContainer = $('#datepickers-container');
            },

            _buildBaseHtml: function () {
                var $appendTarget,
                    $inline = $('<div class="datepicker-inline">');

                if(this.el.nodeName == 'INPUT') {
                    if (!this.opts.inline) {
                        $appendTarget = $datepickersContainer;
                    } else {
                        $appendTarget = $inline.insertAfter(this.$el)
                    }
                } else {
                    $appendTarget = $inline.appendTo(this.$el)
                }

                this.$datepicker = $(baseTemplate).appendTo($appendTarget);
                this.$content = $('.datepicker--content', this.$datepicker);
                this.$nav = $('.datepicker--nav', this.$datepicker);
            },

            _triggerOnChange: function () {
                if (!this.selectedDates.length) {
                    // Prevent from triggering multiple onSelect callback with same argument (empty string) in IE10-11
                    if (this._prevOnSelectValue === '') return;
                    this._prevOnSelectValue = '';
                    return this.opts.onSelect('', '', this);
                }

                var selectedDates = this.selectedDates,
                    parsedSelected = datepicker.getParsedDate(selectedDates[0]),
                    formattedDates,
                    _this = this,
                    dates = new Date(
                        parsedSelected.year,
                        parsedSelected.month,
                        parsedSelected.date,
                        parsedSelected.hours,
                        parsedSelected.minutes
                    );

                formattedDates = selectedDates.map(function (date) {
                    return _this.formatDate(_this.loc.dateFormat, date)
                }).join(this.opts.multipleDatesSeparator);
                // Create new dates array, to separate it from original selectedDates
                if (this.opts.multipleDates || this.opts.range) {
                    dates = selectedDates.map(function(date) {
                        var parsedDate = datepicker.getParsedDate(date);
                        return new Date(
                            parsedDate.year,
                            parsedDate.month,
                            parsedDate.date,
                            parsedDate.hours,
                            parsedDate.minutes
                        );
                    })
                }

                this._prevOnSelectValue = formattedDates;
                this.opts.onSelect(formattedDates, dates, this);
            },

            next: function () {
                var d = this.parsedDate,
                    o = this.opts;
                switch (this.view) {
                    case 'days':
                        this.date = new Date(d.year, d.month + 1, 1);
                        if (o.onChangeMonth) o.onChangeMonth(this.parsedDate.month, this.parsedDate.year);
                        break;
                    case 'months':
                        this.date = new Date(d.year + 1, d.month, 1);
                        if (o.onChangeYear) o.onChangeYear(this.parsedDate.year);
                        break;
                    case 'years':
                        this.date = new Date(d.year + 10, 0, 1);
                        if (o.onChangeDecade) o.onChangeDecade(this.curDecade);
                        break;
                }
            },

            prev: function () {
                var d = this.parsedDate,
                    o = this.opts;
                switch (this.view) {
                    case 'days':
                        this.date = new Date(d.year, d.month - 1, 1);
                        if (o.onChangeMonth) o.onChangeMonth(this.parsedDate.month, this.parsedDate.year);
                        break;
                    case 'months':
                        this.date = new Date(d.year - 1, d.month, 1);
                        if (o.onChangeYear) o.onChangeYear(this.parsedDate.year);
                        break;
                    case 'years':
                        this.date = new Date(d.year - 10, 0, 1);
                        if (o.onChangeDecade) o.onChangeDecade(this.curDecade);
                        break;
                }
            },

            formatDate: function (string, date) {
                date = date || this.date;
                var result = string,
                    boundary = this._getWordBoundaryRegExp,
                    locale = this.loc,
                    leadingZero = datepicker.getLeadingZeroNum,
                    decade = datepicker.getDecade(date),
                    d = datepicker.getParsedDate(date),
                    fullHours = d.fullHours,
                    hours = d.hours,
                    ampm = string.match(boundary('aa')) || string.match(boundary('AA')),
                    dayPeriod = 'am',
                    replacer = this._replacer,
                    validHours;

                //console.log(result);

                if (this.opts.timepicker && this.timepicker && ampm) {
                    validHours = this.timepicker._getValidHoursFromDate(date, ampm);
                    fullHours = leadingZero(validHours.hours);
                    hours = validHours.hours;
                    dayPeriod = validHours.dayPeriod;
                }

                switch (true) {
                    case /@/.test(result):
                        result = result.replace(/@/, date.getTime());
                    case /aa/.test(result):
                        result = replacer(result, boundary('aa'), dayPeriod);
                    case /AA/.test(result):
                        result = replacer(result, boundary('AA'), dayPeriod.toUpperCase());
                    case /dd/.test(result):
                        result = replacer(result, boundary('dd'), d.fullDate);
                    case /d/.test(result):
                        result = replacer(result, boundary('d'), d.date);
                    case /DD/.test(result):
                        result = replacer(result, boundary('DD'), locale.days[d.day]);
                    case /D/.test(result):
                        result = replacer(result, boundary('D'), locale.daysShort[d.day]);
                    case /mm/.test(result):
                        result = replacer(result, boundary('mm'), d.fullMonth);
                    case /m/.test(result):
                        result = replacer(result, boundary('m'), d.month + 1);
                    case /MM/.test(result):
                        result = replacer(result, boundary('MM'), this.loc.months[d.month]);
                    case /M/.test(result):
                        result = replacer(result, boundary('M'), locale.monthsShort[d.month]);
                    case /ii/.test(result):
                        result = replacer(result, boundary('ii'), d.fullMinutes);
                    case /i/.test(result):
                        result = replacer(result, boundary('i'), d.minutes);
                    case /hh/.test(result):
                        result = replacer(result, boundary('hh'), fullHours);
                    case /h/.test(result):
                        result = replacer(result, boundary('h'), hours);
                    case /yyyy/.test(result):
                        result = replacer(result, boundary('yyyy'), d.year);
                    case /yyyy1/.test(result):
                        result = replacer(result, boundary('yyyy1'), decade[0]);
                    case /yyyy2/.test(result):
                        result = replacer(result, boundary('yyyy2'), decade[1]);
                    case /yy/.test(result):
                        result = replacer(result, boundary('yy'), d.year.toString().slice(-2));
                }

                return result;
            },
            _replacer: function (str, reg, data) {
                return str.replace(reg, function (match, p1,p2,p3) {
                    return p1 + data + p3;
                })
            },
            _getWordBoundaryRegExp: function (sign) {
                var symbols = '\\s|\\.|-|/|\\\\|,|\\$|\\!|\\?|:|;';

                return new RegExp('(^|>|' + symbols + ')(' + sign + ')($|<|' + symbols + ')', 'g');
            },
            selectDate: function (date) {
                var _this = this,
                    opts = _this.opts,
                    d = _this.parsedDate,
                    selectedDates = _this.selectedDates,
                    len = selectedDates.length,
                    newDate = '';

                if (Array.isArray(date)) {
                    date.forEach(function (d) {
                        _this.selectDate(d)
                    });
                    return;
                }

                if (!(date instanceof Date)) return;

                this.lastSelectedDate = date;

                // Set new time values from Date
                if (this.timepicker) {
                    this.timepicker._setTime(date);
                }

                // On this step timepicker will set valid values in it's instance
                _this._trigger('selectDate', date);

                // Set correct time values after timepicker's validation
                // Prevent from setting hours or minutes which values are lesser then `min` value or
                // greater then `max` value
                if (this.timepicker) {
                    date.setHours(this.timepicker.hours);
                    date.setMinutes(this.timepicker.minutes)
                }

                if (_this.view == 'days') {
                    if (date.getMonth() != d.month && opts.moveToOtherMonthsOnSelect) {
                        newDate = new Date(date.getFullYear(), date.getMonth(), 1);
                    }
                }

                if (_this.view == 'years') {
                    if (date.getFullYear() != d.year && opts.moveToOtherYearsOnSelect) {
                        newDate = new Date(date.getFullYear(), 0, 1);
                    }
                }

                if (newDate) {
                    _this.silent = true;
                    _this.date = newDate;
                    _this.silent = false;
                    _this.nav._render()
                }

                if (opts.multipleDates && !opts.range) { // Set priority to range functionality
                    if (len === opts.multipleDates) return;
                    if (!_this._isSelected(date)) {
                        _this.selectedDates.push(date);
                    }
                } else if (opts.range) {
                    if (len == 2) {
                        _this.selectedDates = [date];
                        _this.minRange = date;
                        _this.maxRange = '';
                    } else if (len == 1) {
                        _this.selectedDates.push(date);
                        if (!_this.maxRange){
                            _this.maxRange = date;
                        } else {
                            _this.minRange = date;
                        }
                        // Swap dates if they were selected via dp.selectDate() and second date was smaller then first
                        if (datepicker.bigger(_this.maxRange, _this.minRange)) {
                            _this.maxRange = _this.minRange;
                            _this.minRange = date;
                        }
                        _this.selectedDates = [_this.minRange, _this.maxRange]

                    } else {
                        _this.selectedDates = [date];
                        _this.minRange = date;
                    }
                } else {
                    _this.selectedDates = [date];
                }

                _this._setInputValue();

                if (opts.onSelect) {
                    _this._triggerOnChange();
                }

                if (opts.autoClose && !this.timepickerIsActive) {
                    if (!opts.multipleDates && !opts.range) {
                        _this.hide();
                    } else if (opts.range && _this.selectedDates.length == 2) {
                        _this.hide();
                    }
                }

                _this.views[this.currentView]._render()
            },
            removeDate: function (date) {
                var selected = this.selectedDates,
                    _this = this;

                if (!(date instanceof Date)) return;

                return selected.some(function (curDate, i) {
                    if (datepicker.isSame(curDate, date)) {
                        selected.splice(i, 1);
                        if (!_this.selectedDates.length) {
                            _this.minRange = '';
                            _this.maxRange = '';
                            _this.lastSelectedDate = '';
                        } else {
                            _this.lastSelectedDate = _this.selectedDates[_this.selectedDates.length - 1];
                        }
                        _this.views[_this.currentView]._render();
                        _this._setInputValue();
                        if (_this.opts.onSelect) {
                            _this._triggerOnChange();
                        }

                        return true
                    }
                })
            },
            today: function () {
                this.silent = true;
                this.view = this.opts.minView;
                this.silent = false;
                this.date = new Date();

                if (this.opts.todayButton instanceof Date) {
                    this.selectDate(this.opts.todayButton)
                }
            },
            close: function () {
                this.hide();
            },
            clear: function () {
                this.selectedDates = [];
                this.minRange = '';
                this.maxRange = '';
                this.views[this.currentView]._render();
                this._setInputValue();
                if (this.opts.onSelect) {
                    this._triggerOnChange()
                }
            },
            /**
             * Updates datepicker options
             * @param {String|Object} param - parameter's name to update. If object then it will extend current options
             * @param {String|Number|Object} [value] - new param value
             */
            update: function (param, value) {
                var len = arguments.length,
                    lastSelectedDate = this.lastSelectedDate;
                if (len == 2) {
                    this.opts[param] = value;
                } else if (len == 1 && typeof param == 'object') {
                    this.opts = $.extend(true, this.opts, param)
                }
                this._createShortCuts();
                this._syncWithMinMaxDates();
                this._defineLocale(this.opts.language);
                this.nav._addButtonsIfNeed();
                if (!this.opts.onlyTimepicker) this.nav._render();
                this.views[this.currentView]._render();
                if (this.elIsInput && !this.opts.inline) {
                    this._setPositionClasses(this.opts.position);
                    if (this.visible) {
                        this.setPosition(this.opts.position)
                    }
                }
                if (this.opts.classes) {
                    this.$datepicker.addClass(this.opts.classes)
                }
                if (this.opts.onlyTimepicker) {
                    this.$datepicker.addClass('-only-timepicker-');
                }
                if (this.opts.timepicker) {
                    if (lastSelectedDate) this.timepicker._handleDate(lastSelectedDate);
                    this.timepicker._updateRanges();
                    this.timepicker._updateCurrentTime();
                    // Change hours and minutes if it's values have been changed through min/max hours/minutes
                    if (lastSelectedDate) {
                        lastSelectedDate.setHours(this.timepicker.hours);
                        lastSelectedDate.setMinutes(this.timepicker.minutes);
                    }
                }
                this._setInputValue();
                return this;
            },
            _syncWithMinMaxDates: function () {
                var curTime = this.date.getTime();
                this.silent = true;
                if (this.minTime > curTime) {
                    this.date = this.minDate;
                }
                if (this.maxTime < curTime) {
                    this.date = this.maxDate;
                }
                this.silent = false;
            },
            _isSelected: function (checkDate, cellType) {
                var res = false;
                this.selectedDates.some(function (date) {
                    if (datepicker.isSame(date, checkDate, cellType)) {
                        res = date;
                        return true;
                    }
                });
                return res;
            },
            _setInputValue: function () {
                var _this = this,
                    opts = _this.opts,
                    format = _this.loc.dateFormat,
                    altFormat = opts.altFieldDateFormat,
                    value = _this.selectedDates.map(function (date) {
                        return _this.formatDate(format, date)
                    }),
                    altValues;
                if (opts.altField && _this.$altField.length) {
                    altValues = this.selectedDates.map(function (date) {
                        return _this.formatDate(altFormat, date)
                    });
                    altValues = altValues.join(this.opts.multipleDatesSeparator);
                    this.$altField.val(altValues);
                }
                value = value.join(this.opts.multipleDatesSeparator);
                this.$el.val(value)
            },
            /**
             * Check if date is between minDate and maxDate
             * @param date {object} - date object
             * @param type {string} - cell type
             * @returns {boolean}
             * @private
             */
            _isInRange: function (date, type) {
                var time = date.getTime(),
                    d = datepicker.getParsedDate(date),
                    min = datepicker.getParsedDate(this.minDate),
                    max = datepicker.getParsedDate(this.maxDate),
                    dMinTime = new Date(d.year, d.month, min.date).getTime(),
                    dMaxTime = new Date(d.year, d.month, max.date).getTime(),
                    types = {
                        day: time >= this.minTime && time <= this.maxTime,
                        month: dMinTime >= this.minTime && dMaxTime <= this.maxTime,
                        year: d.year >= min.year && d.year <= max.year
                    };
                return type ? types[type] : types.day
            },
            _getDimensions: function ($el) {
                var offset = $el.offset();
                return {
                    width: $el.outerWidth(),
                    height: $el.outerHeight(),
                    left: offset.left,
                    top: offset.top
                }
            },
            _getDateFromCell: function (cell) {
                var curDate = this.parsedDate,
                    year = cell.data('year') || curDate.year,
                    month = cell.data('month') == undefined ? curDate.month : cell.data('month'),
                    date = cell.data('date') || 1;
                return new Date(year, month, date);
            },
            _setPositionClasses: function (pos) {
                pos = pos.split(' ');
                var main = pos[0],
                    sec = pos[1],
                    classes = 'datepicker -' + main + '-' + sec + '- -from-' + main + '-';
                if (this.visible) classes += ' active';
                this.$datepicker
                    .removeAttr('class')
                    .addClass(classes);
            },
            setPosition: function (position) {
                position = position || this.opts.position;
                var dims = this._getDimensions(this.$el),
                    selfDims = this._getDimensions(this.$datepicker),
                    pos = position.split(' '),
                    top, left,
                    offset = this.opts.offset,
                    main = pos[0],
                    secondary = pos[1];
                switch (main) {
                    case 'top':
                        top = dims.top - selfDims.height - offset;
                        break;
                    case 'right':
                        left = dims.left + dims.width + offset;
                        break;
                    case 'bottom':
                        top = dims.top + dims.height + offset;
                        break;
                    case 'left':
                        left = dims.left - selfDims.width - offset;
                        break;
                }

                switch(secondary) {
                    case 'top':
                        top = dims.top;
                        break;
                    case 'right':
                        left = dims.left + dims.width - selfDims.width;
                        break;
                    case 'bottom':
                        top = dims.top + dims.height - selfDims.height;
                        break;
                    case 'left':
                        left = dims.left;
                        break;
                    case 'center':
                        if (/left|right/.test(main)) {
                            top = dims.top + dims.height/2 - selfDims.height/2;
                        } else {
                            left = dims.left + dims.width/2 - selfDims.width/2;
                        }
                }
                this.$datepicker
                    .css({
                        left: left,
                        top: top
                    })
            },
            show: function () {
                var onShow = this.opts.onShow;

                this.setPosition(this.opts.position);
                this.$datepicker.addClass('active');
                this.visible = true;

                if (onShow) {
                    this._bindVisionEvents(onShow)
                }
            },

            hide: function () {
                var onHide = this.opts.onHide;

                this.$datepicker
                    .removeClass('active')
                    .css({
                        left: '-100000px'
                    });

                this.focused = '';
                this.keys = [];

                this.inFocus = false;
                this.visible = false;
                this.$el.blur();

                if (onHide) {
                    this._bindVisionEvents(onHide)
                }
            },
            down: function (date) {
                this._changeView(date, 'down');
            },

            up: function (date) {
                this._changeView(date, 'up');
            },

            _bindVisionEvents: function (event) {
                this.$datepicker.off('transitionend.dp');
                event(this, false);
                this.$datepicker.one('transitionend.dp', event.bind(this, this, true))
            },

            _changeView: function (date, dir) {
                date = date || this.focused || this.date;

                var nextView = dir == 'up' ? this.viewIndex + 1 : this.viewIndex - 1;
                if (nextView > 2) nextView = 2;
                if (nextView < 0) nextView = 0;

                this.silent = true;
                this.date = new Date(date.getFullYear(), date.getMonth(), 1);
                this.silent = false;
                this.view = this.viewIndexes[nextView];

            },

            _handleHotKey: function (key) {
                var date = datepicker.getParsedDate(this._getFocusedDate()),
                    focusedParsed,
                    o = this.opts,
                    newDate,
                    totalDaysInNextMonth,
                    monthChanged = false,
                    yearChanged = false,
                    decadeChanged = false,
                    y = date.year,
                    m = date.month,
                    d = date.date;

                switch (key) {
                    case 'ctrlRight':
                    case 'ctrlUp':
                        m += 1;
                        monthChanged = true;
                        break;
                    case 'ctrlLeft':
                    case 'ctrlDown':
                        m -= 1;
                        monthChanged = true;
                        break;
                    case 'shiftRight':
                    case 'shiftUp':
                        yearChanged = true;
                        y += 1;
                        break;
                    case 'shiftLeft':
                    case 'shiftDown':
                        yearChanged = true;
                        y -= 1;
                        break;
                    case 'altRight':
                    case 'altUp':
                        decadeChanged = true;
                        y += 10;
                        break;
                    case 'altLeft':
                    case 'altDown':
                        decadeChanged = true;
                        y -= 10;
                        break;
                    case 'ctrlShiftUp':
                        this.up();
                        break;
                }

                totalDaysInNextMonth = datepicker.getDaysCount(new Date(y,m));
                newDate = new Date(y,m,d);

                // If next month has less days than current, set date to total days in that month
                if (totalDaysInNextMonth < d) d = totalDaysInNextMonth;

                // Check if newDate is in valid range
                if (newDate.getTime() < this.minTime) {
                    newDate = this.minDate;
                } else if (newDate.getTime() > this.maxTime) {
                    newDate = this.maxDate;
                }

                this.focused = newDate;

                focusedParsed = datepicker.getParsedDate(newDate);
                if (monthChanged && o.onChangeMonth) {
                    o.onChangeMonth(focusedParsed.month, focusedParsed.year)
                }
                if (yearChanged && o.onChangeYear) {
                    o.onChangeYear(focusedParsed.year)
                }
                if (decadeChanged && o.onChangeDecade) {
                    o.onChangeDecade(this.curDecade)
                }
            },

            _registerKey: function (key) {
                var exists = this.keys.some(function (curKey) {
                    return curKey == key;
                });

                if (!exists) {
                    this.keys.push(key)
                }
            },

            _unRegisterKey: function (key) {
                var index = this.keys.indexOf(key);

                this.keys.splice(index, 1);
            },

            _isHotKeyPressed: function () {
                var currentHotKey,
                    found = false,
                    _this = this,
                    pressedKeys = this.keys.sort();

                for (var hotKey in hotKeys) {
                    currentHotKey = hotKeys[hotKey];
                    if (pressedKeys.length != currentHotKey.length) continue;

                    if (currentHotKey.every(function (key, i) { return key == pressedKeys[i]})) {
                        _this._trigger('hotKey', hotKey);
                        found = true;
                    }
                }

                return found;
            },

            _trigger: function (event, args) {
                this.$el.trigger(event, args)
            },

            _focusNextCell: function (keyCode, type) {
                type = type || this.cellType;

                var date = datepicker.getParsedDate(this._getFocusedDate()),
                    y = date.year,
                    m = date.month,
                    d = date.date;

                if (this._isHotKeyPressed()){
                    return;
                }

                switch(keyCode) {
                    case 37: // left
                        type == 'day' ? (d -= 1) : '';
                        type == 'month' ? (m -= 1) : '';
                        type == 'year' ? (y -= 1) : '';
                        break;
                    case 38: // up
                        type == 'day' ? (d -= 7) : '';
                        type == 'month' ? (m -= 3) : '';
                        type == 'year' ? (y -= 4) : '';
                        break;
                    case 39: // right
                        type == 'day' ? (d += 1) : '';
                        type == 'month' ? (m += 1) : '';
                        type == 'year' ? (y += 1) : '';
                        break;
                    case 40: // down
                        type == 'day' ? (d += 7) : '';
                        type == 'month' ? (m += 3) : '';
                        type == 'year' ? (y += 4) : '';
                        break;
                }

                var nd = new Date(y,m,d);
                if (nd.getTime() < this.minTime) {
                    nd = this.minDate;
                } else if (nd.getTime() > this.maxTime) {
                    nd = this.maxDate;
                }

                this.focused = nd;

            },

            _getFocusedDate: function () {
                var focused  = this.focused || this.selectedDates[this.selectedDates.length - 1],
                    d = this.parsedDate;

                if (!focused) {
                    switch (this.view) {
                        case 'days':
                            focused = new Date(d.year, d.month, new Date().getDate());
                            break;
                        case 'months':
                            focused = new Date(d.year, d.month, 1);
                            break;
                        case 'years':
                            focused = new Date(d.year, 0, 1);
                            break;
                    }
                }

                return focused;
            },

            _getCell: function (date, type) {
                type = type || this.cellType;

                var d = datepicker.getParsedDate(date),
                    selector = '.datepicker--cell[data-year="' + d.year + '"]',
                    $cell;
                switch (type) {
                    case 'month':
                        selector = '[data-month="' + d.month + '"]';
                        break;
                    case 'day':
                        selector += '[data-month="' + d.month + '"][data-date="' + d.date + '"]';
                        break;
                }
                $cell = this.views[this.currentView].$el.find(selector);

                return $cell.length ? $cell : $('');
            },

            destroy: function () {
                var _this = this;
                _this.$el
                    .off('.adp')
                    .data('datepicker', '');

                _this.selectedDates = [];
                _this.focused = '';
                _this.views = {};
                _this.keys = [];
                _this.minRange = '';
                _this.maxRange = '';

                if (_this.opts.inline || !_this.elIsInput) {
                    _this.$datepicker.closest('.datepicker-inline').remove();
                } else {
                    _this.$datepicker.remove();
                }
            },

            _handleAlreadySelectedDates: function (alreadySelected, selectedDate) {
                if (this.opts.range) {
                    if (!this.opts.toggleSelected) {
                        // Add possibility to select same date when range is true
                        if (this.selectedDates.length != 2) {
                            this._trigger('clickCell', selectedDate);
                        }
                    } else {
                        this.removeDate(selectedDate);
                    }
                } else if (this.opts.toggleSelected){
                    this.removeDate(selectedDate);
                }

                // Change last selected date to be able to change time when clicking on this cell
                if (!this.opts.toggleSelected) {
                    this.lastSelectedDate = alreadySelected;
                    if (this.opts.timepicker) {
                        this.timepicker._setTime(alreadySelected);
                        this.timepicker.update();
                    }
                }
            },

            _onShowEvent: function (e) {
                if (!this.visible) {
                    this.show();
                }
            },

            _onBlur: function () {
                if (!this.inFocus && this.visible) {
                    this.hide();
                }
            },

            _onMouseDownDatepicker: function (e) {
                this.inFocus = true;
            },

            _onMouseUpDatepicker: function (e) {
                this.inFocus = false;
                e.originalEvent.inFocus = true;
                if (!e.originalEvent.timepickerFocus) this.$el.focus();
            },

            _onKeyUpGeneral: function (e) {
                var val = this.$el.val();

                if (!val) {
                    this.clear();
                }
            },

            _onResize: function () {
                if (this.visible) {
                    this.setPosition();
                }
            },

            _onMouseUpBody: function (e) {
                if (e.originalEvent.inFocus) return;

                if (this.visible && !this.inFocus) {
                    this.hide();
                }
            },

            _onMouseUpEl: function (e) {
                e.originalEvent.inFocus = true;
                setTimeout(this._onKeyUpGeneral.bind(this),4);
            },

            _onKeyDown: function (e) {
                var code = e.which;
                this._registerKey(code);

                // Arrows
                if (code >= 37 && code <= 40) {
                    e.preventDefault();
                    this._focusNextCell(code);
                }

                // Enter
                if (code == 13) {
                    if (this.focused) {
                        if (this._getCell(this.focused).hasClass('-disabled-')) return;
                        if (this.view != this.opts.minView) {
                            this.down()
                        } else {
                            var alreadySelected = this._isSelected(this.focused, this.cellType);

                            if (!alreadySelected) {
                                if (this.timepicker) {
                                    this.focused.setHours(this.timepicker.hours);
                                    this.focused.setMinutes(this.timepicker.minutes);
                                }
                                this.selectDate(this.focused);
                                return;
                            }
                            this._handleAlreadySelectedDates(alreadySelected, this.focused)
                        }
                    }
                }

                // Esc
                if (code == 27) {
                    this.hide();
                }
            },

            _onKeyUp: function (e) {
                var code = e.which;
                this._unRegisterKey(code);
            },

            _onHotKey: function (e, hotKey) {
                this._handleHotKey(hotKey);
            },

            _onMouseEnterCell: function (e) {
                var $cell = $(e.target).closest('.datepicker--cell'),
                    date = this._getDateFromCell($cell);
                // Prevent from unnecessary rendering and setting new currentDate
                this.silent = true;

                if (this.focused) {
                    this.focused = ''
                }

                $cell.addClass('-focus-');

                this.focused = date;
                this.silent = false;

                if (this.opts.range && this.selectedDates.length == 1) {
                    this.minRange = this.selectedDates[0];
                    this.maxRange = '';
                    if (datepicker.less(this.minRange, this.focused)) {
                        this.maxRange = this.minRange;
                        this.minRange = '';
                    }
                    this.views[this.currentView]._update();
                }
            },

            _onMouseLeaveCell: function (e) {
                var $cell = $(e.target).closest('.datepicker--cell');

                $cell.removeClass('-focus-');

                this.silent = true;
                this.focused = '';
                this.silent = false;
            },

            _onTimeChange: function (e, h, m) {
                var date = new Date(),
                    selectedDates = this.selectedDates,
                    selected = false;

                if (selectedDates.length) {
                    selected = true;
                    date = this.lastSelectedDate;
                }

                date.setHours(h);
                date.setMinutes(m);

                if (!selected && !this._getCell(date).hasClass('-disabled-')) {
                    this.selectDate(date);
                } else {
                    this._setInputValue();
                    if (this.opts.onSelect) {
                        this._triggerOnChange();
                    }
                }
            },

            _onClickCell: function (e, date) {
                if (this.timepicker) {
                    date.setHours(this.timepicker.hours);
                    date.setMinutes(this.timepicker.minutes);
                }
                this.selectDate(date);
            },

            set focused(val) {
                if (!val && this.focused) {
                    var $cell = this._getCell(this.focused);

                    if ($cell.length) {
                        $cell.removeClass('-focus-')
                    }
                }
                this._focused = val;
                if (this.opts.range && this.selectedDates.length == 1) {
                    this.minRange = this.selectedDates[0];
                    this.maxRange = '';
                    if (datepicker.less(this.minRange, this._focused)) {
                        this.maxRange = this.minRange;
                        this.minRange = '';
                    }
                }
                if (this.silent) return;
                this.date = val;
            },

            get focused() {
                return this._focused;
            },

            get parsedDate() {
                return datepicker.getParsedDate(this.date);
            },

            set date (val) {
                if (!(val instanceof Date)) return;

                this.currentDate = val;

                if (this.inited && !this.silent) {
                    this.views[this.view]._render();
                    this.nav._render();
                    if (this.visible && this.elIsInput) {
                        this.setPosition();
                    }
                }
                return val;
            },

            get date () {
                return this.currentDate
            },

            set view (val) {
                this.viewIndex = this.viewIndexes.indexOf(val);

                if (this.viewIndex < 0) {
                    return;
                }

                this.prevView = this.currentView;
                this.currentView = val;

                if (this.inited) {
                    if (!this.views[val]) {
                        this.views[val] = new  $.fn.datepicker.Body(this, val, this.opts)
                    } else {
                        this.views[val]._render();
                    }

                    this.views[this.prevView].hide();
                    this.views[val].show();
                    this.nav._render();

                    if (this.opts.onChangeView) {
                        this.opts.onChangeView(val)
                    }
                    if (this.elIsInput && this.visible) this.setPosition();
                }

                return val
            },

            get view() {
                return this.currentView;
            },

            get cellType() {
                return this.view.substring(0, this.view.length - 1)
            },

            get minTime() {
                var min = datepicker.getParsedDate(this.minDate);
                return new Date(min.year, min.month, min.date).getTime()
            },

            get maxTime() {
                var max = datepicker.getParsedDate(this.maxDate);
                return new Date(max.year, max.month, max.date).getTime()
            },

            get curDecade() {
                return datepicker.getDecade(this.date)
            }
        };
        //  Utils
        // -------------------------------------------------
        datepicker.getDaysCount = function (date) {
            return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
        };
        datepicker.getParsedDate = function (date) {
            return {
                year: date.getFullYear(),
                month: date.getMonth(),
                fullMonth: (date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1, // One based
                date: date.getDate(),
                fullDate: date.getDate() < 10 ? '0' + date.getDate() : date.getDate(),
                day: date.getDay(),
                hours: date.getHours(),
                fullHours:  date.getHours() < 10 ? '0' + date.getHours() :  date.getHours() ,
                minutes: date.getMinutes(),
                fullMinutes:  date.getMinutes() < 10 ? '0' + date.getMinutes() :  date.getMinutes()
            }
        };

        datepicker.getDecade = function (date) {
            var firstYear = Math.floor(date.getFullYear() / 10) * 10;

            return [firstYear, firstYear + 9];
        };

        datepicker.template = function (str, data) {
            return str.replace(/#\{([\w]+)\}/g, function (source, match) {
                if (data[match] || data[match] === 0) {
                    return data[match]
                }
            });
        };

        datepicker.isSame = function (date1, date2, type) {
            if (!date1 || !date2) return false;
            var d1 = datepicker.getParsedDate(date1),
                d2 = datepicker.getParsedDate(date2),
                _type = type ? type : 'day',

                conditions = {
                    day: d1.date == d2.date && d1.month == d2.month && d1.year == d2.year,
                    month: d1.month == d2.month && d1.year == d2.year,
                    year: d1.year == d2.year
                };

            return conditions[_type];
        };

        datepicker.less = function (dateCompareTo, date, type) {
            if (!dateCompareTo || !date) return false;
            return date.getTime() < dateCompareTo.getTime();
        };

        datepicker.bigger = function (dateCompareTo, date, type) {
            if (!dateCompareTo || !date) return false;
            return date.getTime() > dateCompareTo.getTime();
        };

        datepicker.getLeadingZeroNum = function (num) {
            return parseInt(num) < 10 ? '0' + num : num;
        };

        /**
         * Returns copy of date with hours and minutes equals to 0
         * @param date {Date}
         */
        datepicker.resetTime = function (date) {
            if (typeof date != 'object') return;
            date = datepicker.getParsedDate(date);
            return new Date(date.year, date.month, date.date)
        };

        $.fn.datepicker = function ( options ) {
            return this.each(function () {
                if (!$.data(this, pluginName)) {
                    $.data(this,  pluginName, new Datepicker( this, options ));
                } else {
                    var _this = $.data(this, pluginName);

                    _this.opts = $.extend(true, _this.opts, options);
                    _this.update();
                }
            });
        };
        $.fn.datepicker.Constructor = datepicker;
        datepicker = Datepicker;
        $.fn.datepicker.language = {
            en: {
                days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
                daysShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
                daysMin: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
                months: ['January','February','March','April','May','June', 'July','August','September','October','November','December'],
                monthsShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
                year: "",
                yearCentury: "",
                prevtitle: 'prev',
                nexttitle: 'next',
                today: 'Today',
                clear: 'Clear',
                close: 'Close',
                dateFormat: 'yyyy-mm-dd',
                timeFormat: 'hh:ii',
                firstDay: 0,
                navTitles: {
                    days: '<i>MM</i> / <i>yyyy</i>',
                    months: '<i>yyyy</i>',
                    years: '<i>yyyy1</i> - <i>yyyy2</i>'
                },
            },
            ko: {
                days: ['일요일', '월요일', '화요일', '수요일', '목요일', '금요일', '토요일'],
                daysShort: ['일', '월', '화', '수', '목', '금', '토'],
                daysMin: ['일', '월', '화', '수', '목', '금', '토'],
                months: ['01월','02월','03월','04월','05월','06월', '07월','08월','09월','10월','11월','12월'],
                monthsShort: ['01월','02월','03월','04월','05월','06월', '07월','08월','09월','10월','11월','12월'],
                year: "년",
                yearCentury: "년대",
                prevtitle: '이전 이동',
                nexttitle: '다음 이동',
                today: '오늘',
                clear: '지우기',
                close: "닫기",
                dateFormat: 'yyyy-mm-dd',
                timeFormat: 'hh:ii',
                firstDay: 0,
                navTitles: {
                    days: ' <i>yyyy</i>년<i>MM</i>',
                    months: '<i>yyyy</i>년',
                    years: '<i>yyyy1</i>년 - <i>yyyy2</i>년'
                },

            }
        };

        /*
        $(function () {
            $(autoInitSelector).datepicker();
        })
        */
    })();
    (function () {
        var templates = {
                days:'' +
                    '<div class="datepicker--days datepicker--body">' +
                    '<div class="datepicker--days-names"></div>' +
                    '<div class="datepicker--cells datepicker--cells-days"></div>' +
                    '</div>',
                months: '' +
                    '<div class="datepicker--months datepicker--body">' +
                    '<div class="datepicker--cells datepicker--cells-months"></div>' +
                    '</div>',
                years: '' +
                    '<div class="datepicker--years datepicker--body">' +
                    '<div class="datepicker--cells datepicker--cells-years"></div>' +
                    '</div>'
            },
            datepicker = $.fn.datepicker,
            dp = datepicker.Constructor;

        datepicker.Body = function (d, type, opts) {
            this.d = d;
            this.type = type;
            this.opts = opts;
            this.$el = $('');

            if (this.opts.onlyTimepicker) return;
            this.init();
        };
        datepicker.Body.prototype = {
            init: function () {
                this._buildBaseHtml();
                this._render();
                this._bindEvents();
            },

            _bindEvents: function () {
                this.$el.on('click', '.datepicker--cell', $.proxy(this._onClickCell, this));
            },

            _buildBaseHtml: function () {
                this.$el = $(templates[this.type]).appendTo(this.d.$content);
                this.$names = $('.datepicker--days-names', this.$el);
                this.$cells = $('.datepicker--cells', this.$el);
            },
            _getDayNamesHtml: function (firstDay, curDay, html, i) {
                curDay = curDay != undefined ? curDay : firstDay;
                html = html ? html : '';
                i = i != undefined ? i : 0;
                if (i > 7) return html;
                if (curDay == 7) return this._getDayNamesHtml(firstDay, 0, html, ++i);

                html += '<div class="datepicker--day-name' + (this.d.isWeekend(curDay) ? " -weekend-" : "") + '">' + this.d.loc.daysMin[curDay] + '</div>';

                return this._getDayNamesHtml(firstDay, ++curDay, html, ++i);
            },

            _getCellContents: function (date, type) {
                var classes = "datepicker--cell datepicker--cell-" + type,
                    currentDate = new Date(),
                    parent = this.d,
                    minRange = dp.resetTime(parent.minRange),
                    maxRange = dp.resetTime(parent.maxRange),
                    opts = parent.opts,
                    d = dp.getParsedDate(date),
                    render = {},
                    html = d.date;

                switch (type) {
                    case 'day':
                        if (parent.isWeekend(d.day)) classes += " -weekend-";
                        if (d.month != this.d.parsedDate.month) {
                            classes += " -other-month-";
                            if (!opts.selectOtherMonths) {
                                classes += " -disabled-";
                            }
                            if (!opts.showOtherMonths) html = '';
                        }
                        break;
                    case 'month':
                        html = parent.loc[parent.opts.monthsField][d.month];
                        break;
                    case 'year':
                        var decade = parent.curDecade;
                        html = d.year;
                        if (d.year < decade[0] || d.year > decade[1]) {
                            classes += ' -other-decade-';
                            if (!opts.selectOtherYears) {
                                classes += " -disabled-";
                            }
                            if (!opts.showOtherYears) html = '';
                        }
                        break;
                }

                if (opts.onRenderCell) {
                    render = opts.onRenderCell(date, type) || {};
                    html = render.html ? render.html : html;
                    classes += render.classes ? ' ' + render.classes : '';
                }

                if (opts.range) {
                    if (dp.isSame(minRange, date, type)) classes += ' -range-from-';
                    if (dp.isSame(maxRange, date, type)) classes += ' -range-to-';

                    if (parent.selectedDates.length == 1 && parent.focused) {
                        if (
                            (dp.bigger(minRange, date) && dp.less(parent.focused, date)) ||
                            (dp.less(maxRange, date) && dp.bigger(parent.focused, date)))
                        {
                            classes += ' -in-range-'
                        }

                        if (dp.less(maxRange, date) && dp.isSame(parent.focused, date)) {
                            classes += ' -range-from-'
                        }
                        if (dp.bigger(minRange, date) && dp.isSame(parent.focused, date)) {
                            classes += ' -range-to-'
                        }

                    } else if (parent.selectedDates.length == 2) {
                        if (dp.bigger(minRange, date) && dp.less(maxRange, date)) {
                            classes += ' -in-range-'
                        }
                    }
                }


                if (dp.isSame(currentDate, date, type)) classes += ' -current-';
                if (parent.focused && dp.isSame(date, parent.focused, type)) classes += ' -focus-';
                if (parent._isSelected(date, type)) classes += ' -selected-';
                if (!parent._isInRange(date, type) || render.disabled) classes += ' -disabled-';
                return {
                    html: html,
                    classes: classes
                }
            },

            /**
             * Calculates days number to render. Generates days html and returns it.
             * @param {object} date - Date object
             * @returns {string}
             * @private
             */
            _getDaysHtml: function (date) {
                var totalMonthDays = dp.getDaysCount(date),
                    firstMonthDay = new Date(date.getFullYear(), date.getMonth(), 1).getDay(),
                    lastMonthDay = new Date(date.getFullYear(), date.getMonth(), totalMonthDays).getDay(),
                    daysFromPevMonth = firstMonthDay - this.d.loc.firstDay,
                    daysFromNextMonth = 6 - lastMonthDay + this.d.loc.firstDay;

                daysFromPevMonth = daysFromPevMonth < 0 ? daysFromPevMonth + 7 : daysFromPevMonth;
                daysFromNextMonth = daysFromNextMonth > 6 ? daysFromNextMonth - 7 : daysFromNextMonth;
                var startDayIndex = -daysFromPevMonth + 1,
                    m, y,
                    html = '';
                for (var i = startDayIndex, max = totalMonthDays + daysFromNextMonth; i <= max; i++) {
                    y = date.getFullYear();
                    m = date.getMonth();
                    html += this._getDayHtml(new Date(y, m, i))
                }
                return html;
            },
            _getDayHtml: function (date) {
                var content = this._getCellContents(date, 'day');
                return '<div class="' + content.classes + '" ' +
                    'data-date="' + date.getDate() + '" ' +
                    'data-month="' + date.getMonth() + '" ' +
                    'data-year="' + date.getFullYear() + '">' + content.html + '</div>';
            },
            /**
             * Generates months html
             * @param {object} date - date instance
             * @returns {string}
             * @private
             */
            _getMonthsHtml: function (date) {
                var html = '',
                    d = dp.getParsedDate(date),
                    i = 0;
                while(i < 12) {
                    html += this._getMonthHtml(new Date(d.year, i));
                    i++
                }
                return html;
            },
            _getMonthHtml: function (date) {
                var content = this._getCellContents(date, 'month');
                return '<div class="' + content.classes + '" data-month="' + date.getMonth() + '">' + content.html + '</div>'
            },
            _getYearsHtml: function (date) {
                var d = dp.getParsedDate(date),
                    decade = dp.getDecade(date),
                    firstYear = decade[0] - 1,
                    html = '',
                    i = firstYear;
                for (i; i <= decade[1] + 1; i++) {
                    html += this._getYearHtml(new Date(i , 0));
                }
                return html;
            },

            _getYearHtml: function (date) {
                var content = this._getCellContents(date, 'year');
                return '<div class="' + content.classes + '" data-year="' + date.getFullYear() + '">' + content.html + this.d.loc.year+ '</div>'
            },
            _renderTypes: {
                days: function () {
                    var dayNames = this._getDayNamesHtml(this.d.loc.firstDay),
                        days = this._getDaysHtml(this.d.currentDate);
                    this.$cells.html(days);
                    this.$names.html(dayNames)
                },
                months: function () {
                    var html = this._getMonthsHtml(this.d.currentDate);
                    this.$cells.html(html)
                },
                years: function () {
                    var html = this._getYearsHtml(this.d.currentDate);
                    this.$cells.html(html)
                }
            },
            _render: function () {
                if (this.opts.onlyTimepicker) return;
                this._renderTypes[this.type].bind(this)();
            },
            _update: function () {
                var $cells = $('.datepicker--cell', this.$cells),
                    _this = this,
                    classes,
                    $cell,
                    date;
                $cells.each(function (cell, i) {
                    $cell = $(this);
                    date = _this.d._getDateFromCell($(this));
                    classes = _this._getCellContents(date, _this.d.cellType);
                    $cell.attr('class',classes.classes)
                });
            },
            show: function () {
                if (this.opts.onlyTimepicker) return;
                this.$el.addClass('active');
                this.acitve = true;
            },
            hide: function () {
                this.$el.removeClass('active');
                this.active = false;
            },
            //  Events
            // -------------------------------------------------
            _handleClick: function (el) {
                var date = el.data('date') || 1, month = el.data('month') || 0, year = el.data('year') || this.d.parsedDate.year, dp = this.d;
                // Change view if min view does not reach yet
                if (dp.view != this.opts.minView) {
                    dp.down(new Date(year, month, date));
                    return;
                }
                // Select date if min view is reached
                var selectedDate = new Date(year, month, date),
                    alreadySelected = this.d._isSelected(selectedDate, this.d.cellType);

                if (!alreadySelected) {
                    dp._trigger('clickCell', selectedDate);
                    return;
                }
                dp._handleAlreadySelectedDates.bind(dp, alreadySelected, selectedDate)();
            },
            _onClickCell: function (e) {
                var $el = $(e.target).closest('.datepicker--cell');
                if ($el.hasClass('-disabled-')) return;
                this._handleClick.bind(this)($el);
            }
        };
    })();

    (function () {
        var template = '' +
                '<button type="button" class="datepicker--nav-action" data-action="prev"><span class="sr-only"></span>#{prevHtml}</button>' +
                '<button type="button" class="datepicker--nav-title">#{title}</button>' +
                '<button type="button" class="datepicker--nav-action" data-action="next"><span class="sr-only"></span>#{nextHtml}</button>',
            buttonsContainerTemplate = '<div class="datepicker--buttons"></div>',
            button = '<button type="button"  class="datepicker--button" data-action="#{action}">#{label}</button>',
            datepicker = $.fn.datepicker,
            dp = datepicker.Constructor;
        datepicker.Navigation = function (d, opts) {
            this.d = d;
            this.opts = opts;
            this.loc = $.fn.datepicker.language[this.opts.language];
            this.$buttonsContainer = '';
            this.init();
        };

        datepicker.Navigation.prototype = {
            init: function () {
                this._buildBaseHtml();
                this._bindEvents();
            },
            _bindEvents: function () {
                this.d.$nav.on('click', '.datepicker--nav-action', $.proxy(this._onClickNavButton, this));
                this.d.$nav.on('click', '.datepicker--nav-title', $.proxy(this._onClickNavTitle, this));
                this.d.$datepicker.on('click', '.datepicker--button', $.proxy(this._onClickNavButton, this));
            },
            _buildBaseHtml: function () {
                if (!this.opts.onlyTimepicker) {
                    this._render();
                }
                this._addButtonsIfNeed();
            },
            _addButtonsIfNeed: function () {
                if (this.opts.todayButton) {
                    this._addButton('today')
                }
                if (this.opts.closeButton) {
                    this._addButton('close')
                }
                if (this.opts.clearButton) {
                    this._addButton('clear')
                }
            },
            _render: function () {
                var title = this._getTitle(this.d.currentDate),
                    html = dp.template(template, $.extend({title: title}, this.opts));
                this.d.$nav.html(html);
                if (this.d.view == 'years') {
                    $('.datepicker--nav-title', this.d.$nav).addClass('-disabled-');
                }
                $('[data-action="prev"]', this.d.$nav).attr('title',this.loc.prevtitle);
                $('[data-action="prev"] span', this.d.$nav).text(this.loc.prevtitle);
                $('[data-action="next"]', this.d.$nav).attr('title',this.loc.nexttitle);
                $('[data-action="next"] span', this.d.$nav).text(this.loc.nexttitle);
                this.setNavStatus();
            },
            _getTitle: function (date) {
                return this.d.formatDate(this.loc.navTitles[this.d.view], date)
            },
            _addButton: function (type) {
                if (!this.$buttonsContainer.length) {
                    this._addButtonsContainer();
                }
                var data = {
                        action: type,
                        label: this.d.loc[type]
                    },
                    html = dp.template(button, data);

                if ($('[data-action=' + type + ']', this.$buttonsContainer).length) return;
                this.$buttonsContainer.append(html);
            },

            _addButtonsContainer: function () {
                this.d.$datepicker.append(buttonsContainerTemplate);
                this.$buttonsContainer = $('.datepicker--buttons', this.d.$datepicker);
            },
            setNavStatus: function () {
                if (!(this.opts.minDate || this.opts.maxDate) || !this.opts.disableNavWhenOutOfRange) return;
                var date = this.d.parsedDate,
                    m = date.month,
                    y = date.year,
                    d = date.date;
                switch (this.d.view) {
                    case 'days':
                        if (!this.d._isInRange(new Date(y, m-1, 1), 'month')) {
                            this._disableNav('prev')
                        }
                        if (!this.d._isInRange(new Date(y, m+1, 1), 'month')) {
                            this._disableNav('next')
                        }
                        break;
                    case 'months':
                        if (!this.d._isInRange(new Date(y-1, m, d), 'year')) {
                            this._disableNav('prev')
                        }
                        if (!this.d._isInRange(new Date(y+1, m, d), 'year')) {
                            this._disableNav('next')
                        }
                        break;
                    case 'years':
                        var decade = dp.getDecade(this.d.date);
                        if (!this.d._isInRange(new Date(decade[0] - 1, 0, 1), 'year')) {
                            this._disableNav('prev')
                        }
                        if (!this.d._isInRange(new Date(decade[1] + 1, 0, 1), 'year')) {
                            this._disableNav('next')
                        }
                        break;
                }
            },
            _disableNav: function (nav) {
                $('[data-action="' + nav + '"]', this.d.$nav).addClass('-disabled-')
            },

            _activateNav: function (nav) {
                $('[data-action="' + nav + '"]', this.d.$nav).removeClass('-disabled-')
            },

            _onClickNavButton: function (e) {
                var $el = $(e.target).closest('[data-action]'),
                    action = $el.data('action');
                this.d[action]();
            },

            _onClickNavTitle: function (e) {
                if ($(e.target).hasClass('-disabled-')) return;

                if (this.d.view == 'days') {
                    return this.d.view = 'months'
                }

                this.d.view = 'years';
            }
        }


    })();
    (function () {
        var template = '<div class="datepicker--time">' +
                '<div class="datepicker--time-current">' +
                '   <span class="datepicker--time-current-hours">#{hourVisible}</span>' +
                '   <span class="datepicker--time-current-colon">:</span>' +
                '   <span class="datepicker--time-current-minutes">#{minValue}</span>' +
                '</div>' +
                '<div class="datepicker--time-sliders">' +
                '   <div class="datepicker--time-row">' +
                '      <input type="range" name="hours" value="#{hourValue}" min="#{hourMin}" max="#{hourMax}" step="#{hourStep}"/>' +
                '   </div>' +
                '   <div class="datepicker--time-row">' +
                '      <input type="range" name="minutes" value="#{minValue}" min="#{minMin}" max="#{minMax}" step="#{minStep}"/>' +
                '   </div>' +
                '</div>' +
                '</div>',
            datepicker = $.fn.datepicker,
            dp = datepicker.Constructor;

        datepicker.Timepicker = function (inst, opts) {
            this.d = inst;
            this.opts = opts;

            this.init();
        };

        datepicker.Timepicker.prototype = {
            init: function () {
                var input = 'input';
                this._setTime(this.d.date);
                this._buildHTML();

                if (navigator.userAgent.match(/trident/gi)) {
                    input = 'change';
                }

                this.d.$el.on('selectDate', this._onSelectDate.bind(this));
                this.$ranges.on(input, this._onChangeRange.bind(this));
                this.$ranges.on('mouseup', this._onMouseUpRange.bind(this));
                this.$ranges.on('mousemove focus ', this._onMouseEnterRange.bind(this));
                this.$ranges.on('mouseout blur', this._onMouseOutRange.bind(this));
            },

            _setTime: function (date) {
                var _date = dp.getParsedDate(date);

                this._handleDate(date);
                this.hours = _date.hours < this.minHours ? this.minHours : _date.hours;
                this.minutes = _date.minutes < this.minMinutes ? this.minMinutes : _date.minutes;
            },

            /**
             * Sets minHours and minMinutes from date (usually it's a minDate)
             * Also changes minMinutes if current hours are bigger then @date hours
             * @param date {Date}
             * @private
             */
            _setMinTimeFromDate: function (date) {
                this.minHours = date.getHours();
                this.minMinutes = date.getMinutes();

                // If, for example, min hours are 10, and current hours are 12,
                // update minMinutes to default value, to be able to choose whole range of values
                if (this.d.lastSelectedDate) {
                    if (this.d.lastSelectedDate.getHours() > date.getHours()) {
                        this.minMinutes = this.opts.minMinutes;
                    }
                }
            },

            _setMaxTimeFromDate: function (date) {
                this.maxHours = date.getHours();
                this.maxMinutes = date.getMinutes();

                if (this.d.lastSelectedDate) {
                    if (this.d.lastSelectedDate.getHours() < date.getHours()) {
                        this.maxMinutes = this.opts.maxMinutes;
                    }
                }
            },

            _setDefaultMinMaxTime: function () {
                var maxHours = 23,
                    maxMinutes = 59,
                    opts = this.opts;

                this.minHours = opts.minHours < 0 || opts.minHours > maxHours ? 0 : opts.minHours;
                this.minMinutes = opts.minMinutes < 0 || opts.minMinutes > maxMinutes ? 0 : opts.minMinutes;
                this.maxHours = opts.maxHours < 0 || opts.maxHours > maxHours ? maxHours : opts.maxHours;
                this.maxMinutes = opts.maxMinutes < 0 || opts.maxMinutes > maxMinutes ? maxMinutes : opts.maxMinutes;
            },

            /**
             * Looks for min/max hours/minutes and if current values
             * are out of range sets valid values.
             * @private
             */
            _validateHoursMinutes: function (date) {
                if (this.hours < this.minHours) {
                    this.hours = this.minHours;
                } else if (this.hours > this.maxHours) {
                    this.hours = this.maxHours;
                }

                if (this.minutes < this.minMinutes) {
                    this.minutes = this.minMinutes;
                } else if (this.minutes > this.maxMinutes) {
                    this.minutes = this.maxMinutes;
                }
            },

            _buildHTML: function () {
                var lz = dp.getLeadingZeroNum,
                    data = {
                        hourMin: this.minHours,
                        hourMax: lz(this.maxHours),
                        hourStep: this.opts.hoursStep,
                        hourValue: this.hours,
                        hourVisible: lz(this.displayHours),
                        minMin: this.minMinutes,
                        minMax: lz(this.maxMinutes),
                        minStep: this.opts.minutesStep,
                        minValue: lz(this.minutes)
                    },
                    _template = dp.template(template, data);

                this.$timepicker = $(_template).appendTo(this.d.$datepicker);
                this.$ranges = $('[type="range"]', this.$timepicker);
                this.$hours = $('[name="hours"]', this.$timepicker);
                this.$minutes = $('[name="minutes"]', this.$timepicker);
                this.$hoursText = $('.datepicker--time-current-hours', this.$timepicker);
                this.$minutesText = $('.datepicker--time-current-minutes', this.$timepicker);

                if (this.d.ampm) {
                    this.$ampm = $('<span class="datepicker--time-current-ampm">')
                        .appendTo($('.datepicker--time-current', this.$timepicker))
                        .html(this.dayPeriod);

                    this.$timepicker.addClass('-am-pm-');
                }
            },

            _updateCurrentTime: function () {
                var h =  dp.getLeadingZeroNum(this.displayHours),
                    m = dp.getLeadingZeroNum(this.minutes);

                this.$hoursText.html(h);
                this.$minutesText.html(m);

                if (this.d.ampm) {
                    this.$ampm.html(this.dayPeriod);
                }
            },

            _updateRanges: function () {
                this.$hours.attr({
                    min: this.minHours,
                    max: this.maxHours
                }).val(this.hours);

                this.$minutes.attr({
                    min: this.minMinutes,
                    max: this.maxMinutes
                }).val(this.minutes)
            },

            /**
             * Sets minHours, minMinutes etc. from date. If date is not passed, than sets
             * values from options
             * @param [date] {object} - Date object, to get values from
             * @private
             */
            _handleDate: function (date) {
                this._setDefaultMinMaxTime();
                if (date) {
                    if (dp.isSame(date, this.d.opts.minDate)) {
                        this._setMinTimeFromDate(this.d.opts.minDate);
                    } else if (dp.isSame(date, this.d.opts.maxDate)) {
                        this._setMaxTimeFromDate(this.d.opts.maxDate);
                    }
                }

                this._validateHoursMinutes(date);
            },

            update: function () {
                this._updateRanges();
                this._updateCurrentTime();
            },
            /**
             * Calculates valid hour value to display in text input and datepicker's body.
             * @param date {Date|Number} - date or hours
             * @param [ampm] {Boolean} - 12 hours mode
             * @returns {{hours: *, dayPeriod: string}}
             * @private
             */
            _getValidHoursFromDate: function (date, ampm) {
                var d = date,
                    hours = date;
                if (date instanceof Date) {
                    d = dp.getParsedDate(date);
                    hours = d.hours;
                }
                var _ampm = ampm || this.d.ampm,
                    dayPeriod = 'am';
                if (_ampm) {
                    switch(true) {
                        case hours == 0:
                            hours = 12;
                            break;
                        case hours == 12:
                            dayPeriod = 'pm';
                            break;
                        case hours > 11:
                            hours = hours - 12;
                            dayPeriod = 'pm';
                            break;
                        default:
                            break;
                    }
                }
                return {
                    hours: hours,
                    dayPeriod: dayPeriod
                }
            },
            set hours (val) {
                this._hours = val;

                var displayHours = this._getValidHoursFromDate(val);

                this.displayHours = displayHours.hours;
                this.dayPeriod = displayHours.dayPeriod;
            },
            get hours() {
                return this._hours;
            },
            _onChangeRange: function (e) {
                var $target = $(e.target),
                    name = $target.attr('name');

                this.d.timepickerIsActive = true;

                this[name] = $target.val();
                this._updateCurrentTime();
                this.d._trigger('timeChange', [this.hours, this.minutes]);

                this._handleDate(this.d.lastSelectedDate);
                this.update()
            },
            _onSelectDate: function (e, data) {
                this._handleDate(data);
                this.update();
            },
            _onMouseEnterRange: function (e) {
                var name = $(e.target).attr('name');
                $('.datepicker--time-current-' + name, this.$timepicker).addClass('-focus-');
            },
            _onMouseOutRange: function (e) {
                var name = $(e.target).attr('name');
                if (this.d.inFocus) return; // Prevent removing focus when mouse out of range slider
                $('.datepicker--time-current-' + name, this.$timepicker).removeClass('-focus-');
            },
            _onMouseUpRange: function (e) {
                this.d.timepickerIsActive = false;
            }
        };

        var datepickerPlugin = function(option){
            return this.each(function(){
                var $this = $(this);
                var data = $this.datepicker().data("datepicker");
                var options = typeof option === 'object' && option;
                var $that = $this.closest(".date");
                var btn = $this.parents('[data-date="datepicker"]').find('.date__icon');
                if(!$this.parent().hasClass("datepicker__wrap") && !$this.parents().hasClass("date__range")){
                    $this.wrap( "<div class='datepicker__wrap'></div>");
                }
                console.log(options);
                data = $this.datepicker(options).data("datepicker");
                if(option == "show"){


                    data.show();
                }
            });
        };


        function datePickerSet(sDate, eDate, flag,option) {
            //시작 ~ 종료 2개 짜리 달력 datepicker
            if (!isValidStr(sDate) && !isValidStr(eDate) && sDate.length > 0 && eDate.length > 0) {
                var sDay = sDate.val();
                var eDay = eDate.val();
                var options = typeof option === 'object' && option;
                if (flag && !isValidStr(sDay) && !isValidStr(eDay)) {
                    var sdp = sDate.datepicker().data("datepicker");
                    sdp.selectDate(new Date(sDay.replace(/-/g, "/")));
                    var edp = eDate.datepicker().data("datepicker");
                    edp.selectDate(new Date(eDay.replace(/-/g, "/")));
                }
                //시작일자 세팅하기 날짜가 없는경우엔 제한을 걸지 않음
                if (!isValidStr(eDay)) {
                    sDate.datepicker({
                        language: 'ko',
                        maxDate: new Date(eDay.replace(/-/g, "/"))
                    });
                }
                sDate.datepicker({
                    autoClose: true,
                    onSelect: function(dateText, inst) {
                        console.log(dateText, ', ', inst);
                        datePickerSet(sDate, eDate);
                    }
                });
                //종료일자 세팅하기 날짜가 없는경우엔 제한을 걸지 않음\
                if (!isValidStr(sDay)) {
                    eDate.datepicker({
                        language: 'ko',
                        minDate: new Date(sDay.replace(/-/g, "/"))
                    });
                }
                eDate.datepicker({
                    autoClose: true,
                    onSelect: function(dateText, inst) {
                        console.log(dateText, ', ', inst);
                        datePickerSet(sDate, eDate);
                    }
                });
                //한개짜리 달력 datepicker
            }

            function isValidStr(str) {
                if (str == null || str == undefined || str == "")
                    return true;
                else
                    return false;
            }
        }
        $(document).on('click', '[data-date="datepicker"] .date__input', function (e) {
            var $this = $(this);
            var datepicker = $this.datepicker().data("datepicker");
            if (!datepicker) return false;
            e.preventDefault();
            datepickerPlugin.call($this, 'show');
        });
        $(document).on('click', '[data-date="datepicker"] .date__icon', function (e) {
            var $this = $(this);
            $this.parents('.input__split').parents('[data-date="datepicker"]').find('.date__input').trigger("click");
            e.preventDefault();
        });

        $('[data-date="daterange"] [data-date="datepicker"] .date__input').each(function () {
            var $this = $(this);   //버튼
            var datepicker = $this.datepicker().data("datepicker");
            var $that = $this.closest(".date");
            var sDate = $this.parents('[data-date="daterange"]').find('[data-date="datepicker"][data-start-date] .date__input');
            var eDate = $this.parents('[data-date="daterange"]').find('[data-date="datepicker"][data-end-date] .date__input');
            var flag = true;
            if (!sDate && !eDate ) return false;
            $this.on('click', function (e) {
                datePickerSet(sDate, eDate, true);
            });
        });
        $(document).on('click', '[data-date="daterange"] [data-date="datepicker"] .date__icon', function (e) {
            var $this = $(this);
            $this.parents('.input__split').parents('[data-date="datepicker"]').find('.date__input').trigger("click");
            e.preventDefault();
        });

    })();
})(window, jQuery);

//TimePicker
(function($) {


    $.hunterTimePicker = function(box, options) {

        //console.log(box)
        //console.log(options)
        var dates = {
            hour: ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23'],
            minute: ['00', '05', '10', '15', '20', '25', '30', '35', '40', '45', '50', '55'],
        };
        var box = $(box);
        var template = $('<div class="Hunter-time-picker" id="Hunter_time_picker"><div class="Hunter-wrap"><div class="Hunter-wrap" id="Hunter_time_wrap"></div></div></div>');
        var time_wrap = $('#Hunter_time_wrap', template);
        $(document).click(function() {
            template.remove();
        });
        box.click(function(event) {
            event.preventDefault();
            event.stopPropagation();
            $('.Hunter-time-picker').remove();
            var _this = $(this);
            var offset = _this.offset();
            var top = offset.top + _this.outerHeight() + 15;
            template.css({
                'left': offset.left,
                'top': top
            });
            buildTimePicker();
            $('body').append(template);
            $('.Hunter-time-picker').click(function(event) {
                event.preventDefault();
                event.stopPropagation();
            });
        });

        function buildTimePicker() {
            buildHourTpl();
            hourEvent();
            minuteEvent();
            cleanBtnEvent();
            closeBtnEvent();
        }
        function buildHourTpl() {
            var hour_html = '<p>Hour</p><div class="obj">';
            for(var i = 0; i < dates.hour.length; i++) {
                var temp = box.val().split(":")[0];
                if(dates.hour[i] == temp) {
                    hour_html += '<div class="Hunter-hour active" data-hour="' + dates.hour[i] + '"><div class="Hunter-minute-wrap"></div><div class="Hunter-hour-name">' + dates.hour[i] + '</div></div>';
                } else {
                    hour_html += '<div class="Hunter-hour" data-hour="' + dates.hour[i] + '"><div class="Hunter-minute-wrap"></div><div class="Hunter-hour-name">' + dates.hour[i] + '</div></div>';
                }
            }
            hour_html += '</div><div class="Hunter-clean"><input type="button" class="Hunter-clean-btn" id="Hunter_clean_btn" value="초기화"></div><div class="Hunter-close"><button type="button" class="Hunter-close-btn" id="Hunter_close_btn">닫기</button></div>';
            time_wrap.html(hour_html);
        }
        function buildMinuteTpl(cur_time) {
            var poi = cur_time.position();
            var minute_html = '<p>Minute</p><div class="obj">';
            var temp = box.val().split(":")[1];
            for(var j = 0; j < dates.minute.length; j++) {
                if(dates.minute[j] == temp) {
                    minute_html += '<div class="Hunter-minute active" data-minute="' + dates.minute[j] + '">' + dates.minute[j] + '</div>';
                } else {
                    minute_html += '<div class="Hunter-minute" data-minute="' + dates.minute[j] + '">' + dates.minute[j] + '</div>';
                }
            }
            minute_html += '</div>';
            cur_time.find('.Hunter-minute-wrap').html(minute_html).css('left', '0px').show();
        }
        function hourEvent() {
            time_wrap.on('click', '.Hunter-hour', function(event) {
                event.preventDefault();
                event.stopPropagation();
                var _this = $(this);
                time_wrap.find('.Hunter-hour').removeClass('active');
                time_wrap.find('.Hunter-hour-name').removeClass('active');
                time_wrap.find('.Hunter-minute-wrap').hide().children().remove();

                _this.addClass('active');
                _this.find('.Hunter-hour').addClass('active');

                var hourValue = _this.data('hour');
                var temp = box.val().split(":");
                if(temp.length > 1) {
                    box.val(hourValue + ":" + temp[1]);
                } else {
                    box.val(hourValue + ":00");
                }
                buildMinuteTpl(_this);

                if(options.callback) options.callback(box);

                return false;
            });
        }
        function minuteEvent() {
            time_wrap.on('click', '.Hunter-minute', function(event) {
                event.preventDefault();
                event.stopPropagation();
                var _this = $(this);

                var minuteValue = _this.data('minute');
                var temp = box.val().split(":")[0] + ":" + minuteValue;
                box.val(temp);
                template.remove();

                if(options.callback) options.callback(box);

                return false;
            });
        }
        /*function closeBtnEvent() {
            time_wrap.on('click', '#Hunter_close_btn', function(event) {
                event.preventDefault();
                event.stopPropagation();
                //box.val('');
                template.remove();
                if(options.callback) options.callback(box);
                return false;
            });
        }*/
        function closeBtnEvent() {
            time_wrap.on('click', '#Hunter_close_btn', function(event) {
                event.preventDefault();
                event.stopPropagation();
                template.remove();
                if(options.callback) options.callback(box);
                return false;
            });
        }

        function cleanBtnEvent(){
            time_wrap.on('click', '#Hunter_clean_btn', function(event){
                event.preventDefault();
                event.stopPropagation();
                box.val('');
                template.remove();
                if(options.callback) options.callback(box);
                return false;
            });
        }
    };

    $.fn.extend({
        hunterTimePicker: function(options) {
            options = $.extend({}, options);
            this.each(function() {
                new $.hunterTimePicker(this, options);
            });
            return this;
        }
    });
})(jQuery);

$(function () {
    $('[data-date="timepicker"]').hunterTimePicker({});

});

$(function () {
    var Tooltip = function (element, options) {
        this.init("tooltip", element, options)
    };
    Tooltip.DEFAULTS = {
        placement: "top",
        selector: false,
        template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
        trigger: "hover focus",
        title: "",
        delay: 0,
        container: false,
        viewport: {
            selector: "body",
            padding: 0
        }
    };
    Tooltip.prototype.init = function (type, element, options) {
        this.enabled = true;
        this.type = type;
        this.$element = $(element);
        this.options = this.getOptions(options);
        this.$viewport = this.options.viewport && $(this.options.viewport.selector || this.options.viewport);

        var triggers = this.options.trigger.split(" ");

        for (var i = triggers.length; i--;) {
            var trigger = triggers[i];

            if (trigger !== "manual") {
                var eventIn = trigger === "hover" ? "mouseenter" : "focusin";
                var eventOut = trigger === "hover" ? "mouseleave" : "focusout";

                this.$element.on(eventIn + "." + this.type, this.options.selector, $.proxy(this.enter, this));
                this.$element.on(eventOut + "." + this.type, this.options.selector, $.proxy(this.leave, this));
            }
        }
        if (this.options.selector) {
            //data-selector 있으면
            this._options = $.extend({}, this.options, { trigger: "manual", selector: "" });
        } else {
            this.fixTitle()
        }
    };
    Tooltip.prototype.getDefaults = function () {
        return Tooltip.DEFAULTS
    };
    Tooltip.prototype.getOptions = function (options) {
        options = $.extend({}, this.getDefaults(), this.$element.data(), options);
        return options
    };
    Tooltip.prototype.getDelegateOptions = function () {
        var options = {};
        var defaults = this.getDefaults();

        this._options && $.each(this._options, function (key, value) {
            if (defaults[key] !== value) options[key] = value
        });

        return options
    };

    Tooltip.prototype.enter = function (obj) {
        var self = $(obj.currentTarget).data(this.type);

        self.hoverState = "in";
        if (self.hoverState === "in") {
            self.show()
        }
    };

    Tooltip.prototype.leave = function (obj) {

        var self = $(obj.currentTarget).data(this.type);

        self.hoverState = "out";

        if (self.hoverState === "out") {
            self.hide()
        }


    };

    Tooltip.prototype.show = function () {
        var e = $.Event("show." + this.type);

        if (this.hasContent() && this.enabled) {


            var that = this;
            var $tip = this.tip();
            var tipId = this.getUID(this.type);

            this.setContent();

            $tip.attr("id", tipId);
            this.$element.attr("aria-describedby", tipId);
            // 위치 지정 -
            var placement = this.options.placement;

            var autoToken = /\s?auto?\s?/i;
            var autoPlace = autoToken.test(placement);
            if (autoPlace) placement = placement.replace(autoToken, "") || "top";

            $tip
                .detach()
                .css({ top: 0, left: 0, display: "block" })
                .addClass(placement)
                .data(this.type, this);


            if (this.options.container) {
                $tip.appendTo(this.options.container)

            } else {
                $tip.insertAfter(this.$element);
            }

            var pos = this.getPosition();
            var actualWidth = $tip[0].offsetWidth;
            var actualHeight = $tip[0].offsetHeight;

            if (autoPlace) {
                var orgPlacement = placement;
                var $container = this.options.container ? $(this.options.container) : this.$element.parent();
                var containerDim = this.getPosition($container);

                placement = placement === "bottom" && pos.bottom + actualHeight > containerDim.bottom ? "top" :
                    placement === "top" && pos.top - actualHeight < containerDim.top ? "bottom" :
                        placement === "right" && pos.right + actualWidth > containerDim.width ? "left" :
                            placement === "left" && pos.left - actualWidth < containerDim.left ? "right" :
                                placement;

                $tip
                    .removeClass(orgPlacement)
                    .addClass(placement)
            }


            var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight);

            this.applyPlacement(calculatedOffset, placement);

        }
    };

    Tooltip.prototype.applyPlacement = function (offset, placement) {
        var $tip = this.tip();
        var width = $tip[0].offsetWidth;
        var height = $tip[0].offsetHeight;
        var marginTop = parseInt($tip.css("margin-top"), 10);
        var marginLeft = parseInt($tip.css("margin-left"), 10);
        if (isNaN(marginTop)) marginTop = 0;
        if (isNaN(marginLeft)) marginLeft = 0;
        offset.top = offset.top + marginTop;
        offset.left = offset.left + marginLeft;
        $.offset.setOffset($tip[0], $.extend({
            using: function (props) {
                $tip.css({
                    top: Math.round(props.top),
                    left: Math.round(props.left)
                })
            }
        }, offset), 0);
        $tip.addClass("active");
        var actualWidth = $tip[0].offsetWidth;
        var actualHeight = $tip[0].offsetHeight;
        if (placement === "top" && actualHeight !== height) {
            offset.top = offset.top + height - actualHeight;
        }
        var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight);
        if (delta.left) offset.left += delta.left;
        else offset.top += delta.top;

        var isVertical = /top|bottom/.test(placement);
        var arrowDelta = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight;
        var arrowOffsetPosition = isVertical ? "offsetWidth" : "offsetHeight";
        $tip.offset(offset);
        this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical)
    };
    Tooltip.prototype.replaceArrow = function (delta, dimension, isHorizontal) {
        this.arrow()
            .css(isHorizontal ? "left" : "top", 50 * (1 - delta / dimension) + "%")
            .css(isHorizontal ? "top" : "left", "")
    };
    Tooltip.prototype.setContent = function () {
        var $tip = this.tip();
        var title = this.getTitle();
        $tip.find(".tooltip-inner")["text"](title);
        $tip.removeClass("fade in top bottom left right active");
        if (this.options.maxwidth) {
            $tip.find(".tooltip-inner").css({
                maxWidth: this.options.maxwidth
            });
        }
    };
    Tooltip.prototype.hide = function (callback) {
        var that = this;
        var $tip = this.tip();
        var e = $.Event("hide." + this.type);

        function complete() {
            if (that.hoverState !== "in") $tip.detach();
            that.$element
                .removeAttr("aria-describedby")
                .trigger("hidden." + that.type);
            callback && callback()
        }
        this.$element.trigger(e);
        if (e.isDefaultPrevented()) return;
        $tip.removeClass("active");
        complete();
        this.hoverState = null;
        return this
    };
    Tooltip.prototype.fixTitle = function () {
        var $e = this.$element;
        if ($e.attr("title") || typeof (this.options.original_title) !== "string") {
            $e.attr("data-original_title", $e.attr("title") || "").attr("title", "")
        }
    };
    Tooltip.prototype.hasContent = function () {
        return this.getTitle()
    };
    Tooltip.prototype.getPosition = function ($element) {
        $element = $element || this.$element;
        var el = $element[0];
        var isBody = el.tagName === "BODY";
        var elRect = el.getBoundingClientRect();
        if (elRect.width == null) {
            elRect = $.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top })
        }
        var elOffset = isBody ? { top: 0, left: 0 } : $element.offset();
        var scroll = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() };
        var outerDims = isBody ? { width: $(window).width(), height: $(window).height() } : null;
        return $.extend({}, elRect, scroll, outerDims, elOffset)
    };
    Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {
        return placement === "bottom" ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } :
            placement === "top" ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } :
                placement === "left" ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
                    /* placement === "right" */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width }

    };
    Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) {
        var delta = { top: 0, left: 0 };
        if (!this.$viewport) return delta;
        var viewportPadding = this.options.viewport && this.options.viewport.padding || 0;
        var viewportDimensions = this.getPosition(this.$viewport);
        if (/right|left/.test(placement)) {
            var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll;
            var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight;
            if (topEdgeOffset < viewportDimensions.top) {
                delta.top = viewportDimensions.top - topEdgeOffset
            } else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) {
                delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset
            }
        } else {
            var leftEdgeOffset = pos.left - viewportPadding;
            var rightEdgeOffset = pos.left + viewportPadding + actualWidth;
            if (leftEdgeOffset < viewportDimensions.left) {
                delta.left = viewportDimensions.left - leftEdgeOffset
            } else if (rightEdgeOffset > viewportDimensions.width) {
                delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset
            }
        }
        return delta
    };
    Tooltip.prototype.getTitle = function () {
        var title;
        var $e = this.$element;
        title = $e.attr("data-original_title");
        if (!title) {
            title = this.options.original_title;
        }
        return title
    };
    Tooltip.prototype.getUID = function (prefix) {
        do prefix += ~~(Math.random() * 1000000);
        while (document.getElementById(prefix));
        return prefix
    };
    Tooltip.prototype.tip = function () {
        return (this.$tip = this.$tip || $(this.options.template))
    };
    Tooltip.prototype.arrow = function () {
        return (this.$arrow = this.$arrow || this.tip().find(".tooltip-arrow"))
    };
    Tooltip.prototype.toggle = function (e) {
        var self = this;
        if (e) {
            self = $(e.currentTarget).data(this.type);
            if (!self) {
                self = new this.constructor(e.currentTarget);
                $(e.currentTarget).data(this.type, self)
            }
        }
        if (self.tip().hasClass("active")) {
            self.leave(self)
        } else {
            self.enter(self)
        }
    };
    function tooltipPlugin(option) {
        return this.each(function () {
            var $this = $(this);
            var data = $this.data("tooltip");
            var options = typeof option === "object" && option;
            if (!data) {
                $this.data("tooltip", (data = new Tooltip(this, options)));
            }

        })
    }

    $.fn.tooltip = tooltipPlugin;
    $.fn.tooltip.Constructor = Tooltip;
    //Popover
    var Popover = function (element, options) {
        this.init('popover', element, options)
    };
    if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js');
    Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, {
        placement: 'right',
        trigger: 'hover focus',
        content: '',
        template: '<div class="popover" role="tooltip"><div class="arrow"></div><div class="popover-title"></div><div class="popover-content"></div></div>'
    });
    Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype);
    Popover.prototype.constructor = Popover;
    Popover.prototype.getDefaults = function () {
        return Popover.DEFAULTS
    };
    Popover.prototype.setContent = function () {
        var $tip = this.tip();
        var title = this.getTitle();
        var content = this.getContent();
        $tip.find('.popover-title')["text"](title);
        $tip.find('.popover-content').children().detach().end()["text"](content);
        $tip.removeClass('fade top bottom left right in active');
        if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide();
        if (this.options.maxwidth) {
            $tip.css({
                maxWidth: this.options.maxwidth
            });
        }
    };
    Popover.prototype.hasContent = function () {
        return this.getTitle() || this.getContent()
    };
    Popover.prototype.getContent = function () {
        var $e = this.$element;

        return $e.attr('data-content') || (typeof this.options.content === 'function' ?
            this.options.content.call($e[0]) :
            this.options.content)
    };

    Popover.prototype.arrow = function () {
        return (this.$arrow = this.$arrow || this.tip().find('.arrow'))
    };

    Popover.prototype.tip = function () {
        if (!this.$tip) this.$tip = $(this.options.template);
        return this.$tip
    };

    function popoverPulgin(option) {
        return this.each(function () {
            var $this = $(this);
            var data = $this.data('popover');
            var options = typeof option === 'object' && option;


            if (!data) $this.data('popover', (data = new Popover(this, options)));
            if (typeof option === 'string') data[option]()

        })
    }

    $.fn.popover = popoverPulgin;
    $.fn.popover.Constructor = Popover;
    $(window).on("load", function (e) {
        $("[data-button=\"tooltip\"]").each(function () {
            if ($(this).is('a')) {
                $(this).on("click", function (e) {
                    e.preventDefault();
                });
            }
            var allTooltip = $(this);
            var data = allTooltip.data();
            tooltipPlugin.call(allTooltip, data);
        });
        $("[data-button=\"popover\"]").each(function () {
            if ($(this).is('a')) {
                $(this).on("click", function (e) {
                    e.preventDefault();
                });
            }
            var allPopover = $(this);
            var data = allPopover.data();
            popoverPulgin.call(allPopover, data);
        });

    });

});


(function () {
    var youtubeModal = function () {
        this.Selector = {
            overlay: '.Modal-overlay',
            box: '.Modal-box',
            button: '[data-button=youtube-button]'
        };
        this.Markup = {
            close: '<div class="Modal-close">&times;</div>',
            overlay: '<div class="Modal-overlay"></div>',
            box: '<div class="Modal-box"></div>'
        };
        this.youtubeID = false;
    };

    youtubeModal.prototype = {

        toggleOverflow: function () {
            $('body').toggleClass('Modal-cancel-overflow');
        },

        videoContainer: function () {
            return '<div class="video-container"><iframe id="player" frameborder="0" allowfullscreen="1" title="YouTube video player" width="640" height="390" src="//www.youtube.com/embed/' + this.youtubeID + '?autoplay=1&rel=0" frameborder="0" type="text/html"></iframe></div>';
        },

        addOverlay: function () {
            var self = this;
            $(this.Markup.overlay).appendTo('body').fadeIn('slow', function () {
                self.toggleOverflow();
            });
            $(this.Selector.overlay).on('click touchstart', function () {
                self.closeModal();
            });
        },

        addModalBox: function () {
            $(this.Markup.box).appendTo(this.Selector.overlay);
        },

        buildModal: function (youtubeID) {
            this.addOverlay();
            this.addModalBox();
            $(this.Markup.close).appendTo(this.Selector.overlay);
            $(this.videoContainer(youtubeID)).appendTo(this.Selector.box);
        },

        closeModal: function () {
            this.toggleOverflow();
            $(this.Selector.overlay).fadeOut().detach();
            $(this.Selector.box).empty();
        },

        getYoutubeID: function () {
            return this.youtubeID;
        },

        setYoutubeID: function (href) {
            var id = '';
            if (href.indexOf('youtube.com') > -1) {
                // full Youtube link
                id = href.split('v=')[1];
            } else if (href.indexOf('youtu.be') > -1) {
                // shortened Youtube link
                id = href.split('.be/')[1];
            } else {
                // in case it's not a Youtube link, send them on their merry way
                document.location = href;
            }
            // If there's an ampersand, remove it and return what's left, otherwise return the ID
            // this.youtubeID = (id.indexOf('&') != -1) ? id.substring(0, amp) : id;
            this.youtubeID = id;
        },

        startup: function (href) {
            this.setYoutubeID(href);
            if (this.youtubeID) {
                this.buildModal();
            }
        }
    };

    $(document).ready(function () {
        var youtubemodal = new youtubeModal();
        $(youtubemodal.Selector.button).on('click touchstart', function (e) {
            e.preventDefault();
            youtubemodal.startup(this.href);
        });
    });

})(this);

// ajaxprototyOpen

function ajaxprototyOpen(t, m) {
    var t = $(t);
    var m = $(m);
    var winHeight = $("html").height();
    t.url = t.attr("href");
    $.get(t.url, function (msg) {
        $("html").css({ "height": winHeight });
        // $("html,body").css("overflow", "hidden");
        t.msg = $(msg);
        t.content = t.msg.html();
        m.layer = $("#ajaxLayer");
        if (m.layer.size() > 0) {
            m.layer.html(msg);
            //m.layer.find(".modal__close>button").trigger("focus");
        } else {
            m.append("<div id=\"ajaxLayer\" style=\"display:none;overflow:auto\">" + msg + "</div>");
            m.layer = $("#ajaxLayer");
            m.layer.fadeIn(300);
            m.layer.find(".modal__close2>button").trigger("focus");
        }


    });
    return true;
}
function ajaxprototypExit(t) {
    var t = $(t);
    t.fadeOut(300,
        function () {
            $("html,body").removeAttr("style");
            t.remove();
        }
    );
    return true;
}



/**
 * date 타입 --> yyyy-mm-dd 형태로 변경
 * @param date
 * @returns {string}
 */
function getFormatDate(date) {
    const year = date.getFullYear();
    let month = date.getMonth() + 1;
    month = month >= 10 ? month : '0' + month;
    let day = date.getDate();
    day = day >= 10 ? day : '0' + day;
    return year + '-' + month + '-' + day;
}

/**
 * submit 시 데이터 공통병합처리
 * @param telno     전화번호
 * @param mblTelno  휴대전화번호
 * @param brdt      생년월일
 * @param emlAddr   이메일
 * @param fxno      팩스번호
 * @param arr
 */
function setDefaultFormData(arr) {
    arr.forEach(function(nm) {
        if (nm == 'telno') {
            $("#telno").val($("#tel01").val() + "-" + $("#tel02").val() + "-" + $("#tel03").val());
        } else if (nm == 'mblTelno') {
            $("#mblTelno").val($("#mblTel01").val() + "-" + $("#mblTel02").val() + "-" + $("#mblTel03").val());
        } else if (nm == 'brdt') {
            $("#brdt").val($("#brdtYear").val() + "-" + $("#brdtMonth").val() + "-" + $("#brdtDay").val());
        } else if (nm == 'emlAddr') {
            $("#emlAddr").val($("#emailId").val() + "@" + $("#emailDomain").val());
        } else if (nm == 'fxno') {
            $("#fxno").val($("#fxno01").val() + "-" + $("#fxno02").val() + "-" + $("#fxno03").val());
        }
    });
}

/**
 * SheetJS - export HTML Table to Excel
 * @param type
 * @param fn
 * @param dl
 * @returns {*|void|ArrayBuffer|string|string|boolean}
 * @constructor
 */
function ExportToExcel(type, fn, dl) {
    var elt = document.getElementById('datatable');
    var wb = XLSX.utils.table_to_book(elt, { sheet: "sheet1" });
    return dl ? XLSX.write(wb, { bookType: type, bookSST: true, type: 'base64' }) : XLSX.writeFile(wb, fn || ('MySheetName.' + (type || 'xlsx')));
}

/**
 * jQuery Validate Custom Function
 * @param formName
 * @param cb
 */
$.fn.goFormValid = function(cb) {
    var rules = $(this).data('rules');
    var messages = $(this).data('messages');

    if (rules === undefined) {
        rules = {};
    }

    if (messages === undefined) {
        messages = {};
    }

    // 폼 검증
    $(this).validate({
        rules: rules,
        messages: messages,
        errorElement: 'div',
        errorClass: 'col-sm-9 pl-2 pt-0 pb-2 message',
        ignore: [],
        errorPlacement: function errorPlacement(error, element) {
            validateErrorHandler(error, element);
        },
        highlight: function(element) {
            var $el = $(element);
            var $parent = $el.parents('.form-group');

            $el.addClass('is-invalid');
            $parent.addClass('error');

            // Select2 and Tagsinput
            if ($el.hasClass('select2-hidden-accessible') || $el.attr('data-role') === 'tagsinput') {
                $el.parent().addClass('is-invalid');
            }
        },
        unhighlight: function(element) {
            let chk = true;
            // check others
            $(element).parents('.form-group').find('[required=required]').each(function(i, obj) {
                if ($(obj).val().length == 0) {
                    chk = false;
                }
            });

            if (chk) {
                $(element).parents('.form-group').find('.is-invalid').removeClass('is-invalid');
                $(element).parents('.form-group').removeClass('error');
            }
        },
        submitHandler: function(form) {
            if (typeof cb == 'function') {
                cb(form);
            }
        }
    });
};

/**
 * jQuery Validate용 Error 메시지 처리
 * @param error
 * @param element
 */
function validateErrorHandler (error, element) {
    const elId = $(element).attr("id").replace('.', '\\.');
    const $parent = $(element).parents('.form-group');
    const $errorLabels = $parent.find('.jquery-validation-error');

    try {
        if ($errorLabels.length > 0) {
            let checkBreak = false;
            $errorLabels.each(function (idx, item) {
                $(item).text().trim().length == 0 ? $(item).remove() : checkBreak = true;
            });
            if (checkBreak) return;
        }
    } catch (e) {
        console.log(e);
    }

    const $error = error.addClass('jquery-validation-error small form-text invalid-feedback');
    $parent.find(" > div").not(".control-label").not(".col-form-label").each(function(idx, item) {
        if ($(item).find("#" + elId).length > 0) {
            $(item).append($error);
        }
    });
}

/**
 * 이용약관 동의 처리
 * - radiobox에 메시지 처리 : data-msg-agree="개인정보 수집 및 이용에 동의해 주세요."
 * @returns {boolean}
 */
function fn_chk_agree() {
    if ($("input.agree_radio_y:not(:checked)").length > 0) {
        const msg = $("input.agree_radio_y:not(:checked)").eq(0).attr('title');
        Common.Dialog.alert({
            title: '약관 동의'
            ,content: msg
            ,ok: function () {
                $("input.agree_radio_y:not(:checked)").eq(0).focus();
            }
        });
        return false;
    } else {
        return true;
    }
}

/*
* 달력 생성기
* @param sDate 파라미터만 넣으면 1개짜리 달력 생성
* @example   datePickerSet($("#datepicker"));
*
*
* @param sDate,
* @param eDate 2개 넣으면 연결달력 생성되어 서로의 날짜를 넘어가지 않음
* @example   datePickerSet($("#datepicker1"), $("#datepicker2"));
*/
function dateRangeSet(sDate, eDate, flag) {
    //시작 ~ 종료 2개 짜리 달력 datepicker
    if (!isValidStr(sDate) && !isValidStr(eDate) && sDate.length > 0 && eDate.length > 0) {
        var sDay = sDate.val();
        var eDay = eDate.val();
        if (flag && !isValidStr(sDay) && !isValidStr(eDay)) { //처음 입력 날짜 설정, update...
            var sdp = sDate.datepicker().data("datepicker");
            sdp.selectDate(new Date(sDay.replace(/-/g, "/")));  //익스에서는 그냥 new Date하면 -을 인식못함 replace필요
            var edp = eDate.datepicker().data("datepicker");
            edp.selectDate(new Date(eDay.replace(/-/g, "/")));  //익스에서는 그냥 new Date하면 -을 인식못함 replace필요
        }
        //시작일자 세팅하기 날짜가 없는경우엔 제한을 걸지 않음
        if (!isValidStr(eDay)) {
            sDate.datepicker({
                dateFormat: 'yyyy-mm-dd',
                maxDate: new Date(eDay.replace(/-/g, "/"))
            });
        }
        sDate.datepicker({
            autoClose: true,
            dateFormat: 'yyyy-mm-dd',
            onSelect: function () {
                datePickerSet(sDate, eDate);
            }
        });
        //종료일자 세팅하기 날짜가 없는경우엔 제한을 걸지 않음
        if (!isValidStr(sDay)) {
            eDate.datepicker({
                dateFormat: 'yyyy-mm-dd',
                minDate: new Date(sDay.replace(/-/g, "/"))
            });
        }
        eDate.datepicker({
            autoClose: true,
            dateFormat: 'yyyy-mm-dd',
            onSelect: function () {
                datePickerSet(sDate, eDate);
            }
        });
        //한개짜리 달력 datepicker
    } else if (!isValidStr(sDate)) {
        var sDay = sDate.val();
        if (flag && !isValidStr(sDay)) { //처음 입력 날짜 설정, update...
            var sdp = sDate.datepicker().data("datepicker");
            sdp.selectDate(new Date(sDay.replace(/-/g, "/"))); //익스에서는 그냥 new Date하면 -을 인식못함 replace필요
        }
        sDate.datepicker({
            autoClose: true
        });
    }
    function isValidStr(str) {
        if (str == null || str == undefined || str == "") return true;
        else return false;
    }
}

/**
 * yyyy, yyyy-mm, yyyy-mm-dd
 * @param sDate
 * @param dateFormat
 * @param flag
 */
function dateSet(sDate, dateFormat, flag) {
    $(sDate).attr("autocomplete", "off");
    if (dateFormat === 'yyyy') {
        sDate.datepicker({
            language: 'ko',
            autoClose: true,
            showOtherMonths: false,
            selectOtherMonths: false,
            view: 'years',
            minView: 'years',
            dateFormat: 'yyyy',
        });
    } else if (dateFormat === 'yyyy-mm') {
        sDate.datepicker({
            language: 'ko',
            autoClose: true,
            showOtherMonths: false,
            selectOtherMonths: false,
            view: 'months',
            minView: 'months',
            dateFormat: 'yyyy-mm',
        });
    } else {
        sDate.datepicker({
            autoClose: true,
        });
    }


    function isValidStr(str) {
        if (str == null || str == undefined || str == "") return true;
        else return false;
    }
}

function datePickerSet(sDate, eDate, flag,option) {
    //시작 ~ 종료 2개 짜리 달력 datepicker
    if (!isValidStr(sDate) && !isValidStr(eDate) && sDate.length > 0 && eDate.length > 0) {
        var sDay = sDate.val();
        var eDay = eDate.val();
        var options = typeof option === 'object' && option;
        if (flag && !isValidStr(sDay) && !isValidStr(eDay)) {
            var sdp = sDate.datepicker().data("datepicker");
            sdp.selectDate(new Date(sDay.replace(/-/g, "/")));
            var edp = eDate.datepicker().data("datepicker");
            edp.selectDate(new Date(eDay.replace(/-/g, "/")));
        }
        //시작일자 세팅하기 날짜가 없는경우엔 제한을 걸지 않음
        if (!isValidStr(eDay)) {
            sDate.datepicker({
                maxDate: new Date(eDay.replace(/-/g, "/"))
            });
        }
        sDate.datepicker({
            autoClose: true,
            onSelect: function(dateText, inst) {
                console.log(dateText, ', ', inst);
                datePickerSet(sDate, eDate);
            }
        });
        //종료일자 세팅하기 날짜가 없는경우엔 제한을 걸지 않음
        if (!isValidStr(sDay)) {
            eDate.datepicker({
                minDate: new Date(sDay.replace(/-/g, "/"))
            });
        }
        eDate.datepicker({
            autoClose: true,
            onSelect: function(dateText, inst) {
                console.log(dateText, ', ', inst);
                datePickerSet(sDate, eDate);
            }
        });
        //한개짜리 달력 datepicker
    }

    function isValidStr(str) {
        if (str == null || str == undefined || str == "")
            return true;
        else
            return false;
    }
}

/**
 * 주소 함수 처리
 */
function goZipCodePopup() {
    var daumPopup = window.open("/module/juso/daumPopup.jsp", "daumPopup", "width=500,height=500, scrollbars=yes, resizable=yes");
}

function jusoCallBack(zipCode, addr, roadAddr, jibunAddr, roadFullAddr) {
    $("#zip").val(zipCode);
    $("#addr").val(addr);
    $("#daddr").focus();

    // 좌표 자동세팅
    if ($("input[name=lat]").length > 0) {
        let coord = fn_findLatLotByAddr(addr);
        console.log('coord',coord);

        $("input[name=lat]").val(coord.lat);
        $("input[name=lot]").val(coord.lot);
    }
}

// 지도 API 마커 위치 잡기 위한 위/경도 조회
function fn_findLatLotByAddr(addr) {
    let result = {};
    $.ajax({
        type: "GET",
        async: false,
        data: {'query': addr },
        url: 'https://dapi.kakao.com/v2/local/search/address.json',
        beforeSend: function(xhr) {
            xhr.setRequestHeader("Authorization","KakaoAK a26aff6147ab07e0003e9c9345c457dc");
        },
        success: function(res) {
            if (res.documents.length > 0) {
                let addrInfo = res.documents[0];
                result.lot = addrInfo.x;
                result.lat = addrInfo.y;
            }
        }
    });
    return result;
}

$(function() {

    const dataset = document.body.dataset;
    window.onpageshow = function(event) {
        if ( event.persisted || (window.performance && window.performance.navigation.type == 2)) {
            dataset.message = "";
        }

        if (dataset.message != undefined && dataset.message != '') {
            Common.Dialog.alert({
                title: '메세지',
                content: dataset.message
            });
        }
        dataset.message = "";
    }

    var isRtl = $('body').attr('dir') === 'rtl' || $('html').attr('dir') === 'rtl';

    // Initialize sidenav
    $('#layout-sidenav').each(function() {
        new SideNav(this, {
            orientation: $(this).hasClass('sidenav-horizontal') ? 'horizontal' : 'vertical'
        });
    });

    // Initialize sidenav togglers
    $('body').on('click', '.layout-sidenav-toggle', function(e) {
        e.preventDefault();
        window.layoutHelpers.toggleCollapsed();
    });

    // Swap dropdown menus in RTL mode
    if ($('html').attr('dir') === 'rtl') {
        $('#layout-navbar .dropdown-menu').toggleClass('dropdown-menu-right');
    }

    $('.select2').each(function() {
        const ph = $(this).find('option:eq(0)').value;
        $(this)
            .wrap('<div class="position-relative"></div>')
            .select2({
                placeholder: ph,
                dropdownParent: $(this).parent()
            });
    });


    /*****************************************************
     * Default Form Binding
     ****************************************************/

    // 이메일
    $("#emlAddr").each(function() {
        const emlAddr = $(this).val();
        if (emlAddr != '' && emlAddr.indexOf("@") > 0) {
            const split = emlAddr.split("@");
            $("#emailId").val(split[0]);
            if (split.length > 1 && split[1] != '') {
                $("#emailDomain").val(split[1]);
                $("#emailSel option[value='" + split[1] + "']").prop('selected', true);
                if ($("#emailSel option[value='" + split[1] + "']").length == 1) {
                    $("#emailDomain").prop("readonly", true);
                }
            }
        }

        // 이메일 도메인변경
        $("#emailSel").change(function () {
            const $target = $(this).prev("input").prop("readonly", true);
            $target.val($(this).val());
            if ($(this).val() == "input") {
                $target.prop("readonly", false).val("");
            } else {
                $target.valid();
            }
        });
    });

    // 생년월일
    $("#brdt").each(function() {
        const  brdt = $(this).val();
        if (brdt != '' && brdt.indexOf("-") > 0) {
            const split = brdt.split("-");
            $("#brdtYear").val(split[0]);
            $("#brdtMonth").val(split[1]);
            $("#brdtDay").val(split[2]);
        } else if(brdt.length == 8) {

            $("#brdt").val(brdt.substring(0,4)+"-"+brdt.substring(4,6)+"-"+brdt.substring(6,8));
        }
    });

    // 전화번호
    $("#telno").each(function() {
        const telNo = $(this).val();
        if (telNo != '' && telNo.indexOf("-") > 0) {
            const split = telNo.split("-");
            $("#tel01").val(split[0]);
            $("#tel02").val(split[1]);
            $("#tel03").val(split[2]);
        }
    });

    // 핸드폰번호
    $("#mblTelno").each(function() {
        const mblTelNo = $(this).val();
        if (mblTelNo != '' && mblTelNo.indexOf("-") > 0) {
            const split = mblTelNo.split("-");
            $("#mblTel01").val(split[0]);
            $("#mblTel02").val(split[1]);
            $("#mblTel03").val(split[2]);
        } else if(mblTelNo.length == 11) {
            $("#mblTel01").val(mblTelNo.substring(0,3));
            $("#mblTel02").val(mblTelNo.substring(3,7));
            $("#mblTel03").val(mblTelNo.substring(7,11));
        }
    });

    // 팩스번호
    $("#fxno").each(function() {
        const fxno = $(this).val();
        if (fxno != '' && fxno.indexOf("-") > 0) {
            const split = fxno.split("-");
            $("#fxno01").val(split[0]);
            $("#fxno02").val(split[1]);
            $("#fxno03").val(split[2]);
        }
    });

    // maxlength만큼 입력, 다음 maxlength2로 focus 처리
    $(".maxlength1").on("propertychange change keyup paste input", function() {
        if(this.maxLength <= this.value.length) {
            this.value = this.value.slice(0, this.maxLength);
        }
    });

    // maxlength만큼 입력 가능
    $(".maxlength2,input__maxlength").on("propertychange change keyup paste input", function() {
        if(this.maxLength <= this.value.length) {
            this.value = this.value.slice(0, this.maxLength);
        }
    });

    // onlyNumber 입력 가능
    $(".onlyNumber,input__maxlength").on("propertychange change keyup paste input", function() {
        $(this).val($(this).val().replace(/[^0-9]/g,""));
    })

    $(".checkbox-box input:radio").change(function () {
        const $this = $(this);
        const $target = $(this).data("target");     // true 일때 처리

        const disabledEl = $this.closest(".checkbox-box").data("disabled");
        const hideEl = $this.closest(".checkbox-box").data("hide");

        if ($target) {
            $(disabledEl).attr("disabled",false);
            $(hideEl).show().attr("disabled",false);
        } else {
            $(disabledEl).attr("disabled",true).val();
            $(hideEl).hide().attr("disabled",true);
        }
    })

    /*
    * datepicker / timepicker
    * 관련 acego.common 과 합칠경우 삭제 할 수도 있음
    * */
    /*
    * 달력 생성기
    * @param sDate 파라미터만 넣으면 1개짜리 달력 생성
    * @example   datePickerSet($("#datepicker"));
    *
    *
    * @param sDate,
    * @param eDate 2개 넣으면 연결달력 생성되어 서로의 날짜를 넘어가지 않음
    * @example   datePickerSet($("#datepicker1"), $("#datepicker2"));
    */
    function dateRangeSet(sDate, eDate, flag, dateFormat) {
        //시작 ~ 종료 2개 짜리 달력 datepicker
        if (!isValidStr(sDate) && !isValidStr(eDate) && sDate.length > 0 && eDate.length > 0) {
            var sDay = sDate.val();
            var eDay = eDate.val();
            if (flag && !isValidStr(sDay) && !isValidStr(eDay)) { //처음 입력 날짜 설정, update...
                var sdp = sDate.datepicker().data("datepicker");
                sdp.selectDate(new Date(sDay.replace(/-/g, "/")));  //익스에서는 그냥 new Date하면 -을 인식못함 replace필요
                var edp = eDate.datepicker().data("datepicker");
                edp.selectDate(new Date(eDay.replace(/-/g, "/")));  //익스에서는 그냥 new Date하면 -을 인식못함 replace필요
            }

            //시작일자 세팅하기 날짜가 없는경우엔 제한을 걸지 않음
            if (!isValidStr(eDay)) {
                sDate.datepicker({
                    view: 'years',
                    minView: 'years',
                    dateFormat: 'yyyy',
                    maxDate: new Date(eDay.replace(/-/g, "/"))
                });
            }
            sDate.datepicker({
                autoClose: true,
                view: 'years',
                minView: 'years',
                dateFormat: 'yyyy',
                onSelect: function () {
                    datePickerSet(sDate, eDate);
                }
            });

            //종료일자 세팅하기 날짜가 없는경우엔 제한을 걸지 않음
            if (!isValidStr(sDay)) {
                eDate.datepicker({
                    view: 'years',
                    minView: 'years',
                    dateFormat: 'yyyy',
                    minDate: new Date(sDay.replace(/-/g, "/"))
                });
            }
            eDate.datepicker({
                autoClose: true,
                view: 'years',
                minView: 'years',
                dateFormat: 'yyyy',
                onSelect: function () {
                    datePickerSet(sDate, eDate);
                }
            });
            //한개짜리 달력 datepicker
        } else if (!isValidStr(sDate)) {
            var sDay = sDate.val();
            if (flag && !isValidStr(sDay)) { //처음 입력 날짜 설정, update...
                var sdp = sDate.datepicker().data("datepicker");
                sdp.selectDate(new Date(sDay.replace(/-/g, "/"))); //익스에서는 그냥 new Date하면 -을 인식못함 replace필요
            }
            sDate.datepicker({
                autoClose: true
            });
        }
        function isValidStr(str) {
            if (str == null || str == undefined || str == "") return true;
            else return false;
        }
    }

    //두개짜리 제어 연결된거 만들어주는 함수
    dateRangeSet($("#datepicker1"), $("#datepicker2"), true); //다중은 시작하는 달력 먼저, 끝달력 2번째

    $("#weekStart-disabled").each(function() {
        var $weekStartdisabled = $('#weekStart-disabled');
        var $weekEnddisabled = $('#weekEnd-disabled');
        var disabledDays = [0, 6]; //주말 관련
        var datepicker = $('#weekStart-disabled, #weekEnd-disabled').datepicker().data('datepicker');

        $weekStartdisabled.datepicker({
            language: 'ko',
            autoClose: true,
            //minDate: new Date(),
            onRenderCell: function(date, cellType) {
                // 특정일 제외 https://codepen.io/by_olegovichs/pen/JQwbGq
                if (cellType == 'day') {
                    var day = date.getDay(),
                        isDisabled = disabledDays.indexOf(day) != -1;
                    return {
                        disabled: isDisabled
                    };
                }
            }
        }).attr("autocomplete", "off");

        $weekEnddisabled.datepicker({
            language: 'ko',
            autoClose: true,
            //minDate: new Date(),
            onRenderCell: function(date, cellType) {
                if (cellType == 'day') {
                    var day = date.getDay(),
                        isDisabled = disabledDays.indexOf(day) != -1;
                    return {
                        disabled: isDisabled
                    };
                }
            }
        }).attr("autocomplete", "off");
    });

});

if (window.layoutHelpers) {
    window.layoutHelpers.setAutoUpdate(true);
}

(function () {
    $(document).on("click", "[data-bbstype]", function (e) {
        e.preventDefault();
        $(this).each(function () {
            var $this, $viewTrigger, $list, target;
            $this = $(this);
            $viewTrigger = $("[data-bbstype]");
            $list = $(".bbs__list > .bbs__list-type");
            function swapBbsTypeActiveClass() {
                $viewTrigger.removeClass('active');
                $this.addClass('active');
            }
            function swapbbstype() {
                var $currentView = $this.attr('data-bbstype');
                $list.attr('data-bbsview', $currentView);
            }
            swapBbsTypeActiveClass();
            swapbbstype();
        });
    });
    $(window).on("load", function () {
        $("[data-trigger]").each(function () {
            var $this = $(this);
        });
    });
})();
/*
     _ _      _       _
 ___| (_) ___| | __  (_)___
/ __| | |/ __| |/ /  | / __|
\__ \ | | (__|   < _ | \__ \
|___/_|_|\___|_|\_(_)/ |___/
                   |__/
 Version: 1.9.0
  Author: Ken Wheeler
 Website: http://kenwheeler.github.io
    Docs: http://kenwheeler.github.io/slick
    Repo: http://github.com/kenwheeler/slick
  Issues: http://github.com/kenwheeler/slick/issues
 */
/* global window, document, define, jQuery, setInterval, clearInterval */
; (function (factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        define(['jquery'], factory);
    } else if (typeof exports !== 'undefined') {
        module.exports = factory(require('jquery'));
    } else {
        factory(jQuery);
    }

}(function ($) {
    'use strict';
    var Slick = window.Slick || {};

    Slick = (function () {

        var instanceUid = 0;

        function Slick(element, settings) {

            var _ = this, dataSettings;

            _.defaults = {
                accessibility: true,
                adaptiveHeight: false,
                appendArrows: $(element),
                appendDots: $(element),
                arrows: true,
                asNavFor: null,
                prevArrow: '<button class="slick-prev" aria-label="Previous" type="button">Previous</button>',
                nextArrow: '<button class="slick-next" aria-label="Next" type="button">Next</button>',
                autoplay: false,
                autoplaySpeed: 3000,
                centerMode: false,
                centerPadding: '50px',
                cssEase: 'ease',
                customPaging: function (slider, i) {
                    return $('<button type="button" />').text(i + 1);
                },
                dots: false,
                dotsClass: 'slick-dots',
                draggable: true,
                easing: 'linear',
                edgeFriction: 0.35,
                fade: false,
                focusOnSelect: false,
                focusOnChange: false,
                infinite: true,
                initialSlide: 0,
                lazyLoad: 'ondemand',
                mobileFirst: false,
                pauseOnHover: true,
                pauseOnFocus: true,
                pauseOnDotsHover: false,
                respondTo: 'window',
                responsive: null,
                rows: 1,
                rtl: false,
                slide: '',
                slidesPerRow: 1,
                slidesToShow: 1,
                slidesToScroll: 1,
                speed: 500,
                swipe: true,
                swipeToSlide: false,
                touchMove: true,
                touchThreshold: 5,
                useCSS: true,
                useTransform: true,
                variableWidth: false,
                vertical: false,
                verticalSwiping: false,
                waitForAnimate: true,
                zIndex: 1000
            };

            _.initials = {
                animating: false,
                dragging: false,
                autoPlayTimer: null,
                currentDirection: 0,
                currentLeft: null,
                currentSlide: 0,
                direction: 1,
                $dots: null,
                listWidth: null,
                listHeight: null,
                loadIndex: 0,
                $nextArrow: null,
                $prevArrow: null,
                scrolling: false,
                slideCount: null,
                slideWidth: null,
                $slideTrack: null,
                $slides: null,
                sliding: false,
                slideOffset: 0,
                swipeLeft: null,
                swiping: false,
                $list: null,
                touchObject: {},
                transformsEnabled: false,
                unslicked: false
            };

            $.extend(_, _.initials);

            _.activeBreakpoint = null;
            _.animType = null;
            _.animProp = null;
            _.breakpoints = [];
            _.breakpointSettings = [];
            _.cssTransitions = false;
            _.focussed = false;
            _.interrupted = false;
            _.hidden = 'hidden';
            _.paused = true;
            _.positionProp = null;
            _.respondTo = null;
            _.rowCount = 1;
            _.shouldClick = true;
            _.$slider = $(element);
            _.$slidesCache = null;
            _.transformType = null;
            _.transitionType = null;
            _.visibilityChange = 'visibilitychange';
            _.windowWidth = 0;
            _.windowTimer = null;

            dataSettings = $(element).data('slick') || {};

            _.options = $.extend({}, _.defaults, settings, dataSettings);

            _.currentSlide = _.options.initialSlide;

            _.originalSettings = _.options;

            if (typeof document.mozHidden !== 'undefined') {
                _.hidden = 'mozHidden';
                _.visibilityChange = 'mozvisibilitychange';
            } else if (typeof document.webkitHidden !== 'undefined') {
                _.hidden = 'webkitHidden';
                _.visibilityChange = 'webkitvisibilitychange';
            }

            _.autoPlay = $.proxy(_.autoPlay, _);
            _.autoPlayClear = $.proxy(_.autoPlayClear, _);
            _.autoPlayIterator = $.proxy(_.autoPlayIterator, _);
            _.changeSlide = $.proxy(_.changeSlide, _);
            _.clickHandler = $.proxy(_.clickHandler, _);
            _.selectHandler = $.proxy(_.selectHandler, _);
            _.setPosition = $.proxy(_.setPosition, _);
            _.swipeHandler = $.proxy(_.swipeHandler, _);
            _.dragHandler = $.proxy(_.dragHandler, _);
            _.keyHandler = $.proxy(_.keyHandler, _);

            _.instanceUid = instanceUid++;

            // A simple way to check for HTML strings
            // Strict HTML recognition (must start with <)
            // Extracted from jQuery v1.11 source
            _.htmlExpr = /^(?:\s*(<[\w\W]+>)[^>]*)$/;


            _.registerBreakpoints();
            _.init(true);

        }

        return Slick;

    }());

    Slick.prototype.activateADA = function () {
        var _ = this;

        _.$slideTrack.find('.slick-active').attr({
            'aria-hidden': 'false'
        }).find('a, input, button, select').attr({
            'tabindex': '0'
        });

    };

    Slick.prototype.addSlide = Slick.prototype.slickAdd = function (markup, index, addBefore) {

        var _ = this;

        if (typeof (index) === 'boolean') {
            addBefore = index;
            index = null;
        } else if (index < 0 || (index >= _.slideCount)) {
            return false;
        }

        _.unload();

        if (typeof (index) === 'number') {
            if (index === 0 && _.$slides.length === 0) {
                $(markup).appendTo(_.$slideTrack);
            } else if (addBefore) {
                $(markup).insertBefore(_.$slides.eq(index));
            } else {
                $(markup).insertAfter(_.$slides.eq(index));
            }
        } else {
            if (addBefore === true) {
                $(markup).prependTo(_.$slideTrack);
            } else {
                $(markup).appendTo(_.$slideTrack);
            }
        }

        _.$slides = _.$slideTrack.children(this.options.slide);

        _.$slideTrack.children(this.options.slide).detach();

        _.$slideTrack.append(_.$slides);

        _.$slides.each(function (index, element) {
            $(element).attr('data-slick-index', index);
        });

        _.$slidesCache = _.$slides;

        _.reinit();

    };

    Slick.prototype.animateHeight = function () {
        var _ = this;
        if (_.options.slidesToShow === 1 && _.options.adaptiveHeight === true && _.options.vertical === false) {
            var targetHeight = _.$slides.eq(_.currentSlide).outerHeight(true);
            _.$list.animate({
                height: targetHeight
            }, _.options.speed);
        }
    };

    Slick.prototype.animateSlide = function (targetLeft, callback) {

        var animProps = {},
            _ = this;

        _.animateHeight();

        if (_.options.rtl === true && _.options.vertical === false) {
            targetLeft = -targetLeft;
        }
        if (_.transformsEnabled === false) {
            if (_.options.vertical === false) {
                _.$slideTrack.animate({
                    left: targetLeft
                }, _.options.speed, _.options.easing, callback);
            } else {
                _.$slideTrack.animate({
                    top: targetLeft
                }, _.options.speed, _.options.easing, callback);
            }

        } else {

            if (_.cssTransitions === false) {
                if (_.options.rtl === true) {
                    _.currentLeft = -(_.currentLeft);
                }
                $({
                    animStart: _.currentLeft
                }).animate({
                    animStart: targetLeft
                }, {
                    duration: _.options.speed,
                    easing: _.options.easing,
                    step: function (now) {
                        now = Math.ceil(now);
                        if (_.options.vertical === false) {
                            animProps[_.animType] = 'translate(' +
                                now + 'px, 0px)';
                            _.$slideTrack.css(animProps);
                        } else {
                            animProps[_.animType] = 'translate(0px,' +
                                now + 'px)';
                            _.$slideTrack.css(animProps);
                        }
                    },
                    complete: function () {
                        if (callback) {
                            callback.call();
                        }
                    }
                });

            } else {

                _.applyTransition();
                targetLeft = Math.ceil(targetLeft);

                if (_.options.vertical === false) {
                    animProps[_.animType] = 'translate3d(' + targetLeft + 'px, 0px, 0px)';
                } else {
                    animProps[_.animType] = 'translate3d(0px,' + targetLeft + 'px, 0px)';
                }
                _.$slideTrack.css(animProps);

                if (callback) {
                    setTimeout(function () {

                        _.disableTransition();

                        callback.call();
                    }, _.options.speed);
                }

            }

        }

    };

    Slick.prototype.getNavTarget = function () {

        var _ = this,
            asNavFor = _.options.asNavFor;

        if (asNavFor && asNavFor !== null) {
            asNavFor = $(asNavFor).not(_.$slider);
        }

        return asNavFor;

    };

    Slick.prototype.asNavFor = function (index) {

        var _ = this,
            asNavFor = _.getNavTarget();

        if (asNavFor !== null && typeof asNavFor === 'object') {
            asNavFor.each(function () {
                var target = $(this).slick('getSlick');
                if (!target.unslicked) {
                    target.slideHandler(index, true);
                }
            });
        }

    };

    Slick.prototype.applyTransition = function (slide) {

        var _ = this,
            transition = {};

        if (_.options.fade === false) {
            transition[_.transitionType] = _.transformType + ' ' + _.options.speed + 'ms ' + _.options.cssEase;
        } else {
            transition[_.transitionType] = 'opacity ' + _.options.speed + 'ms ' + _.options.cssEase;
        }

        if (_.options.fade === false) {
            _.$slideTrack.css(transition);
        } else {
            _.$slides.eq(slide).css(transition);
        }

    };

    Slick.prototype.autoPlay = function () {

        var _ = this;

        _.autoPlayClear();

        if (_.slideCount > _.options.slidesToShow) {
            _.autoPlayTimer = setInterval(_.autoPlayIterator, _.options.autoplaySpeed);
        }

    };

    Slick.prototype.autoPlayClear = function () {

        var _ = this;

        if (_.autoPlayTimer) {
            clearInterval(_.autoPlayTimer);
        }

    };

    Slick.prototype.autoPlayIterator = function () {

        var _ = this,
            slideTo = _.currentSlide + _.options.slidesToScroll;

        if (!_.paused && !_.interrupted && !_.focussed) {

            if (_.options.infinite === false) {

                if (_.direction === 1 && (_.currentSlide + 1) === (_.slideCount - 1)) {
                    _.direction = 0;
                }

                else if (_.direction === 0) {

                    slideTo = _.currentSlide - _.options.slidesToScroll;

                    if (_.currentSlide - 1 === 0) {
                        _.direction = 1;
                    }

                }

            }

            _.slideHandler(slideTo);

        }

    };

    Slick.prototype.buildArrows = function () {

        var _ = this;

        if (_.options.arrows === true) {

            _.$prevArrow = $(_.options.prevArrow).addClass('slick-arrow');
            _.$nextArrow = $(_.options.nextArrow).addClass('slick-arrow');

            if (_.slideCount > _.options.slidesToShow) {

                _.$prevArrow.removeClass('slick-hidden').removeAttr('aria-hidden tabindex');
                _.$nextArrow.removeClass('slick-hidden').removeAttr('aria-hidden tabindex');

                if (_.htmlExpr.test(_.options.prevArrow)) {
                    _.$prevArrow.prependTo(_.options.appendArrows);
                }

                if (_.htmlExpr.test(_.options.nextArrow)) {
                    _.$nextArrow.appendTo(_.options.appendArrows);
                }

                if (_.options.infinite !== true) {
                    _.$prevArrow
                        .addClass('slick-disabled')
                        .attr('aria-disabled', 'true');
                }

            } else {

                _.$prevArrow.add(_.$nextArrow)

                    .addClass('slick-hidden')
                    .attr({
                        'aria-disabled': 'true',
                        'tabindex': '-1'
                    });

            }

        }

    };

    Slick.prototype.buildDots = function () {

        var _ = this,
            i, dot;

        if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {

            _.$slider.addClass('slick-dotted');

            dot = $('<ul />').addClass(_.options.dotsClass);

            for (i = 0; i <= _.getDotCount(); i += 1) {
                dot.append($('<li />').append(_.options.customPaging.call(this, _, i)));
            }

            _.$dots = dot.appendTo(_.options.appendDots);

            _.$dots.find('li').first().addClass('slick-active');

        }

    };

    Slick.prototype.buildOut = function () {

        var _ = this;

        _.$slides =
            _.$slider
                .children(_.options.slide + ':not(.slick-cloned)')
                .addClass('slick-slide');

        _.slideCount = _.$slides.length;

        _.$slides.each(function (index, element) {
            $(element)
                .attr('data-slick-index', index)
                .data('originalStyling', $(element).attr('style') || '');
        });

        _.$slider.addClass('slick-slider');

        _.$slideTrack = (_.slideCount === 0) ?
            $('<div class="slick-track"/>').appendTo(_.$slider) :
            _.$slides.wrapAll('<div class="slick-track"/>').parent();

        _.$list = _.$slideTrack.wrap(
            '<div class="slick-list"/>').parent();
        _.$slideTrack.css('opacity', 0);

        if (_.options.centerMode === true || _.options.swipeToSlide === true) {
            _.options.slidesToScroll = 1;
        }

        $('img[data-lazy]', _.$slider).not('[src]').addClass('slick-loading');

        _.setupInfinite();

        _.buildArrows();

        _.buildDots();

        _.updateDots();


        _.setSlideClasses(typeof _.currentSlide === 'number' ? _.currentSlide : 0);

        if (_.options.draggable === true) {
            _.$list.addClass('draggable');
        }

    };

    Slick.prototype.buildRows = function () {

        var _ = this, a, b, c, newSlides, numOfSlides, originalSlides, slidesPerSection;

        newSlides = document.createDocumentFragment();
        originalSlides = _.$slider.children();

        if (_.options.rows > 0) {

            slidesPerSection = _.options.slidesPerRow * _.options.rows;
            numOfSlides = Math.ceil(
                originalSlides.length / slidesPerSection
            );

            for (a = 0; a < numOfSlides; a++) {
                var slide = document.createElement('div');
                for (b = 0; b < _.options.rows; b++) {
                    var row = document.createElement('div');
                    for (c = 0; c < _.options.slidesPerRow; c++) {
                        var target = (a * slidesPerSection + ((b * _.options.slidesPerRow) + c));
                        if (originalSlides.get(target)) {
                            row.appendChild(originalSlides.get(target));
                        }
                    }
                    slide.appendChild(row);
                }
                newSlides.appendChild(slide);
            }

            _.$slider.empty().append(newSlides);
            _.$slider.children().children().children()
                .css({
                    'width': (100 / _.options.slidesPerRow) + '%',
                    'display': 'inline-block'
                });

        }

    };

    Slick.prototype.checkResponsive = function (initial, forceUpdate) {

        var _ = this,
            breakpoint, targetBreakpoint, respondToWidth, triggerBreakpoint = false;
        var sliderWidth = _.$slider.width();
        var windowWidth = window.innerWidth || $(window).width();

        if (_.respondTo === 'window') {
            respondToWidth = windowWidth;
        } else if (_.respondTo === 'slider') {
            respondToWidth = sliderWidth;
        } else if (_.respondTo === 'min') {
            respondToWidth = Math.min(windowWidth, sliderWidth);
        }

        if (_.options.responsive &&
            _.options.responsive.length &&
            _.options.responsive !== null) {

            targetBreakpoint = null;

            for (breakpoint in _.breakpoints) {
                if (_.breakpoints.hasOwnProperty(breakpoint)) {
                    if (_.originalSettings.mobileFirst === false) {
                        if (respondToWidth < _.breakpoints[breakpoint]) {
                            targetBreakpoint = _.breakpoints[breakpoint];
                        }
                    } else {
                        if (respondToWidth > _.breakpoints[breakpoint]) {
                            targetBreakpoint = _.breakpoints[breakpoint];
                        }
                    }
                }
            }

            if (targetBreakpoint !== null) {
                if (_.activeBreakpoint !== null) {
                    if (targetBreakpoint !== _.activeBreakpoint || forceUpdate) {
                        _.activeBreakpoint =
                            targetBreakpoint;
                        if (_.breakpointSettings[targetBreakpoint] === 'unslick') {
                            _.unslick(targetBreakpoint);
                        } else {
                            _.options = $.extend({}, _.originalSettings,
                                _.breakpointSettings[
                                    targetBreakpoint]);
                            if (initial === true) {
                                _.currentSlide = _.options.initialSlide;
                            }
                            _.refresh(initial);
                        }
                        triggerBreakpoint = targetBreakpoint;
                    }
                } else {
                    _.activeBreakpoint = targetBreakpoint;
                    if (_.breakpointSettings[targetBreakpoint] === 'unslick') {
                        _.unslick(targetBreakpoint);
                    } else {
                        _.options = $.extend({}, _.originalSettings,
                            _.breakpointSettings[
                                targetBreakpoint]);
                        if (initial === true) {
                            _.currentSlide = _.options.initialSlide;
                        }
                        _.refresh(initial);
                    }
                    triggerBreakpoint = targetBreakpoint;
                }
            } else {
                if (_.activeBreakpoint !== null) {
                    _.activeBreakpoint = null;
                    _.options = _.originalSettings;
                    if (initial === true) {
                        _.currentSlide = _.options.initialSlide;
                    }
                    _.refresh(initial);
                    triggerBreakpoint = targetBreakpoint;
                }
            }

            // only trigger breakpoints during an actual break. not on initialize.
            if (!initial && triggerBreakpoint !== false) {
                _.$slider.trigger('breakpoint', [_, triggerBreakpoint]);
            }
        }

    };

    Slick.prototype.changeSlide = function (event, dontAnimate) {

        var _ = this,
            $target = $(event.currentTarget),
            indexOffset, slideOffset, unevenOffset;

        // If target is a link, prevent default action.
        if ($target.is('a')) {
            event.preventDefault();
        }

        // If target is not the <li> element (ie: a child), find the <li>.
        if (!$target.is('li')) {
            $target = $target.closest('li');
        }

        unevenOffset = (_.slideCount % _.options.slidesToScroll !== 0);
        indexOffset = unevenOffset ? 0 : (_.slideCount - _.currentSlide) % _.options.slidesToScroll;

        switch (event.data.message) {

            case 'previous':
                slideOffset = indexOffset === 0 ? _.options.slidesToScroll : _.options.slidesToShow - indexOffset;
                if (_.slideCount > _.options.slidesToShow) {
                    _.slideHandler(_.currentSlide - slideOffset, false, dontAnimate);
                }
                break;

            case 'next':
                slideOffset = indexOffset === 0 ? _.options.slidesToScroll : indexOffset;
                if (_.slideCount > _.options.slidesToShow) {
                    _.slideHandler(_.currentSlide + slideOffset, false, dontAnimate);
                }
                break;

            case 'index':
                var index = event.data.index === 0 ? 0 :
                    event.data.index || $target.index() * _.options.slidesToScroll;

                _.slideHandler(_.checkNavigable(index), false, dontAnimate);
                $target.children().trigger('focus');
                break;

            default:
                return;
        }

    };

    Slick.prototype.checkNavigable = function (index) {

        var _ = this,
            navigables, prevNavigable;

        navigables = _.getNavigableIndexes();
        prevNavigable = 0;
        if (index > navigables[navigables.length - 1]) {
            index = navigables[navigables.length - 1];
        } else {
            for (var n in navigables) {
                if (index < navigables[n]) {
                    index = prevNavigable;
                    break;
                }
                prevNavigable = navigables[n];
            }
        }

        return index;
    };

    Slick.prototype.cleanUpEvents = function () {

        var _ = this;

        if (_.options.dots && _.$dots !== null) {

            $('li', _.$dots)
                .off('click.slick', _.changeSlide)
                .off('mouseenter.slick', $.proxy(_.interrupt, _, true))
                .off('mouseleave.slick', $.proxy(_.interrupt, _, false));

            if (_.options.accessibility === true) {
                _.$dots.off('keydown.slick', _.keyHandler);
            }
        }

        _.$slider.off('focus.slick blur.slick');

        if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {
            _.$prevArrow && _.$prevArrow.off('click.slick', _.changeSlide);
            _.$nextArrow && _.$nextArrow.off('click.slick', _.changeSlide);

            if (_.options.accessibility === true) {
                _.$prevArrow && _.$prevArrow.off('keydown.slick', _.keyHandler);
                _.$nextArrow && _.$nextArrow.off('keydown.slick', _.keyHandler);
            }
        }

        _.$list.off('touchstart.slick mousedown.slick', _.swipeHandler);
        _.$list.off('touchmove.slick mousemove.slick', _.swipeHandler);
        _.$list.off('touchend.slick mouseup.slick', _.swipeHandler);
        _.$list.off('touchcancel.slick mouseleave.slick', _.swipeHandler);

        _.$list.off('click.slick', _.clickHandler);

        $(document).off(_.visibilityChange, _.visibility);

        _.cleanUpSlideEvents();

        if (_.options.accessibility === true) {
            _.$list.off('keydown.slick', _.keyHandler);
        }

        if (_.options.focusOnSelect === true) {
            $(_.$slideTrack).children().off('click.slick', _.selectHandler);
        }

        $(window).off('orientationchange.slick.slick-' + _.instanceUid, _.orientationChange);

        $(window).off('resize.slick.slick-' + _.instanceUid, _.resize);

        $('[draggable!=true]', _.$slideTrack).off('dragstart', _.preventDefault);

        $(window).off('load.slick.slick-' + _.instanceUid, _.setPosition);

    };

    Slick.prototype.cleanUpSlideEvents = function () {

        var _ = this;

        _.$list.off('mouseenter.slick', $.proxy(_.interrupt, _, true));
        _.$list.off('mouseleave.slick', $.proxy(_.interrupt, _, false));

    };

    Slick.prototype.cleanUpRows = function () {

        var _ = this, originalSlides;

        if (_.options.rows > 0) {
            originalSlides = _.$slides.children().children();
            originalSlides.removeAttr('style');
            _.$slider.empty().append(originalSlides);
        }

    };

    Slick.prototype.clickHandler = function (event) {

        var _ = this;

        if (_.shouldClick === false) {
            event.stopImmediatePropagation();
            event.stopPropagation();
            event.preventDefault();
        }

    };

    Slick.prototype.destroy = function (refresh) {

        var _ = this;

        _.autoPlayClear();

        _.touchObject = {};

        _.cleanUpEvents();

        $('.slick-cloned', _.$slider).detach();

        if (_.$dots) {
            _.$dots.remove();
        }

        if (_.$prevArrow && _.$prevArrow.length) {

            _.$prevArrow
                .removeClass('slick-disabled slick-arrow slick-hidden')
                .removeAttr('aria-hidden aria-disabled tabindex')
                .css('display', '');

            if (_.htmlExpr.test(_.options.prevArrow)) {
                _.$prevArrow.remove();
            }
        }

        if (_.$nextArrow && _.$nextArrow.length) {

            _.$nextArrow
                .removeClass('slick-disabled slick-arrow slick-hidden')
                .removeAttr('aria-hidden aria-disabled tabindex')
                .css('display', '');

            if (_.htmlExpr.test(_.options.nextArrow)) {
                _.$nextArrow.remove();
            }
        }


        if (_.$slides) {

            _.$slides
                .removeClass('slick-slide slick-active slick-center slick-visible slick-current')
                .removeAttr('aria-hidden')
                .removeAttr('data-slick-index')
                .each(function () {
                    $(this).attr('style', $(this).data('originalStyling'));
                });

            _.$slideTrack.children(this.options.slide).detach();

            _.$slideTrack.detach();

            _.$list.detach();

            _.$slider.append(_.$slides);
        }

        _.cleanUpRows();

        _.$slider.removeClass('slick-slider');
        _.$slider.removeClass('slick-initialized');
        _.$slider.removeClass('slick-dotted');

        _.unslicked = true;

        if (!refresh) {
            _.$slider.trigger('destroy', [_]);
        }

    };

    Slick.prototype.disableTransition = function (slide) {

        var _ = this,
            transition = {};

        transition[_.transitionType] = '';

        if (_.options.fade === false) {
            _.$slideTrack.css(transition);
        } else {
            _.$slides.eq(slide).css(transition);
        }

    };

    Slick.prototype.fadeSlide = function (slideIndex, callback) {

        var _ = this;

        if (_.cssTransitions === false) {

            _.$slides.eq(slideIndex).css({
                zIndex: _.options.zIndex
            });

            _.$slides.eq(slideIndex).animate({
                opacity: 1
            }, _.options.speed, _.options.easing, callback);

        } else {

            _.applyTransition(slideIndex);

            _.$slides.eq(slideIndex).css({
                opacity: 1,
                zIndex: _.options.zIndex
            });

            if (callback) {
                setTimeout(function () {

                    _.disableTransition(slideIndex);

                    callback.call();
                }, _.options.speed);
            }

        }

    };

    Slick.prototype.fadeSlideOut = function (slideIndex) {

        var _ = this;

        if (_.cssTransitions === false) {

            _.$slides.eq(slideIndex).animate({
                opacity: 0,
                zIndex: _.options.zIndex - 2
            }, _.options.speed, _.options.easing);

        } else {

            _.applyTransition(slideIndex);

            _.$slides.eq(slideIndex).css({
                opacity: 0,
                zIndex: _.options.zIndex - 2
            });

        }

    };

    Slick.prototype.filterSlides = Slick.prototype.slickFilter = function (filter) {

        var _ = this;

        if (filter !== null) {

            _.$slidesCache = _.$slides;

            _.unload();

            _.$slideTrack.children(this.options.slide).detach();

            _.$slidesCache.filter(filter).appendTo(_.$slideTrack);

            _.reinit();

        }

    };

    Slick.prototype.focusHandler = function () {

        var _ = this;

        // If any child element receives focus within the slider we need to pause the autoplay
        _.$slider
            .off('focus.slick blur.slick')
            .on(
                'focus.slick',
                '*',
                function (event) {
                    var $sf = $(this);

                    setTimeout(function () {
                        if (_.options.pauseOnFocus) {
                            if ($sf.is(':focus')) {
                                _.focussed = true;
                                _.autoPlay();
                            }
                        }
                    }, 0);
                }
            ).on(
            'blur.slick',
            '*',
            function (event) {
                var $sf = $(this);

                // When a blur occurs on any elements within the slider we become unfocused
                if (_.options.pauseOnFocus) {
                    _.focussed = false;
                    _.autoPlay();
                }
            }
        );
    };

    Slick.prototype.getCurrent = Slick.prototype.slickCurrentSlide = function () {

        var _ = this;
        return _.currentSlide;

    };

    Slick.prototype.getDotCount = function () {

        var _ = this;

        var breakPoint = 0;
        var counter = 0;
        var pagerQty = 0;

        if (_.options.infinite === true) {
            if (_.slideCount <= _.options.slidesToShow) {
                ++pagerQty;
            } else {
                while (breakPoint < _.slideCount) {
                    ++pagerQty;
                    breakPoint = counter + _.options.slidesToScroll;
                    counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow;
                }
            }
        } else if (_.options.centerMode === true) {
            pagerQty = _.slideCount;
        } else if (!_.options.asNavFor) {
            pagerQty = 1 + Math.ceil((_.slideCount - _.options.slidesToShow) / _.options.slidesToScroll);
        } else {
            while (breakPoint < _.slideCount) {
                ++pagerQty;
                breakPoint = counter + _.options.slidesToScroll;
                counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow;
            }
        }

        return pagerQty - 1;

    };

    Slick.prototype.getLeft = function (slideIndex) {

        var _ = this,
            targetLeft,
            verticalHeight,
            verticalOffset = 0,
            targetSlide,
            coef;

        _.slideOffset = 0;
        verticalHeight = _.$slides.first().outerHeight(true);

        if (_.options.infinite === true) {
            if (_.slideCount > _.options.slidesToShow) {
                _.slideOffset = (_.slideWidth * _.options.slidesToShow) * -1;
                coef = -1

                if (_.options.vertical === true && _.options.centerMode === true) {
                    if (_.options.slidesToShow === 2) {
                        coef = -1.5;
                    } else if (_.options.slidesToShow === 1) {
                        coef = -2
                    }
                }
                verticalOffset = (verticalHeight * _.options.slidesToShow) * coef;
            }
            if (_.slideCount % _.options.slidesToScroll !== 0) {
                if (slideIndex + _.options.slidesToScroll > _.slideCount && _.slideCount > _.options.slidesToShow) {
                    if (slideIndex > _.slideCount) {
                        _.slideOffset = ((_.options.slidesToShow - (slideIndex - _.slideCount)) * _.slideWidth) * -1;
                        verticalOffset = ((_.options.slidesToShow - (slideIndex - _.slideCount)) * verticalHeight) * -1;
                    } else {
                        _.slideOffset = ((_.slideCount % _.options.slidesToScroll) * _.slideWidth) * -1;
                        verticalOffset = ((_.slideCount % _.options.slidesToScroll) * verticalHeight) * -1;
                    }
                }
            }
        } else {
            if (slideIndex + _.options.slidesToShow > _.slideCount) {
                _.slideOffset = ((slideIndex + _.options.slidesToShow) - _.slideCount) * _.slideWidth;
                verticalOffset = ((slideIndex + _.options.slidesToShow) - _.slideCount) * verticalHeight;
            }
        }

        if (_.slideCount <= _.options.slidesToShow) {
            _.slideOffset = 0;
            verticalOffset = 0;
        }

        if (_.options.centerMode === true && _.slideCount <= _.options.slidesToShow) {
            _.slideOffset = ((_.slideWidth * Math.floor(_.options.slidesToShow)) / 2) - ((_.slideWidth * _.slideCount) / 2);
        } else if (_.options.centerMode === true && _.options.infinite === true) {
            _.slideOffset += _.slideWidth * Math.floor(_.options.slidesToShow / 2) - _.slideWidth;
        } else if (_.options.centerMode === true) {
            _.slideOffset = 0;
            _.slideOffset += _.slideWidth * Math.floor(_.options.slidesToShow / 2);
        }

        if (_.options.vertical === false) {
            targetLeft = ((slideIndex * _.slideWidth) * -1) + _.slideOffset;
        } else {
            targetLeft = ((slideIndex * verticalHeight) * -1) + verticalOffset;
        }

        if (_.options.variableWidth === true) {

            if (_.slideCount <= _.options.slidesToShow || _.options.infinite === false) {
                targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex);
            } else {
                targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex + _.options.slidesToShow);
            }

            if (_.options.rtl === true) {
                if (targetSlide[0]) {
                    targetLeft = (_.$slideTrack.width() - targetSlide[0].offsetLeft - targetSlide.width()) * -1;
                } else {
                    targetLeft = 0;
                }
            } else {
                targetLeft = targetSlide[0] ? targetSlide[0].offsetLeft * -1 : 0;
            }

            if (_.options.centerMode === true) {
                if (_.slideCount <= _.options.slidesToShow || _.options.infinite === false) {
                    targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex);
                } else {
                    targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex + _.options.slidesToShow + 1);
                }

                if (_.options.rtl === true) {
                    if (targetSlide[0]) {
                        targetLeft = (_.$slideTrack.width() - targetSlide[0].offsetLeft - targetSlide.width()) * -1;
                    } else {
                        targetLeft = 0;
                    }
                } else {
                    targetLeft = targetSlide[0] ? targetSlide[0].offsetLeft * -1 : 0;
                }

                targetLeft += (_.$list.width() - targetSlide.outerWidth()) / 2;
            }
        }

        return targetLeft;

    };

    Slick.prototype.getOption = Slick.prototype.slickGetOption = function (option) {

        var _ = this;

        return _.options[option];

    };

    Slick.prototype.getNavigableIndexes = function () {

        var _ = this,
            breakPoint = 0,
            counter = 0,
            indexes = [],
            max;

        if (_.options.infinite === false) {
            max = _.slideCount;
        } else {
            breakPoint = _.options.slidesToScroll * -1;
            counter = _.options.slidesToScroll * -1;
            max = _.slideCount * 2;
        }

        while (breakPoint < max) {
            indexes.push(breakPoint);
            breakPoint = counter + _.options.slidesToScroll;
            counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow;
        }

        return indexes;

    };

    Slick.prototype.getSlick = function () {

        return this;

    };

    Slick.prototype.getSlideCount = function () {

        var _ = this,
            slidesTraversed, swipedSlide, swipeTarget, centerOffset;

        centerOffset = _.options.centerMode === true ? Math.floor(_.$list.width() / 2) : 0;
        swipeTarget = (_.swipeLeft * -1) + centerOffset;

        if (_.options.swipeToSlide === true) {

            _.$slideTrack.find('.slick-slide').each(function (index, slide) {

                var slideOuterWidth, slideOffset, slideRightBoundary;
                slideOuterWidth = $(slide).outerWidth();
                slideOffset = slide.offsetLeft;
                if (_.options.centerMode !== true) {
                    slideOffset += (slideOuterWidth / 2);
                }

                slideRightBoundary = slideOffset + (slideOuterWidth);

                if (swipeTarget < slideRightBoundary) {
                    swipedSlide = slide;
                    return false;
                }
            });

            slidesTraversed = Math.abs($(swipedSlide).attr('data-slick-index') - _.currentSlide) || 1;

            return slidesTraversed;

        } else {
            return _.options.slidesToScroll;
        }

    };

    Slick.prototype.goTo = Slick.prototype.slickGoTo = function (slide, dontAnimate) {

        var _ = this;

        _.changeSlide({
            data: {
                message: 'index',
                index: parseInt(slide)
            }
        }, dontAnimate);

    };

    Slick.prototype.init = function (creation) {

        var _ = this;

        if (!$(_.$slider).hasClass('slick-initialized')) {

            $(_.$slider).addClass('slick-initialized');

            _.buildRows();
            _.buildOut();
            _.setProps();
            _.startLoad();
            _.loadSlider();
            _.initializeEvents();
            _.updateArrows();
            _.updateDots();
            _.checkResponsive(true);
            _.focusHandler();

        }

        if (creation) {
            _.$slider.trigger('init', [_]);
        }

        if (_.options.accessibility === true) {
            _.initADA();
        }

        if (_.options.autoplay) {

            _.paused = false;
            _.autoPlay();

        }

    };

    Slick.prototype.initADA = function () {
        var _ = this,
            numDotGroups = Math.ceil(_.slideCount / _.options.slidesToShow),
            tabControlIndexes = _.getNavigableIndexes().filter(function (val) {
                return (val >= 0) && (val < _.slideCount);
            });

        _.$slides.add(_.$slideTrack.find('.slick-cloned')).attr({
            'aria-hidden': 'true',
            'tabindex': '-1'
        }).find('a, input, button, select').attr({
            'tabindex': '-1'
        });

        if (_.$dots !== null) {
            _.$slides.not(_.$slideTrack.find('.slick-cloned')).each(function (i) {
                var slideControlIndex = tabControlIndexes.indexOf(i);

                $(this).attr({
                    'role': 'tabpanel',
                    'id': 'slick-slide' + _.instanceUid + i,
                    'tabindex': -1
                });

                if (slideControlIndex !== -1) {
                    var ariaButtonControl = 'slick-slide-control' + _.instanceUid + slideControlIndex
                    if ($('#' + ariaButtonControl).length) {
                        $(this).attr({
                            'aria-describedby': ariaButtonControl
                        });
                    }
                }
            });

            _.$dots.attr('role', 'tablist').find('li').each(function (i) {
                var mappedSlideIndex = tabControlIndexes[i];

                $(this).attr({
                    'role': 'presentation'
                });

                $(this).find('button').first().attr({
                    'role': 'tab',
                    'id': 'slick-slide-control' + _.instanceUid + i,
                    'aria-controls': 'slick-slide' + _.instanceUid + mappedSlideIndex,
                    'aria-label': (i + 1) + ' of ' + numDotGroups,
                    'aria-selected': null,
                    'tabindex': '-1'
                });

            }).eq(_.currentSlide).find('button').attr({
                'aria-selected': 'true',
                'tabindex': '0'
            }).end();
        }

        for (var i = _.currentSlide, max = i + _.options.slidesToShow; i < max; i++) {
            if (_.options.focusOnChange) {
                _.$slides.eq(i).attr({ 'tabindex': '0' });
            } else {
                _.$slides.eq(i).removeAttr('tabindex');
            }
        }

        _.activateADA();

    };

    Slick.prototype.initArrowEvents = function () {

        var _ = this;

        if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {
            _.$prevArrow
                .off('click.slick')
                .on('click.slick', {
                    message: 'previous'
                }, _.changeSlide);
            _.$nextArrow
                .off('click.slick')
                .on('click.slick', {
                    message: 'next'
                }, _.changeSlide);

            if (_.options.accessibility === true) {
                _.$prevArrow.on('keydown.slick', _.keyHandler);
                _.$nextArrow.on('keydown.slick', _.keyHandler);
            }
        }

    };

    Slick.prototype.initDotEvents = function () {

        var _ = this;

        if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {
            $('li', _.$dots).on('click.slick', {
                message: 'index'
            }, _.changeSlide);

            if (_.options.accessibility === true) {
                _.$dots.on('keydown.slick', _.keyHandler);
            }
        }

        if (_.options.dots === true && _.options.pauseOnDotsHover === true && _.slideCount > _.options.slidesToShow) {

            $('li', _.$dots)
                .on('mouseenter.slick', $.proxy(_.interrupt, _, true))
                .on('mouseleave.slick', $.proxy(_.interrupt, _, false));

        }

    };

    Slick.prototype.initSlideEvents = function () {

        var _ = this;

        if (_.options.pauseOnHover) {

            _.$list.on('mouseenter.slick', $.proxy(_.interrupt, _, true));
            _.$list.on('mouseleave.slick', $.proxy(_.interrupt, _, false));

        }

    };

    Slick.prototype.initializeEvents = function () {

        var _ = this;

        _.initArrowEvents();

        _.initDotEvents();
        _.initSlideEvents();

        _.$list.on('touchstart.slick mousedown.slick', {
            action: 'start'
        }, _.swipeHandler);
        _.$list.on('touchmove.slick mousemove.slick', {
            action: 'move'
        }, _.swipeHandler);
        _.$list.on('touchend.slick mouseup.slick', {
            action: 'end'
        }, _.swipeHandler);
        _.$list.on('touchcancel.slick mouseleave.slick', {
            action: 'end'
        }, _.swipeHandler);

        _.$list.on('click.slick', _.clickHandler);

        $(document).on(_.visibilityChange, $.proxy(_.visibility, _));

        if (_.options.accessibility === true) {
            _.$list.on('keydown.slick', _.keyHandler);
        }

        if (_.options.focusOnSelect === true) {
            $(_.$slideTrack).children().on('click.slick', _.selectHandler);
        }

        $(window).on('orientationchange.slick.slick-' + _.instanceUid, $.proxy(_.orientationChange, _));

        $(window).on('resize.slick.slick-' + _.instanceUid, $.proxy(_.resize, _));

        $('[draggable!=true]', _.$slideTrack).on('dragstart', _.preventDefault);

        $(window).on('load.slick.slick-' + _.instanceUid, _.setPosition);
        $(_.setPosition);

    };

    Slick.prototype.initUI = function () {

        var _ = this;

        if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {

            _.$prevArrow.show();
            _.$nextArrow.show();

        }

        if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {

            _.$dots.show();

        }

    };

    Slick.prototype.keyHandler = function (event) {

        var _ = this;
        //Dont slide if the cursor is inside the form fields and arrow keys are pressed
        if (!event.target.tagName.match('TEXTAREA|INPUT|SELECT')) {
            if (event.keyCode === 37 && _.options.accessibility === true) {
                _.changeSlide({
                    data: {
                        message: _.options.rtl === true ? 'next' : 'previous'
                    }
                });
            } else if (event.keyCode === 39 && _.options.accessibility === true) {
                _.changeSlide({
                    data: {
                        message: _.options.rtl === true ? 'previous' : 'next'
                    }
                });
            }
        }

    };

    Slick.prototype.lazyLoad = function () {

        var _ = this,
            loadRange, cloneRange, rangeStart, rangeEnd;

        function loadImages(imagesScope) {

            $('img[data-lazy]', imagesScope).each(function () {

                var image = $(this),
                    imageSource = $(this).attr('data-lazy'),
                    imageSrcSet = $(this).attr('data-srcset'),
                    imageSizes = $(this).attr('data-sizes') || _.$slider.attr('data-sizes'),
                    imageToLoad = document.createElement('img');

                imageToLoad.onload = function () {

                    image
                        .animate({ opacity: 0 }, 100, function () {

                            if (imageSrcSet) {
                                image
                                    .attr('srcset', imageSrcSet);

                                if (imageSizes) {
                                    image
                                        .attr('sizes', imageSizes);
                                }
                            }

                            image
                                .attr('src', imageSource)
                                .animate({ opacity: 1 }, 200, function () {
                                    image
                                        .removeAttr('data-lazy data-srcset data-sizes')
                                        .removeClass('slick-loading');
                                });
                            _.$slider.trigger('lazyLoaded', [_, image, imageSource]);
                        });

                };

                imageToLoad.onerror = function () {

                    image
                        .removeAttr('data-lazy')
                        .removeClass('slick-loading')
                        .addClass('slick-lazyload-error');

                    _.$slider.trigger('lazyLoadError', [_, image, imageSource]);

                };

                imageToLoad.src = imageSource;

            });

        }

        if (_.options.centerMode === true) {
            if (_.options.infinite === true) {
                rangeStart = _.currentSlide + (_.options.slidesToShow / 2 + 1);
                rangeEnd = rangeStart + _.options.slidesToShow + 2;
            } else {
                rangeStart = Math.max(0, _.currentSlide - (_.options.slidesToShow / 2 + 1));
                rangeEnd = 2 + (_.options.slidesToShow / 2 + 1) + _.currentSlide;
            }
        } else {
            rangeStart = _.options.infinite ? _.options.slidesToShow + _.currentSlide : _.currentSlide;
            rangeEnd = Math.ceil(rangeStart + _.options.slidesToShow);
            if (_.options.fade === true) {
                if (rangeStart > 0) rangeStart--;
                if (rangeEnd <= _.slideCount) rangeEnd++;
            }
        }

        loadRange = _.$slider.find('.slick-slide').slice(rangeStart, rangeEnd);

        if (_.options.lazyLoad === 'anticipated') {
            var prevSlide = rangeStart - 1,
                nextSlide = rangeEnd,
                $slides = _.$slider.find('.slick-slide');

            for (var i = 0; i < _.options.slidesToScroll; i++) {
                if (prevSlide < 0) prevSlide = _.slideCount - 1;
                loadRange = loadRange.add($slides.eq(prevSlide));
                loadRange = loadRange.add($slides.eq(nextSlide));
                prevSlide--;
                nextSlide++;
            }
        }

        loadImages(loadRange);

        if (_.slideCount <= _.options.slidesToShow) {
            cloneRange = _.$slider.find('.slick-slide');
            loadImages(cloneRange);
        } else
        if (_.currentSlide >= _.slideCount - _.options.slidesToShow) {
            cloneRange = _.$slider.find('.slick-cloned').slice(0, _.options.slidesToShow);
            loadImages(cloneRange);
        } else if (_.currentSlide === 0) {
            cloneRange = _.$slider.find('.slick-cloned').slice(_.options.slidesToShow * -1);
            loadImages(cloneRange);
        }

    };

    Slick.prototype.loadSlider = function () {

        var _ = this;

        _.setPosition();

        _.$slideTrack.css({
            opacity: 1
        });

        _.$slider.removeClass('slick-loading');

        _.initUI();

        if (_.options.lazyLoad === 'progressive') {
            _.progressiveLazyLoad();
        }

    };

    Slick.prototype.next = Slick.prototype.slickNext = function () {

        var _ = this;

        _.changeSlide({
            data: {
                message: 'next'
            }
        });

    };

    Slick.prototype.orientationChange = function () {

        var _ = this;

        _.checkResponsive();
        _.setPosition();

    };

    Slick.prototype.pause = Slick.prototype.slickPause = function () {

        var _ = this;

        _.autoPlayClear();
        _.paused = true;

    };

    Slick.prototype.play = Slick.prototype.slickPlay = function () {

        var _ = this;

        _.autoPlay();
        _.options.autoplay = true;
        _.paused = false;
        _.focussed = false;
        _.interrupted = false;

    };

    Slick.prototype.postSlide = function (index) {

        var _ = this;

        if (!_.unslicked) {

            _.$slider.trigger('afterChange', [_, index]);

            _.animating = false;

            if (_.slideCount > _.options.slidesToShow) {
                _.setPosition();
            }

            _.swipeLeft = null;

            if (_.options.autoplay) {
                _.autoPlay();
            }

            if (_.options.accessibility === true) {
                _.initADA();

                if (_.options.focusOnChange) {
                    var $currentSlide = $(_.$slides.get(_.currentSlide));
                    $currentSlide.attr('tabindex', 0).focus();
                }
            }

        }

    };

    Slick.prototype.prev = Slick.prototype.slickPrev = function () {

        var _ = this;

        _.changeSlide({
            data: {
                message: 'previous'
            }
        });

    };

    Slick.prototype.preventDefault = function (event) {

        event.preventDefault();

    };

    Slick.prototype.progressiveLazyLoad = function (tryCount) {

        tryCount = tryCount || 1;

        var _ = this,
            $imgsToLoad = $('img[data-lazy]', _.$slider),
            image,
            imageSource,
            imageSrcSet,
            imageSizes,
            imageToLoad;

        if ($imgsToLoad.length) {

            image = $imgsToLoad.first();
            imageSource = image.attr('data-lazy');
            imageSrcSet = image.attr('data-srcset');
            imageSizes = image.attr('data-sizes') || _.$slider.attr('data-sizes');
            imageToLoad = document.createElement('img');

            imageToLoad.onload = function () {

                if (imageSrcSet) {
                    image
                        .attr('srcset', imageSrcSet);

                    if (imageSizes) {
                        image
                            .attr('sizes', imageSizes);
                    }
                }

                image
                    .attr('src', imageSource)
                    .removeAttr('data-lazy data-srcset data-sizes')
                    .removeClass('slick-loading');

                if (_.options.adaptiveHeight === true) {
                    _.setPosition();
                }

                _.$slider.trigger('lazyLoaded', [_, image, imageSource]);
                _.progressiveLazyLoad();

            };

            imageToLoad.onerror = function () {

                if (tryCount < 3) {

                    /**
                     * try to load the image 3 times,
                     * leave a slight delay so we don't get
                     * servers blocking the request.
                     */
                    setTimeout(function () {
                        _.progressiveLazyLoad(tryCount + 1);
                    }, 500);

                } else {

                    image
                        .removeAttr('data-lazy')
                        .removeClass('slick-loading')
                        .addClass('slick-lazyload-error');

                    _.$slider.trigger('lazyLoadError', [_, image, imageSource]);

                    _.progressiveLazyLoad();

                }

            };

            imageToLoad.src = imageSource;

        } else {

            _.$slider.trigger('allImagesLoaded', [_]);

        }

    };

    Slick.prototype.refresh = function (initializing) {

        var _ = this, currentSlide, lastVisibleIndex;

        lastVisibleIndex = _.slideCount - _.options.slidesToShow;

        // in non-infinite sliders, we don't want to go past the
        // last visible index.
        if (!_.options.infinite && (_.currentSlide > lastVisibleIndex)) {
            _.currentSlide = lastVisibleIndex;
        }

        // if less slides than to show, go to start.
        if (_.slideCount <= _.options.slidesToShow) {
            _.currentSlide = 0;

        }

        currentSlide = _.currentSlide;

        _.destroy(true);

        $.extend(_, _.initials, { currentSlide: currentSlide });

        _.init();

        if (!initializing) {

            _.changeSlide({
                data: {
                    message: 'index',
                    index: currentSlide
                }
            }, false);

        }

    };

    Slick.prototype.registerBreakpoints = function () {

        var _ = this, breakpoint, currentBreakpoint, l,
            responsiveSettings = _.options.responsive || null;

        if ($.type(responsiveSettings) === 'array' && responsiveSettings.length) {

            _.respondTo = _.options.respondTo || 'window';

            for (breakpoint in responsiveSettings) {

                l = _.breakpoints.length - 1;

                if (responsiveSettings.hasOwnProperty(breakpoint)) {
                    currentBreakpoint = responsiveSettings[breakpoint].breakpoint;

                    // loop through the breakpoints and cut out any existing
                    // ones with the same breakpoint number, we don't want dupes.
                    while (l >= 0) {
                        if (_.breakpoints[l] && _.breakpoints[l] === currentBreakpoint) {
                            _.breakpoints.splice(l, 1);
                        }
                        l--;
                    }

                    _.breakpoints.push(currentBreakpoint);
                    _.breakpointSettings[currentBreakpoint] = responsiveSettings[breakpoint].settings;

                }

            }

            _.breakpoints.sort(function (a, b) {
                return (_.options.mobileFirst) ? a - b : b - a;
            });

        }

    };

    Slick.prototype.reinit = function () {

        var _ = this;

        _.$slides =
            _.$slideTrack
                .children(_.options.slide)
                .addClass('slick-slide');

        _.slideCount = _.$slides.length;

        if (_.currentSlide >= _.slideCount && _.currentSlide !== 0) {
            _.currentSlide = _.currentSlide - _.options.slidesToScroll;
        }

        if (_.slideCount <= _.options.slidesToShow) {
            _.currentSlide = 0;
        }

        _.registerBreakpoints();

        _.setProps();
        _.setupInfinite();
        _.buildArrows();
        _.updateArrows();
        _.initArrowEvents();
        _.buildDots();
        _.updateDots();
        _.initDotEvents();
        _.cleanUpSlideEvents();
        _.initSlideEvents();

        _.checkResponsive(false, true);

        if (_.options.focusOnSelect === true) {
            $(_.$slideTrack).children().on('click.slick', _.selectHandler);
        }

        _.setSlideClasses(typeof _.currentSlide === 'number' ? _.currentSlide : 0);

        _.setPosition();
        _.focusHandler();

        _.paused = !_.options.autoplay;
        _.autoPlay();

        _.$slider.trigger('reInit', [_]);

    };

    Slick.prototype.resize = function () {

        var _ = this;

        if ($(window).width() !== _.windowWidth) {
            clearTimeout(_.windowDelay);
            _.windowDelay = window.setTimeout(function () {
                _.windowWidth = $(window).width();
                _.checkResponsive();
                if (!_.unslicked) { _.setPosition(); }
            }, 50);
        }
    };

    Slick.prototype.removeSlide = Slick.prototype.slickRemove = function (index, removeBefore, removeAll) {

        var _ = this;

        if (typeof (index) === 'boolean') {
            removeBefore = index;
            index = removeBefore === true ? 0 : _.slideCount - 1;
        } else {
            index = removeBefore === true ? --index : index;
        }

        if (_.slideCount < 1 || index < 0 || index > _.slideCount - 1) {
            return false;
        }

        _.unload();

        if (removeAll === true) {
            _.$slideTrack.children().remove();
        } else {
            _.$slideTrack.children(this.options.slide).eq(index).remove();
        }

        _.$slides = _.$slideTrack.children(this.options.slide);

        _.$slideTrack.children(this.options.slide).detach();

        _.$slideTrack.append(_.$slides);

        _.$slidesCache = _.$slides;

        _.reinit();

    };

    Slick.prototype.setCSS = function (position) {

        var _ = this,
            positionProps = {},
            x, y;

        if (_.options.rtl === true) {
            position = -position;
        }
        x = _.positionProp == 'left' ? Math.ceil(position) + 'px' : '0px';
        y = _.positionProp == 'top' ? Math.ceil(position) + 'px' : '0px';

        positionProps[_.positionProp] = position;

        if (_.transformsEnabled === false) {
            _.$slideTrack.css(positionProps);
        } else {
            positionProps = {};
            if (_.cssTransitions === false) {
                positionProps[_.animType] = 'translate(' + x + ', ' + y + ')';
                _.$slideTrack.css(positionProps);
            } else {
                positionProps[_.animType] = 'translate3d(' + x + ', ' + y + ', 0px)';
                _.$slideTrack.css(positionProps);
            }
        }

    };

    Slick.prototype.setDimensions = function () {

        var _ = this;

        if (_.options.vertical === false) {
            if (_.options.centerMode === true) {
                _.$list.css({
                    padding: ('0px ' + _.options.centerPadding)
                });
            }
        } else {
            _.$list.height(_.$slides.first().outerHeight(true) * _.options.slidesToShow);
            if (_.options.centerMode === true) {
                _.$list.css({
                    padding: (_.options.centerPadding + ' 0px')
                });
            }
        }

        _.listWidth = _.$list.width();
        _.listHeight = _.$list.height();


        if (_.options.vertical === false && _.options.variableWidth === false) {
            _.slideWidth = Math.ceil(_.listWidth / _.options.slidesToShow);
            _.$slideTrack.width(Math.ceil((_.slideWidth * _.$slideTrack.children('.slick-slide').length)));

        } else if (_.options.variableWidth === true) {
            _.$slideTrack.width(5000 * _.slideCount);
        } else {
            _.slideWidth = Math.ceil(_.listWidth);
            _.$slideTrack.height(Math.ceil((_.$slides.first().outerHeight(true) * _.$slideTrack.children('.slick-slide').length)));
        }

        var offset = _.$slides.first().outerWidth(true) - _.$slides.first().width();
        if (_.options.variableWidth === false) _.$slideTrack.children('.slick-slide').width(_.slideWidth - offset);

    };

    Slick.prototype.setFade = function () {

        var _ = this,
            targetLeft;

        _.$slides.each(function (index, element) {
            targetLeft = (_.slideWidth * index) * -1;
            if (_.options.rtl === true) {
                $(element).css({
                    position: 'relative',
                    right: targetLeft,
                    top: 0,
                    zIndex: _.options.zIndex - 2,
                    opacity: 0
                });
            } else {
                $(element).css({
                    position: 'relative',
                    left: targetLeft,
                    top: 0,
                    zIndex: _.options.zIndex - 2,
                    opacity: 0
                });
            }
        });

        _.$slides.eq(_.currentSlide).css({
            zIndex: _.options.zIndex - 1,
            opacity: 1
        });

    };

    Slick.prototype.setHeight = function () {

        var _ = this;

        if (_.options.slidesToShow === 1 && _.options.adaptiveHeight === true && _.options.vertical === false) {
            var targetHeight = _.$slides.eq(_.currentSlide).outerHeight(true);
            _.$list.css('height', targetHeight);
        }

    };

    Slick.prototype.setOption =
        Slick.prototype.slickSetOption = function () {

            /**
             * accepts arguments in format of:
             *
             *  - for changing a single option's value:
             *     .slick("setOption", option, value, refresh )
             *
             *  - for changing a set of responsive options:
             *     .slick("setOption", 'responsive', [{}, ...], refresh )
             *
             *  - for updating multiple values at once (not responsive)
             *     .slick("setOption", { 'option': value, ... }, refresh )
             */

            var _ = this, l, item, option, value, refresh = false, type;

            if ($.type(arguments[0]) === 'object') {

                option = arguments[0];
                refresh = arguments[1];
                type = 'multiple';

            } else if ($.type(arguments[0]) === 'string') {

                option = arguments[0];
                value = arguments[1];
                refresh = arguments[2];

                if (arguments[0] === 'responsive' && $.type(arguments[1]) === 'array') {

                    type = 'responsive';

                } else if (typeof arguments[1] !== 'undefined') {

                    type = 'single';

                }

            }

            if (type === 'single') {

                _.options[option] = value;


            } else if (type === 'multiple') {

                $.each(option, function (opt, val) {

                    _.options[opt] = val;

                });


            } else if (type === 'responsive') {

                for (item in value) {

                    if ($.type(_.options.responsive) !== 'array') {

                        _.options.responsive = [value[item]];

                    } else {

                        l = _.options.responsive.length - 1;

                        // loop through the responsive object and splice out duplicates.
                        while (l >= 0) {

                            if (_.options.responsive[l].breakpoint === value[item].breakpoint) {

                                _.options.responsive.splice(l, 1);

                            }

                            l--;

                        }

                        _.options.responsive.push(value[item]);

                    }

                }

            }

            if (refresh) {

                _.unload();
                _.reinit();

            }

        };

    Slick.prototype.setPosition = function () {

        var _ = this;

        _.setDimensions();

        _.setHeight();

        if (_.options.fade === false) {
            _.setCSS(_.getLeft(_.currentSlide));
        } else {
            _.setFade();
        }

        _.$slider.trigger('setPosition', [_]);

    };

    Slick.prototype.setProps = function () {

        var _ = this,
            bodyStyle = document.body.style;

        _.positionProp = _.options.vertical === true ? 'top' : 'left';

        if (_.positionProp === 'top') {
            _.$slider.addClass('slick-vertical');
        } else {
            _.$slider.removeClass('slick-vertical');
        }

        if (bodyStyle.WebkitTransition !== undefined ||
            bodyStyle.MozTransition !== undefined ||
            bodyStyle.msTransition !== undefined) {
            if (_.options.useCSS === true) {
                _.cssTransitions = true;
            }
        }

        if (_.options.fade) {
            if (typeof _.options.zIndex === 'number') {
                if (_.options.zIndex < 3) {
                    _.options.zIndex = 3;
                }
            } else {
                _.options.zIndex = _.defaults.zIndex;
            }
        }

        if (bodyStyle.OTransform !== undefined) {
            _.animType = 'OTransform';
            _.transformType = '-o-transform';
            _.transitionType = 'OTransition';
            if (bodyStyle.perspectiveProperty === undefined && bodyStyle.webkitPerspective === undefined) _.animType = false;
        }
        if (bodyStyle.MozTransform !== undefined) {
            _.animType = 'MozTransform';
            _.transformType = '-moz-transform';
            _.transitionType = 'MozTransition';
            if (bodyStyle.perspectiveProperty === undefined && bodyStyle.MozPerspective === undefined) _.animType = false;
        }
        if (bodyStyle.webkitTransform !== undefined) {
            _.animType = 'webkitTransform';
            _.transformType = '-webkit-transform';
            _.transitionType = 'webkitTransition';
            if (bodyStyle.perspectiveProperty === undefined && bodyStyle.webkitPerspective === undefined) _.animType = false;
        }
        if (bodyStyle.msTransform !== undefined) {
            _.animType = 'msTransform';
            _.transformType = '-ms-transform';
            _.transitionType = 'msTransition';
            if (bodyStyle.msTransform === undefined) _.animType = false;
        }
        if (bodyStyle.transform !== undefined && _.animType !== false) {
            _.animType = 'transform';
            _.transformType = 'transform';
            _.transitionType = 'transition';
        }
        _.transformsEnabled = _.options.useTransform && (_.animType !== null && _.animType !== false);
    };


    //Slick.prototype.setSlideClasses = function(index) {
    Slick.prototype.setSlideClasses = function (index, oldSlide) {
        var _ = this,
            centerOffset, allSlides, indexOffset, remainder;

        allSlides = _.$slider
            .find('.slick-slide')
            .removeClass('slick-active slick-center slick-current')
            .attr('aria-hidden', 'true');

        _.$slides
            .eq(index)
            .addClass('slick-current');

        if (oldSlide != undefined) {
            if (index == 0 && oldSlide != 1) {
                var _current = this.$slides.eq(this.$slides.size() - 1);
                var __index = allSlides.index(_current);
                var ss = allSlides.eq(__index + 1);
                ss.addClass('slick-current');
            }
            if (index == this.$slides.size() - 1 && oldSlide != this.$slides.size() - 2) {
                var _current = this.$slides.eq(0);
                var __index = allSlides.index(_current);
                var ss = allSlides.eq(__index - 1);
                ss.addClass('slick-current');
            }
        }

        if (_.options.centerMode === true) {

            var evenCoef = _.options.slidesToShow % 2 === 0 ? 1 : 0;

            centerOffset = Math.floor(_.options.slidesToShow / 2);

            if (_.options.infinite === true) {

                if (index >= centerOffset && index <= (_.slideCount - 1) - centerOffset) {
                    _.$slides
                        .slice(index - centerOffset + evenCoef, index + centerOffset + 1)
                        .addClass('slick-active')
                        .attr('aria-hidden', 'false');

                } else {

                    indexOffset = _.options.slidesToShow + index;
                    allSlides
                        .slice(indexOffset - centerOffset + 1 + evenCoef, indexOffset + centerOffset + 2)
                        .addClass('slick-active')
                        .attr('aria-hidden', 'false');

                }

                if (index === 0) {

                    allSlides
                        .eq(allSlides.length - 1 - _.options.slidesToShow)
                        .addClass('slick-center');

                } else if (index === _.slideCount - 1) {

                    allSlides
                        .eq(_.options.slidesToShow)
                        .addClass('slick-center');

                }

            }

            _.$slides
                .eq(index)
                .addClass('slick-center');

        } else {

            if (index >= 0 && index <= (_.slideCount - _.options.slidesToShow)) {

                _.$slides
                    .slice(index, index + _.options.slidesToShow)
                    .addClass('slick-active')
                    .attr('aria-hidden', 'false');

            } else if (allSlides.length <= _.options.slidesToShow) {

                allSlides
                    .addClass('slick-active')
                    .attr('aria-hidden', 'false');

            } else {

                remainder = _.slideCount % _.options.slidesToShow;
                indexOffset = _.options.infinite === true ? _.options.slidesToShow + index : index;

                if (_.options.slidesToShow == _.options.slidesToScroll && (_.slideCount - index) < _.options.slidesToShow) {

                    allSlides
                        .slice(indexOffset - (_.options.slidesToShow - remainder), indexOffset + remainder)
                        .addClass('slick-active')
                        .attr('aria-hidden', 'false');

                } else {

                    allSlides
                        .slice(indexOffset, indexOffset + _.options.slidesToShow)
                        .addClass('slick-active')
                        .attr('aria-hidden', 'false');

                }

            }

        }

        if (_.options.lazyLoad === 'ondemand' || _.options.lazyLoad === 'anticipated') {
            _.lazyLoad();
        }
    };

    Slick.prototype.setupInfinite = function () {

        var _ = this,
            i, slideIndex, infiniteCount;

        if (_.options.fade === true) {
            _.options.centerMode = false;
        }

        if (_.options.infinite === true && _.options.fade === false) {

            slideIndex = null;

            if (_.slideCount > _.options.slidesToShow) {

                if (_.options.centerMode === true) {
                    infiniteCount = _.options.slidesToShow + 1;
                } else {
                    infiniteCount = _.options.slidesToShow;
                }

                for (i = _.slideCount; i > (_.slideCount -
                    infiniteCount); i -= 1) {
                    slideIndex = i - 1;
                    $(_.$slides[slideIndex]).clone(true).attr('id', '')
                        .attr('data-slick-index', slideIndex - _.slideCount)
                        .prependTo(_.$slideTrack).addClass('slick-cloned');
                }
                for (i = 0; i < infiniteCount + _.slideCount; i += 1) {
                    slideIndex = i;
                    $(_.$slides[slideIndex]).clone(true).attr('id', '')
                        .attr('data-slick-index', slideIndex + _.slideCount)
                        .appendTo(_.$slideTrack).addClass('slick-cloned');
                }
                _.$slideTrack.find('.slick-cloned').find('[id]').each(function () {
                    $(this).attr('id', '');
                });

            }

        }

    };

    Slick.prototype.interrupt = function (toggle) {

        var _ = this;

        if (!toggle) {
            _.autoPlay();
        }
        _.interrupted = toggle;

    };

    Slick.prototype.selectHandler = function (event) {

        var _ = this;

        var targetElement =
            $(event.target).is('.slick-slide') ?
                $(event.target) :
                $(event.target).parents('.slick-slide');

        var index = parseInt(targetElement.attr('data-slick-index'));

        if (!index) index = 0;

        if (_.slideCount <= _.options.slidesToShow) {

            _.slideHandler(index, false, true);
            return;

        }

        _.slideHandler(index);

    };

    Slick.prototype.slideHandler = function (index, sync, dontAnimate) {

        var targetSlide, animSlide, oldSlide, slideLeft, targetLeft = null,
            _ = this, navTarget;

        sync = sync || false;

        if (_.animating === true && _.options.waitForAnimate === true) {
            return;
        }

        if (_.options.fade === true && _.currentSlide === index) {
            return;
        }

        if (sync === false) {
            _.asNavFor(index);
        }

        targetSlide = index;
        targetLeft = _.getLeft(targetSlide);
        slideLeft = _.getLeft(_.currentSlide);

        _.currentLeft = _.swipeLeft === null ? slideLeft : _.swipeLeft;

        if (_.options.infinite === false && _.options.centerMode === false && (index < 0 || index > _.getDotCount() * _.options.slidesToScroll)) {
            if (_.options.fade === false) {
                targetSlide = _.currentSlide;
                if (dontAnimate !== true && _.slideCount > _.options.slidesToShow) {
                    _.animateSlide(slideLeft, function () {
                        _.postSlide(targetSlide);
                    });
                } else {
                    _.postSlide(targetSlide);
                }
            }
            return;
        } else if (_.options.infinite === false && _.options.centerMode === true && (index < 0 || index > (_.slideCount - _.options.slidesToScroll))) {
            if (_.options.fade === false) {
                targetSlide = _.currentSlide;
                if (dontAnimate !== true && _.slideCount > _.options.slidesToShow) {
                    _.animateSlide(slideLeft, function () {
                        _.postSlide(targetSlide);
                    });
                } else {
                    _.postSlide(targetSlide);
                }
            }
            return;
        }

        if (_.options.autoplay) {
            clearInterval(_.autoPlayTimer);
        }

        if (targetSlide < 0) {
            if (_.slideCount % _.options.slidesToScroll !== 0) {
                animSlide = _.slideCount - (_.slideCount % _.options.slidesToScroll);
            } else {
                animSlide = _.slideCount + targetSlide;
            }
        } else if (targetSlide >= _.slideCount) {
            if (_.slideCount % _.options.slidesToScroll !== 0) {
                animSlide = 0;
            } else {
                animSlide = targetSlide - _.slideCount;
            }
        } else {
            animSlide = targetSlide;
        }

        _.animating = true;

        _.$slider.trigger('beforeChange', [_, _.currentSlide, animSlide]);

        oldSlide = _.currentSlide;
        _.currentSlide = animSlide;
        _.setSlideClasses(_.currentSlide, oldSlide);

        if (_.options.asNavFor) {

            navTarget = _.getNavTarget();
            navTarget = navTarget.slick('getSlick');

            if (navTarget.slideCount <= navTarget.options.slidesToShow) {
                navTarget.setSlideClasses(_.currentSlide);
            }

        }

        _.updateDots();
        _.updateArrows();

        if (_.options.fade === true) {
            if (dontAnimate !== true) {

                _.fadeSlideOut(oldSlide);

                _.fadeSlide(animSlide, function () {
                    _.postSlide(animSlide);
                });

            } else {
                _.postSlide(animSlide);
            }
            _.animateHeight();
            return;
        }

        if (dontAnimate !== true && _.slideCount > _.options.slidesToShow) {
            _.animateSlide(targetLeft, function () {
                _.postSlide(animSlide);
            });
        } else {
            _.postSlide(animSlide);
        }

    };

    Slick.prototype.startLoad = function () {

        var _ = this;

        if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {

            _.$prevArrow.hide();
            _.$nextArrow.hide();

        }

        if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {

            _.$dots.hide();

        }

        _.$slider.addClass('slick-loading');

    };

    Slick.prototype.swipeDirection = function () {

        var xDist, yDist, r, swipeAngle, _ = this;

        xDist = _.touchObject.startX - _.touchObject.curX;
        yDist = _.touchObject.startY - _.touchObject.curY;
        r = Math.atan2(yDist, xDist);

        swipeAngle = Math.round(r * 180 / Math.PI);
        if (swipeAngle < 0) {
            swipeAngle = 360 - Math.abs(swipeAngle);
        }

        if ((swipeAngle <= 45) && (swipeAngle >= 0)) {
            return (_.options.rtl === false ? 'left' : 'right');
        }
        if ((swipeAngle <= 360) && (swipeAngle >= 315)) {
            return (_.options.rtl === false ? 'left' : 'right');
        }
        if ((swipeAngle >= 135) && (swipeAngle <= 225)) {
            return (_.options.rtl === false ? 'right' : 'left');
        }
        if (_.options.verticalSwiping === true) {
            if ((swipeAngle >= 35) && (swipeAngle <= 135)) {
                return 'down';
            } else {
                return 'up';
            }
        }

        return 'vertical';

    };

    Slick.prototype.swipeEnd = function (event) {

        var _ = this,
            slideCount,
            direction;

        _.dragging = false;
        _.swiping = false;

        if (_.scrolling) {
            _.scrolling = false;
            return false;
        }

        _.interrupted = false;
        _.shouldClick = (_.touchObject.swipeLength > 10) ? false : true;

        if (_.touchObject.curX === undefined) {
            return false;
        }

        if (_.touchObject.edgeHit === true) {
            _.$slider.trigger('edge', [_, _.swipeDirection()]);
        }

        if (_.touchObject.swipeLength >= _.touchObject.minSwipe) {

            direction = _.swipeDirection();

            switch (direction) {

                case 'left':
                case 'down':

                    slideCount =
                        _.options.swipeToSlide ?
                            _.checkNavigable(_.currentSlide + _.getSlideCount()) :
                            _.currentSlide + _.getSlideCount();

                    _.currentDirection = 0;

                    break;

                case 'right':
                case 'up':

                    slideCount =
                        _.options.swipeToSlide ?
                            _.checkNavigable(_.currentSlide - _.getSlideCount()) :
                            _.currentSlide - _.getSlideCount();

                    _.currentDirection = 1;

                    break;

                default:


            }

            if (direction != 'vertical') {

                _.slideHandler(slideCount);
                _.touchObject = {};
                _.$slider.trigger('swipe', [_, direction]);

            }

        } else {

            if (_.touchObject.startX !== _.touchObject.curX) {

                _.slideHandler(_.currentSlide);
                _.touchObject = {};

            }

        }

    };

    Slick.prototype.swipeHandler = function (event) {

        var _ = this;

        if ((_.options.swipe === false) || ('ontouchend' in document && _.options.swipe === false)) {
            return;
        } else if (_.options.draggable === false && event.type.indexOf('mouse') !== -1) {
            return;
        }

        _.touchObject.fingerCount = event.originalEvent && event.originalEvent.touches !== undefined ?
            event.originalEvent.touches.length : 1;

        _.touchObject.minSwipe = _.listWidth / _.options
            .touchThreshold;

        if (_.options.verticalSwiping === true) {
            _.touchObject.minSwipe = _.listHeight / _.options
                .touchThreshold;
        }

        switch (event.data.action) {

            case 'start':
                _.swipeStart(event);
                break;

            case 'move':
                _.swipeMove(event);
                break;

            case 'end':
                _.swipeEnd(event);
                break;

        }

    };

    Slick.prototype.swipeMove = function (event) {

        var _ = this,
            edgeWasHit = false,
            curLeft, swipeDirection, swipeLength, positionOffset, touches, verticalSwipeLength;

        touches = event.originalEvent !== undefined ? event.originalEvent.touches : null;

        if (!_.dragging || _.scrolling || touches && touches.length !== 1) {
            return false;
        }

        curLeft = _.getLeft(_.currentSlide);

        _.touchObject.curX = touches !== undefined ? touches[0].pageX : event.clientX;
        _.touchObject.curY = touches !== undefined ? touches[0].pageY : event.clientY;

        _.touchObject.swipeLength = Math.round(Math.sqrt(
            Math.pow(_.touchObject.curX - _.touchObject.startX, 2)));

        verticalSwipeLength = Math.round(Math.sqrt(
            Math.pow(_.touchObject.curY - _.touchObject.startY, 2)));

        if (!_.options.verticalSwiping && !_.swiping && verticalSwipeLength > 4) {
            _.scrolling = true;
            return false;
        }

        if (_.options.verticalSwiping === true) {
            _.touchObject.swipeLength = verticalSwipeLength;
        }

        swipeDirection = _.swipeDirection();

        if (event.originalEvent !== undefined && _.touchObject.swipeLength > 4) {
            _.swiping = true;
            event.preventDefault();
        }

        positionOffset = (_.options.rtl === false ? 1 : -1) * (_.touchObject.curX > _.touchObject.startX ? 1 : -1);
        if (_.options.verticalSwiping === true) {
            positionOffset = _.touchObject.curY > _.touchObject.startY ? 1 : -1;
        }


        swipeLength = _.touchObject.swipeLength;

        _.touchObject.edgeHit = false;

        if (_.options.infinite === false) {
            if ((_.currentSlide === 0 && swipeDirection === 'right') || (_.currentSlide >= _.getDotCount() && swipeDirection === 'left')) {
                swipeLength = _.touchObject.swipeLength * _.options.edgeFriction;
                _.touchObject.edgeHit = true;
            }
        }

        if (_.options.vertical === false) {
            _.swipeLeft = curLeft + swipeLength * positionOffset;
        } else {
            _.swipeLeft = curLeft + (swipeLength * (_.$list.height() / _.listWidth)) * positionOffset;
        }
        if (_.options.verticalSwiping === true) {
            _.swipeLeft = curLeft + swipeLength * positionOffset;
        }

        if (_.options.fade === true || _.options.touchMove === false) {
            return false;
        }

        if (_.animating === true) {
            _.swipeLeft = null;
            return false;
        }

        _.setCSS(_.swipeLeft);

    };

    Slick.prototype.swipeStart = function (event) {

        var _ = this,
            touches;

        _.interrupted = true;

        if (_.touchObject.fingerCount !== 1 || _.slideCount <= _.options.slidesToShow) {
            _.touchObject = {};
            return false;
        }

        if (event.originalEvent !== undefined && event.originalEvent.touches !== undefined) {
            touches = event.originalEvent.touches[0];
        }

        _.touchObject.startX = _.touchObject.curX = touches !== undefined ? touches.pageX : event.clientX;
        _.touchObject.startY = _.touchObject.curY = touches !== undefined ? touches.pageY : event.clientY;

        _.dragging = true;

    };

    Slick.prototype.unfilterSlides = Slick.prototype.slickUnfilter = function () {

        var _ = this;

        if (_.$slidesCache !== null) {

            _.unload();

            _.$slideTrack.children(this.options.slide).detach();

            _.$slidesCache.appendTo(_.$slideTrack);

            _.reinit();

        }

    };

    Slick.prototype.unload = function () {

        var _ = this;

        $('.slick-cloned', _.$slider).remove();

        if (_.$dots) {
            _.$dots.remove();
        }

        if (_.$prevArrow && _.htmlExpr.test(_.options.prevArrow)) {
            _.$prevArrow.remove();
        }

        if (_.$nextArrow && _.htmlExpr.test(_.options.nextArrow)) {
            _.$nextArrow.remove();
        }

        _.$slides
            .removeClass('slick-slide slick-active slick-visible slick-current')
            .attr('aria-hidden', 'true')
            .css('width', '');

    };

    Slick.prototype.unslick = function (fromBreakpoint) {

        var _ = this;
        _.$slider.trigger('unslick', [_, fromBreakpoint]);
        _.destroy();

    };

    Slick.prototype.updateArrows = function () {

        var _ = this,
            centerOffset;

        centerOffset = Math.floor(_.options.slidesToShow / 2);

        if (_.options.arrows === true &&
            _.slideCount > _.options.slidesToShow &&
            !_.options.infinite) {

            _.$prevArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');
            _.$nextArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');

            if (_.currentSlide === 0) {

                _.$prevArrow.addClass('slick-disabled').attr('aria-disabled', 'true');
                _.$nextArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');

            } else if (_.currentSlide >= _.slideCount - _.options.slidesToShow && _.options.centerMode === false) {

                _.$nextArrow.addClass('slick-disabled').attr('aria-disabled', 'true');
                _.$prevArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');

            } else if (_.currentSlide >= _.slideCount - 1 && _.options.centerMode === true) {

                _.$nextArrow.addClass('slick-disabled').attr('aria-disabled', 'true');
                _.$prevArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');

            }

        }

    };

    Slick.prototype.updateDots = function () {

        var _ = this;

        if (_.$dots !== null) {

            _.$dots
                .find('li')
                .removeClass('slick-active')
                .end();

            _.$dots
                .find('li')
                .eq(Math.floor(_.currentSlide / _.options.slidesToScroll))
                .addClass('slick-active');

        }

    };

    Slick.prototype.visibility = function () {

        var _ = this;

        if (_.options.autoplay) {

            if (document[_.hidden]) {

                _.interrupted = true;

            } else {

                _.interrupted = false;

            }

        }

    };

    $.fn.slick = function () {
        var _ = this,
            opt = arguments[0],
            args = Array.prototype.slice.call(arguments, 1),
            l = _.length,
            i,
            ret;
        for (i = 0; i < l; i++) {
            if (typeof opt == 'object' || typeof opt == 'undefined')
                _[i].slick = new Slick(_[i], opt);
            else
                ret = _[i].slick[opt].apply(_[i].slick, args);
            if (typeof ret != 'undefined') return ret;
        }
        return _;
    };

}));

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function slickSlide(option) {

    var wrap = $(option.wrapEl);
    var slide = wrap.find(option.slideEl);
    var ctr = wrap.find(option.ctrEl);
    var count = Boolean(option.countEl);
    var progressType = Boolean(option.progressType)
    var autoPlay = option.slideOption.autoplay;
    var navslide = $(option.navSlideEl);

    if (option.customType.search('dotInTitle') !== -1) {
        option.slideOption.customPaging = option.customPaging;
        wrap.find(option.dotEl).addClass("customPaging");
    } else {
        option.slideOption.customPaging = function (slider, i) {
            return '<button type="button" class="button"><i></i><span>' + (i + 1) + '</span></button>';
        }
    }

    if (option.slideType.search('video') !== -1) {
        // 비디오가 포함되어있는 슬라이드

        var time = option.slideOption.autoplaySpeed / 1000;
        if (option.progressType == "circle") {

            var svg, val;
            svg = wrap.find(option.svgEl).find(".circle-go");

        } else if (option.progressType == "dot-circle") {
            var svg, val;

        } else if (option.progressType == "bar" || option.progressType == "dot-bar") {
            var percentTime, val, isPause, tick;
        }


        function handleProgress(e) {
            if (isNaN(this.duration)) {
                this.addEventListener("loadedmetadata", function () {

                    if (option.progressType == "bar") {
                        wrap.find(option.barEl + " .bar").stop().animate({ width: "100%" }, this.duration * 1000);

                    } else if (option.progressType == "dot-bar") {
                        wrap.find(option.dotEl + " .slick-active .button i").stop().animate({ width: "100%" }, this.duration * 1000);

                    } else if (option.progressType == "circle") {
                        svg.stop().animate({ strokeDashoffset: 0 }, this.duration * 1000);

                    } else if (option.progressType == "dot-circle") {
                        wrap.find(option.dotEl).find(".slick-active .circle-go").stop().animate({ strokeDashoffset: 0 }, this.duration * 1000);

                    }
                });
            } else {

                if (option.progressType == "bar") {
                    wrap.find(option.barEl + " .bar").stop().animate({ width: "100%" }, this.duration * 1000);

                } else if (option.progressType == "dot-bar") {
                    wrap.find(option.dotEl + " .slick-active .button i").stop().animate({ width: "100%" }, this.duration * 1000);

                } else if (option.progressType == "circle") {
                    svg.stop().animate({ strokeDashoffset: 0 }, this.duration * 1000);

                } else if (option.progressType == "dot-circle") {
                    wrap.find(option.dotEl).find(".slick-active .circle-go").stop().animate({ strokeDashoffset: 0 }, this.duration * 1000);

                }
            }

        }


        function videoControl(item, idx) {
            if (progressType) {
                if (option.progressType == "bar") {
                    wrap.find(option.barEl + " .bar").stop().css({ "width": '0%' });
                } else if (option.progressType == "dot-bar") {
                    wrap.find(option.dotEl + " .button i").stop().css({ "width": '0%' });
                } else if (option.progressType == "circle") {
                    svg.stop().css({ strokeDashoffset: "120" });
                } else if (option.progressType == "dot-circle") {
                    wrap.find(option.dotEl).find(".circle-go").stop().css({ strokeDashoffset: "120" });
                }
            }
            var video = item.find("video");

            video.get(0).currentTime = 0;
            video.get(0).play();
            wrap.find(option.stopBtn).show()
            wrap.find(option.playBtn).hide();
            if (progressType) {

                video.get(0).addEventListener('play', handleProgress);
            }
            video.on("ended", function () {
                video.get(0).currentTime = 0;
                video.get(0).pause();
                slide.slick("slickNext");
            });

        }

        function resetTime() {
            clearTimeout(tick);
            if (option.progressType == "bar") {
                wrap.find(option.barEl + " .bar").stop().css({ "width": '0%' });

            } else if (option.progressType == "dot-bar") {
                wrap.find(option.dotEl + " .button i").stop().css({ "width": '0%' });

            } else if (option.progressType == "circle") {
                svg.stop().css({ strokeDashoffset: "120" });

            } else if (option.progressType == "dot-circle") {
                wrap.find(option.dotEl).find(".circle-go").stop().css({ strokeDashoffset: "120" });
            }
        }

        function slideImgstart() {
            resetTime();
            percentTime = 0;
            val = 0;
            isPause = false;
            tick = setInterval(interval, 10);
            if (progressType) {
                if (option.progressType == "bar") {
                    wrap.find(option.barEl + " .bar").stop().css({ "width": '0%' });
                    wrap.find(option.barEl + " .bar").stop().animate({ width: "100%" }, option.slideOption.autoplaySpeed);
                } else if (option.progressType == "dot-bar") {
                    wrap.find(option.dotEl + "  .button i").stop().css({ "width": '0%' });
                    wrap.find(option.dotEl + " .slick-active .button i").stop().animate({ width: "100%" }, option.slideOption.autoplaySpeed);
                }
            }
        }

        function interval() {
            if (isPause === false) {
                if (option.progressType == "circle") {
                    percentTime += 1 / (time + 0.1);
                    val += 1.2 / (time + 0.1);
                    svg.css({
                        strokeDashoffset: 120 - val
                    });
                    if (percentTime >= 100) {
                        resetTime();
                        slide.slick("slickNext");

                    }
                } else if (option.progressType == "dot-circle") {
                    percentTime += 1 / (time + 0.1);
                    val += 1.2 / (time + 0.1);
                    wrap.find(option.dotEl).find(".slick-active .circle-go").css({
                        strokeDashoffset: 120 - val
                    });
                    if (percentTime >= 100) {
                        resetTime();
                        slide.slick("slickNext");

                    }
                } else {
                    percentTime += 1 / (time + 0.1);
                    if (percentTime >= 100) {
                        resetTime();
                        slide.slick("slickNext");

                    }
                }

            }
        }


        slide.on('init', function (e, slick) {

            if (progressType) {
                if (option.progressType == "bar") {
                    wrap.find(option.barEl).html('<span class="bar"></span>');
                } else if (option.progressType == "dot-circle") {

                    if (!option.navSlide) {
                        wrap.find(".slick-dots").addClass("dot-circle")
                        tag = '<svg class="progress-svg" width="40" height="40">'
                            + '<g transform = "translate(20,20)" >'
                            + '<circle class="circle-bg" r="19" cx="0" cy="0"> </circle>'
                            + '<circle class="circle-go" r="19" cx="0" cy="0"> </circle>'
                            + '</g >'
                            + '</svg >';
                        wrap.find(".slick-dots .button").append(tag)
                        svg = wrap.find(option.dotEl).find(".slick-active .circle-go");
                    }

                }
            }
            if (option.progressType == "pageProgress") {
                var widthPer = 100 / slick.slideCount
                wrap.find(option.barEl).html('<span class="bar"></span>');
                wrap.find(option.barEl + ' .bar').animate({ width: 1 * widthPer + '%' }, 500)
            }

            var $item = slick.$slides.eq(slick.currentSlide);

            if (autoPlay) {
                if (!($item.find("video").length == 0)) {
                    videoControl($item, slick.currentSlide);

                } else {
                    slideImgstart();
                }
            }


            if (slick.$slides.length <= slick.options.slidesToShow) {
                ctr.hide();
            }

            if (count == true) {
                if (option.num) {
                    var crrentNum = parseInt(slick.currentSlide + 1);
                    if (slick.slideCount > 9) { var totalNum = slick.slideCount; } else { var totalNum = "0" + slick.slideCount; }
                    wrap.find(option.countEl).html('<span class="current">0' + crrentNum + '</span> <span class="line"><em>/ </em></span><span class="count">' + totalNum + '</span>');
                } else {
                    wrap.find(option.countEl).html('<span class="current">' + parseInt(slick.currentSlide + 1) + '</span> <span class="line"><em>/ </em></span><span class="count">' + slick.slideCount + '</span>');
                }
            }
            if (option.customType.search('arrInTitle') !== -1) {
                var nextEl = parseInt(slick.currentSlide + 1)
                var prevEl = parseInt(slick.currentSlide - 1)
                if (prevEl == -1) {
                    prevEl = slick.$slides.length - 1
                }
                var nextSpan = slick.$slides.find(option.slideItem).eq(nextEl).attr("data-title");
                var prevSpan = slick.$slides.find(option.slideItem).eq(prevEl).attr("data-title");
                $(option.wrapEl).find(option.nextBtn).append('<em>' + nextSpan + '</em>')
                $(option.wrapEl).find(option.prevBtn).append('<em>' + prevSpan + '</em>')
            }



        });
        if (navslide && option.progressType == "dot-circle") {
            navslide.on('init', function (e, slick) {
                wrap.find(".slick-dots").addClass("dot-circle")
                tag = '<svg class="progress-svg" width="40" height="40">'
                    + '<g transform = "translate(20,20)" >'
                    + '<circle class="circle-bg" r="19" cx="0" cy="0"> </circle>'
                    + '<circle class="circle-go" r="19" cx="0" cy="0"> </circle>'
                    + '</g >'
                    + '</svg >';
                wrap.find(".slick-dots .button").append(tag)
                svg = wrap.find(option.dotEl).find(".slick-active .circle-go");
            })
        }
        slide.on("afterChange", function (e, slick, currentSlide) {


            var $item = slick.$slides.eq(currentSlide);
            if (!($item.find("video").length == 0)) {
                videoControl($item, currentSlide);
            } else {
                slideImgstart();
            }
            if (option.customType.search('arrInTitle') !== -1) {
                var nextEl = parseInt(slick.currentSlide + 1)
                if (nextEl == slick.$slides.length) {
                    nextEl = 0
                }
                var prevEl = parseInt(slick.currentSlide - 1)
                if (prevEl == -1) {
                    prevEl = slick.$slides.length - 1
                }
                var nextSpan = slick.$slides.find(option.slideItem).eq(nextEl).attr("data-title");
                var prevSpan = slick.$slides.find(option.slideItem).eq(prevEl).attr("data-title");
                $(option.wrapEl).find(option.nextBtn).children('em').html(nextSpan)
                $(option.wrapEl).find(option.prevBtn).children('em').html(prevSpan)
            }
            if (option.progressType == "pageProgress") {
                var widthPer = 100 / slick.slideCount
                wrap.find(option.barEl + ' .bar').animate({ width: (slick.currentSlide + 1) * widthPer + '%' }, 500)
            }
        });
        slide.on("beforeChange", function (e, slick, currentSlide, nextSlide) {
            var $item = slick.$slides.eq(currentSlide);

            if (!($item.find("video").length == 0)) {
                $item.find("video").get(0).currentTime = 0;
                $item.find("video").get(0).pause();
            }
            if (count == true) {
                if (option.num) {
                    var crrentNum = parseInt(nextSlide + 1);
                    if (slick.slideCount > 9) { var totalNum = slick.slideCount; } else { var totalNum = "0" + slick.slideCount; }
                    wrap.find(option.countEl).html('<span class="current">0' + crrentNum + '</span> <span class="line"><em>/ </em></span><span class="count">' + totalNum + '</span>');

                } else {
                    wrap.find(option.countEl).html('<span class="current">' + parseInt(nextSlide + 1) + '</span> <span class="line"><em>/ </em></span><span class="count">' + slick.slideCount + '</span>');

                }
            }
        });

        slide.slick((_$$slick =
            option.slideOption,
            _defineProperty(_$$slick, 'autoplay', false),
            _defineProperty(_$$slick, 'arrows', option.arrows),
            _defineProperty(_$$slick, 'prevArrow', wrap.find(option.prevBtn)),
            _defineProperty(_$$slick, 'nextArrow', wrap.find(option.nextBtn)),
            _defineProperty(_$$slick, 'dots', option.dots),
            _defineProperty(_$$slick, 'appendDots', wrap.find(option.dotEl)),
            _$$slick));

        if (option.navSlide) {
            slide.slick('slickSetOption', 'asNavFor', option.navSlideEl, true);
            navslide.slick((_$$slick =
                option.navSlideOption,
                _defineProperty(_$$slick, 'asNavFor', slide),
                _defineProperty(_$$slick, 'arrows', false),
                _$$slick));
        }


        if (autoPlay) {
            wrap.find(option.playBtn).hide();
            wrap.find(option.stopBtn).show();
        } else {
            wrap.find(option.stopBtn).hide();
            wrap.find(option.playBtn).show();
        }

        wrap.find(option.stopBtn).on('click', function () {
            wrap.find(option.stopBtn).hide();
            wrap.find(option.playBtn).show().focus();
            var $item = slide[0].slick.$slides.eq(slide[0].slick.currentSlide);
            if (!($item.find("video").length == 0)) {
                $item.find("video").get(0).currentTime = 0;
                $item.find("video").get(0).pause();
                resetTime();
            } else {
                resetTime();
            }
        });
        wrap.find(option.playBtn).on('click', function () {
            wrap.find(option.stopBtn).show().focus();
            wrap.find(option.playBtn).hide();

            var $item = slide[0].slick.$slides.eq(slide[0].slick.currentSlide);
            if (!($item.find("video").length == 0)) {
                videoControl($item);
            } else {
                slideImgstart();
            }
        });

        wrap.find(option.nextBtn).on('click', function () {
            resetTime();
        })
        wrap.find(option.prevBtn).on('click', function () {
            resetTime();
        });

        if (progressType && option.progressType.search('pageProgress') == -1) {
            $(option.wrapEl).find(option.slideEl).on('mouseenter', function () {
                wrap.find(option.stopBtn).hide();
                wrap.find(option.playBtn).show();
                var $item = slide[0].slick.$slides.eq(slide[0].slick.currentSlide);
                if (!($item.find("video").length == 0)) {
                    $item.find("video").get(0).currentTime = 0;
                    $item.find("video").get(0).pause();
                    resetTime();
                } else {
                    resetTime();
                }
            });
            $(option.wrapEl).find(option.slideEl).on('mouseleave', function () {
                wrap.find(option.stopBtn).show();

                var $item = slide[0].slick.$slides.eq(slide[0].slick.currentSlide);
                if (!($item.find("video").length == 0)) {
                    videoControl($item);
                } else {
                    slideImgstart();
                }
            });
            $(option.wrapEl).find(option.dotEl).on('mouseenter', function () {
                wrap.find(option.stopBtn).hide();
                wrap.find(option.playBtn).show().focus();
                var $item = slide[0].slick.$slides.eq(slide[0].slick.currentSlide);
                if (!($item.find("video").length == 0)) {
                    $item.find("video").get(0).currentTime = 0;
                    $item.find("video").get(0).pause();
                    resetTime();
                } else {
                    resetTime();
                }
            });
            $(option.wrapEl).find(option.dotEl).on('mouseleave', function () {
                wrap.find(option.stopBtn).show().focus();
                wrap.find(option.playBtn).hide();

                var $item = slide[0].slick.$slides.eq(slide[0].slick.currentSlide);
                if (!($item.find("video").length == 0)) {
                    videoControl($item);
                } else {
                    slideImgstart();
                }
            });
            $(option.wrapEl).find(option.slideEl).on('focusin', function () {
                wrap.find(option.stopBtn).hide();
                wrap.find(option.playBtn).show().focus();
                var $item = slide[0].slick.$slides.eq(slide[0].slick.currentSlide);
                if (!($item.find("video").length == 0)) {
                    $item.find("video").get(0).currentTime = 0;
                    $item.find("video").get(0).pause();
                    resetTime();
                } else {
                    resetTime();
                }
            });
            $(option.wrapEl).find(option.slideEl).on('focusout', function () {
                wrap.find(option.stopBtn).show().focus();
                wrap.find(option.playBtn).hide();

                var $item = slide[0].slick.$slides.eq(slide[0].slick.currentSlide);
                if (!($item.find("video").length == 0)) {
                    videoControl($item);
                } else {
                    slideImgstart();
                }
            });
        }


    } else {
        if (option.progressType == "dot-bar") {
            var bar, isPause, tick, percentTime;
        } else if (option.progressType == "dot-circle") {
            var svg, val;
        }
        slide.on('init', function (e, slick) {
            if (slick.$slides.length <= slick.options.slidesToShow) {
                ctr.hide();
            }

            if (count == true) {
                if (option.num) {
                    var crrentNum = parseInt(slick.currentSlide + 1);
                    if (slick.slideCount > 9) { var totalNum = slick.slideCount; } else { var totalNum = "0" + slick.slideCount; }
                    if (crrentNum < 10){
                        wrap.find(option.countEl).html('<span class="current">0' + crrentNum + '</span> <span class="line"><em>/ </em></span><span class="count">' + totalNum + '</span>');
                    }else{
                        wrap.find(option.countEl).html('<span class="current">' + crrentNum + '</span> <span class="line"><em>/ </em></span><span class="count">' + totalNum + '</span>');
                    }

                } else {
                    wrap.find(option.countEl).html('<span class="current">' + parseInt(slick.currentSlide + 1) + '</span> <span class="line"><em>/ </em></span><span class="count">' + slick.slideCount + '</span>');
                }
            }

            if (option.progressType == "dot-bar") {
                wrap.addClass("dot-bar")
            } else if (option.progressType == "dot-circle") {

                wrap.find(".slick-dots").addClass("dot-circle")
                tag = '<svg class="progress-svg" width="40" height="40">'
                    + '<g transform = "translate(20,20)" >'
                    + '<circle class="circle-bg" r="19" cx="0" cy="0"> </circle>'
                    + '<circle class="circle-go" r="19" cx="0" cy="0"> </circle>'
                    + '</g >'
                    + '</svg >';
                wrap.find(".button").append(tag)
                svg = wrap.find(option.dotEl).find(".slick-active .circle-go");
            }
            if (option.customType.search('arrInTitle') !== -1) {
                var nextEl = parseInt(slick.currentSlide + 1)
                var prevEl = parseInt(slick.currentSlide - 1)
                if (prevEl == -1) {
                    prevEl = slick.$slides.length - 1
                }
                var nextSpan = slick.$slides.find(option.slideItem).eq(nextEl).attr("data-title");
                var prevSpan = slick.$slides.find(option.slideItem).eq(prevEl).attr("data-title");
                $(option.wrapEl).find(option.nextBtn).append('<em>' + nextSpan + '</em>')
                $(option.wrapEl).find(option.prevBtn).append('<em>' + prevSpan + '</em>')
            }
            if (option.progressType == "pageProgress") {
                var widthPer = 100 / slick.slideCount
                wrap.find(option.barEl).html('<span class="bar"></span>');
                wrap.find(option.barEl + ' .bar').animate({ width: 1 * widthPer + '%' }, 500)
            }

        });
        if (option.navSlide && option.progressType == "dot-circle") {
            navslide.on('init', function (e, slick) {
                wrap.find(".slick-dots").addClass("dot-circle")
                tag = '<svg class="progress-svg" width="40" height="40">'
                    + '<g transform = "translate(20,20)" >'
                    + '<circle class="circle-bg" r="19" cx="0" cy="0"> </circle>'
                    + '<circle class="circle-go" r="19" cx="0" cy="0"> </circle>'
                    + '</g >'
                    + '</svg >';
                wrap.find(".button").append(tag)
                svg = wrap.find(option.dotEl).find(".slick-active .circle-go");
            });
        }


        slide.slick((_$$slick =
            option.slideOption,
            _defineProperty(_$$slick, 'arrows', option.arrows),
            _defineProperty(_$$slick, 'prevArrow', wrap.find(option.prevBtn)),
            _defineProperty(_$$slick, 'nextArrow', wrap.find(option.nextBtn)),
            _defineProperty(_$$slick, 'dots', option.dots),
            _defineProperty(_$$slick, 'appendDots', wrap.find(option.dotEl)),
            _$$slick));

        if (option.navSlide) {
            slide.slick('slickSetOption', 'asNavFor', option.navSlideEl, true);

            navslide.slick((_$$slick =
                option.navSlideOption,
                _defineProperty(_$$slick, 'asNavFor', slide),
                _defineProperty(_$$slick, 'arrows', false),
                _$$slick));
        }
        slide.on("afterChange", function (e, slick, currentSlide) {
            if (option.customType.search('arrInTitle') !== -1) {
                var nextEl = parseInt(slick.currentSlide + 1)
                if (nextEl == slick.$slides.length) {
                    nextEl = 0
                }
                var prevEl = parseInt(slick.currentSlide - 1)
                if (prevEl == -1) {
                    prevEl = slick.$slides.length - 1
                }
                var nextSpan = slick.$slides.find(option.slideItem).eq(nextEl).attr("data-title");
                var prevSpan = slick.$slides.find(option.slideItem).eq(prevEl).attr("data-title");
                $(option.wrapEl).find(option.nextBtn).children('em').html(nextSpan)
                $(option.wrapEl).find(option.prevBtn).children('em').html(prevSpan)
            }
            if (option.progressType == "pageProgress") {
                var widthPer = 100 / slick.slideCount
                wrap.find(option.barEl + ' .bar').animate({ width: (slick.currentSlide + 1) * widthPer + '%' }, 500)
            }
        });

        if (option.slideOption.autoplay) {
            wrap.find(option.playBtn).hide();
            wrap.find(option.stopBtn).show();
        } else {
            wrap.find(option.stopBtn).hide();
            wrap.find(option.playBtn).show();
        }
        wrap.find(option.stopBtn).on('click', function () {
            wrap.find(option.stopBtn).hide();
            wrap.find(option.playBtn).show().focus();
            slide
                .slick('slickPause')
                .slick('slickSetOption', true);
        });
        wrap.find(option.playBtn).on('click', function () {
            wrap.find(option.stopBtn).show().focus();
            wrap.find(option.playBtn).hide();
            slide
                .slick('slickPlay')
                .slick('slickSetOption', true);
        });
        if (option.progressType == "bar" && option.slideOption.autoplay) {

            var time = option.slideOption.autoplaySpeed / 1000;
            var bar, isPause, tick, percentTime;
            wrap.find(option.barEl).html('<span class="bar"></span>')
            bar = wrap.find(option.barEl).find('.bar');
            function startProgressbar() {
                resetProgressbar();
                percentTime = 0;
                isPause = false;
                tick = setInterval(interval, 10);
            }

            function interval() {
                if (isPause === false) {
                    percentTime += 1 / (time + 0.1);
                    if (percentTime > 100) {
                        bar.css({
                            width: "100%"
                        });
                    } else {
                        bar.css({
                            width: percentTime + "%"
                        });
                    }
                    if (percentTime > 100) {
                        slide.slick("slickNext");
                        startProgressbar();
                    }
                }
            }
            function resetProgressbar() {
                bar.css({ width: 0 + "%" });
                clearTimeout(tick);
            }

            slide.on("beforeChange", function (e, slick, currentSlide, nextSlide) {
                startProgressbar();


                if (count == true) {
                    if (option.num) {
                        var crrentNum = parseInt(nextSlide + 1);
                        if (slick.slideCount > 9) { var totalNum = slick.slideCount; } else { var totalNum = "0" + slick.slideCount; }
                        if (crrentNum < 10) {
                            wrap.find(option.countEl).html('<span class="current">0' + crrentNum + '</span> <span class="line"><em>/ </em></span><span class="count">' + totalNum + '</span>');
                        } else {
                            wrap.find(option.countEl).html('<span class="current">' + crrentNum + '</span> <span class="line"><em>/ </em></span><span class="count">' + totalNum + '</span>');
                        }

                    } else {
                        wrap.find(option.countEl).html('<span class="current">' + parseInt(nextSlide + 1) + '</span> <span class="line"><em>/ </em></span><span class="count">' + slick.slideCount + '</span>');

                    }
                }
            });


            wrap.find(option.stopBtn).click(function () {
                wrap.find(option.stopBtn).hide();
                wrap.find(option.playBtn).show().focus();
                resetProgressbar()
            });
            wrap.find(option.playBtn).click(function () {
                wrap.find(option.playBtn).hide()
                wrap.find(option.stopBtn).show().focus();
                startProgressbar()
            });

            startProgressbar();


        } else if (option.progressType == "circle" && option.slideOption.autoplay) {
            var bar, isPause, tick, percentTime, svg, val;
            var time = option.slideOption.autoplaySpeed / 1000;

            svg = wrap.find(option.svgEl).find(".circle-go");
            function startProgressbar() {
                resetProgressbar();
                percentTime = 0;
                val = 0;
                isPause = false;
                tick = setInterval(interval, 10);
            }

            function interval() {
                if (isPause === false) {

                    percentTime += 1 / (time + 0.1);
                    val += 1.2 / (time + 0.1);

                    svg.css({
                        strokeDashoffset: 120 - val
                    });
                    if (percentTime >= 100) {

                        slide.slick("slickNext");
                        startProgressbar();
                    }
                }
            }
            function resetProgressbar() {

                svg.css({
                    strokeDashoffset: "120"
                });
                clearTimeout(tick);
            }


            slide.on("beforeChange", function (e, slick, currentSlide, nextSlide) {
                startProgressbar();


                if (count == true) {
                    if (option.num) {
                        var crrentNum = parseInt(nextSlide + 1);
                        if (slick.slideCount > 9) { var totalNum = slick.slideCount; } else { var totalNum = "0" + slick.slideCount; }
                        if (crrentNum < 10) {
                            wrap.find(option.countEl).html('<span class="current">0' + crrentNum + '</span> <span class="line"><em>/ </em></span><span class="count">' + totalNum + '</span>');
                        } else {
                            wrap.find(option.countEl).html('<span class="current">' + crrentNum + '</span> <span class="line"><em>/ </em></span><span class="count">' + totalNum + '</span>');
                        }

                    } else {
                        wrap.find(option.countEl).html('<span class="current">' + parseInt(nextSlide + 1) + '</span> <span class="line"><em>/ </em></span><span class="count">' + slick.slideCount + '</span>');

                    }
                }
            });


            wrap.find(option.stopBtn).click(function () {
                wrap.find(option.stopBtn).hide();
                wrap.find(option.playBtn).show().focus();
                resetProgressbar()
            });
            wrap.find(option.playBtn).click(function () {
                wrap.find(option.playBtn).hide()
                wrap.find(option.stopBtn).show().focus();
                startProgressbar()
            });

            startProgressbar();

        } else if (option.progressType == "dot-bar" && option.slideOption.autoplay) {

            var time = option.slideOption.autoplaySpeed / 1000;

            function startProgressbar() {
                resetProgressbar();
                bar = wrap.find(option.dotEl).find('.slick-active .button i');

                percentTime = 0;
                isPause = false;
                tick = setInterval(interval, 10);
            }

            function interval() {
                if (isPause === false) {
                    percentTime += 1 / (time + 0.1);
                    if (percentTime > 100) {
                        bar.css({
                            width: "100%"
                        });
                    } else {
                        bar.css({
                            width: percentTime + "%"
                        });

                    }
                    if (percentTime > 100) {
                        slide.slick("slickNext");
                        startProgressbar();
                    }
                }
            }
            function resetProgressbar() {
                wrap.find(option.dotEl).find('.button i').css({ width: 0 + "%" });
                clearTimeout(tick);
            }

            slide.on("beforeChange", function (e, slick, currentSlide, nextSlide) {
                startProgressbar();


                if (count == true) {
                    if (option.num) {
                        var crrentNum = parseInt(nextSlide + 1);
                        if (slick.slideCount > 9) { var totalNum = slick.slideCount; } else { var totalNum = "0" + slick.slideCount; }
                        if (crrentNum < 10) {
                            wrap.find(option.countEl).html('<span class="current">0' + crrentNum + '</span> <span class="line"><em>/ </em></span><span class="count">' + totalNum + '</span>');
                        } else {
                            wrap.find(option.countEl).html('<span class="current">' + crrentNum + '</span> <span class="line"><em>/ </em></span><span class="count">' + totalNum + '</span>');
                        }

                    } else {
                        wrap.find(option.countEl).html('<span class="current">' + parseInt(nextSlide + 1) + '</span> <span class="line"><em>/ </em></span><span class="count">' + slick.slideCount + '</span>');

                    }
                }
            });


            wrap.find(option.stopBtn).click(function () {
                wrap.find(option.stopBtn).hide();
                wrap.find(option.playBtn).show().focus();
                resetProgressbar()
            });
            wrap.find(option.playBtn).click(function () {
                wrap.find(option.playBtn).hide()
                wrap.find(option.stopBtn).show().focus();
                startProgressbar()
            });
            if (autoPlay) {
                startProgressbar();
            }

        } else if (option.progressType == "dot-circle" && option.slideOption.autoplay) {
            var time = option.slideOption.autoplaySpeed / 1000;

            function startProgressbar() {
                resetProgressbar();
                percentTime = 0;
                val = 0;
                isPause = false;
                tick = setInterval(interval, 10);
            }

            function interval() {
                if (isPause === false) {

                    percentTime += 1 / (time + 0.1);
                    val += 1.2 / (time + 0.1);
                    wrap.find(option.dotEl).find(".slick-active .circle-go").css({
                        strokeDashoffset: 120 - val
                    });
                    if (percentTime >= 100) {
                        resetTime();
                        slide.slick("slickNext");

                    }
                } else {
                    percentTime += 1 / (time + 0.1);
                    if (percentTime >= 100) {
                        resetTime();
                        slide.slick("slickNext");

                    }
                }
            }

            function resetProgressbar() {
                wrap.find(option.dotEl).find(".circle-go").stop().css({ strokeDashoffset: "120" });
                clearTimeout(tick);
            }

            slide.on("beforeChange", function (e, slick, currentSlide, nextSlide) {
                startProgressbar();


                if (count == true) {
                    if (option.num) {
                        var crrentNum = parseInt(nextSlide + 1);
                        if (slick.slideCount > 9) { var totalNum = slick.slideCount; } else { var totalNum = "0" + slick.slideCount; }
                        if (crrentNum < 10) {
                            wrap.find(option.countEl).html('<span class="current">0' + crrentNum + '</span> <span class="line"><em>/ </em></span><span class="count">' + totalNum + '</span>');
                        } else {
                            wrap.find(option.countEl).html('<span class="current">' + crrentNum + '</span> <span class="line"><em>/ </em></span><span class="count">' + totalNum + '</span>');
                        }

                    } else {
                        wrap.find(option.countEl).html('<span class="current">' + parseInt(nextSlide + 1) + '</span> <span class="line"><em>/ </em></span><span class="count">' + slick.slideCount + '</span>');

                    }
                }
            });


            wrap.find(option.stopBtn).click(function () {
                wrap.find(option.stopBtn).hide();
                wrap.find(option.playBtn).show().focus();
                resetProgressbar()
            });
            wrap.find(option.playBtn).click(function () {
                wrap.find(option.playBtn).hide()
                wrap.find(option.stopBtn).show().focus();
                startProgressbar()
            });
            if (autoPlay) {
                startProgressbar();
            }

        }else{
            slide.on("beforeChange", function (e, slick, currentSlide, nextSlide) {
                if (count == true) {
                    if (option.num) {
                        var crrentNum = parseInt(nextSlide + 1);
                        if (slick.slideCount > 9) { var totalNum = slick.slideCount; } else { var totalNum = "0" + slick.slideCount; }
                        if (crrentNum < 10) {
                            wrap.find(option.countEl).html('<span class="current">0' + crrentNum + '</span> <span class="line"><em>/ </em></span><span class="count">' + totalNum + '</span>');
                        } else {
                            wrap.find(option.countEl).html('<span class="current">' + crrentNum + '</span> <span class="line"><em>/ </em></span><span class="count">' + totalNum + '</span>');
                        }

                    } else {
                        wrap.find(option.countEl).html('<span class="current">' + parseInt(nextSlide + 1) + '</span> <span class="line"><em>/ </em></span><span class="count">' + slick.slideCount + '</span>');

                    }
                }
            });
        }


        if (progressType && option.progressType.search('pageProgress') == -1) {
            $(option.wrapEl).find(option.slideEl).on('mouseenter', function () {
                resetProgressbar();
                wrap.find(option.stopBtn).hide();
                wrap.find(option.playBtn).show();
            });
            $(option.wrapEl).find(option.slideEl).on('mouseleave', function () {
                startProgressbar();
                wrap.find(option.stopBtn).show();
                wrap.find(option.playBtn).hide();
            });
            $(option.wrapEl).find(option.dotEl).on('mouseenter', function () {
                resetProgressbar();
                wrap.find(option.stopBtn).hide();
                wrap.find(option.playBtn).show();
            });
            $(option.wrapEl).find(option.dotEl).on('mouseleave', function () {
                startProgressbar();
                wrap.find(option.stopBtn).show();
                wrap.find(option.playBtn).hide();
            });
            $(option.wrapEl).find(option.slideEl).on('focusin', function () {
                resetProgressbar();
                wrap.find(option.stopBtn).hide();
                wrap.find(option.playBtn).show();
            });
            $(option.wrapEl).find(option.slideEl).on('focusout', function () {
                startProgressbar();
                wrap.find(option.stopBtn).show();
                wrap.find(option.playBtn).hide();
            });
        }
    }
    $(window).on('resize orientationchange', function () {
        slide.slick('resize');
        slide.slick('init');
    });
}


/*
jQuery(document).ready(function(){
    npPfsStartup(document.form, false, true, false, false, "npkencrypt", "key");
});
*/
