/** DOMTokenList */
// https://github.com/Alhadis/Fix-IE/edit/master/src/token-list.js
!function(){"use strict";var n,r,t,e,i=window,o=document,u=Object,f=null,a=!0,c=!1,l=" ",s="Element",d="create"+s,h="DOMTokenList",m="__defineGetter__",p="defineProperty",v="class",g="List",y=v+g,w="rel",L=w+g,_="div",b="length",j="contains",S="apply",k="HTML",E=("item "+j+" add remove toggle toString toLocaleString").split(l),A=E[2],C=E[3],M=E[4],N="prototype",O=p in u||m in u[N]||f,T=function(n,r,t,e){u[p]?u[p](n,r,{configurable:c===O?a:!!e,get:t}):n[m](r,t)},x=function(r,t){var e=this,i=[],o={},f=0,s=0,d=function(){if(f>=s)for(;f>s;++s)(function(n){T(e,n,function(){return h(),i[n]},c)})(s)},h=function(){var n,e,u=arguments,c=/\s+/;if(u[b])for(e=0;e<u[b];++e)if(c.test(u[e]))throw n=new SyntaxError('String "'+u[e]+'" '+j+" an invalid character"),n.code=5,n.name="InvalidCharacterError",n;for(i=(""+r[t]).replace(/^\s+|\s+$/g,"").split(c),""===i[0]&&(i=[]),o={},e=0;e<i[b];++e)o[i[e]]=a;f=i[b],d()};return h(),T(e,b,function(){return h(),f}),e[E[6]]=e[E[5]]=function(){return h(),i.join(l)},e.item=function(n){return h(),i[n]},e[j]=function(n){return h(),!!o[n]},e[A]=function(){h[S](e,n=arguments);for(var n,u,c=0,s=n[b];s>c;++c)u=n[c],o[u]||(i.push(u),o[u]=a);f!==i[b]&&(f=i[b]>>>0,r[t]=i.join(l),d())},e[C]=function(){h[S](e,n=arguments);for(var n,u={},c=0,s=[];c<n[b];++c)u[n[c]]=a,delete o[n[c]];for(c=0;c<i[b];++c)u[i[c]]||s.push(i[c]);i=s,f=s[b]>>>0,r[t]=i.join(l),d()},e[M]=function(r,t){return h[S](e,[r]),n!==t?t?(e[A](r),a):(e[C](r),c):o[r]?(e[C](r),c):(e[A](r),a)},function(n,r){if(r)for(var t=0;7>t;++t)r(n,E[t],{enumerable:c})}(e,u[p]),e},D=function(n,r,t){T(n[N],r,function(){var n,e=this,i=m+p+r;if(e[i])return n;if(e[i]=a,c===O){for(var u,f=D.mirror=D.mirror||o[d](_),l=f.childNodes,s=l[b],h=0;s>h;++h)if(l[h]._R===e){u=l[h];break}u||(u=f.appendChild(o[d](_))),n=x.call(u,e,t)}else n=new x(e,t);return T(e,r,function(){return n}),delete e[i],n},a)};if(i[h])r=o[d](_)[y],N=i[h][N],r[A][S](r,E),2>r[b]&&(t=N[A],e=N[C],N[A]=function(){for(var n=0,r=arguments;n<r[b];++n)t.call(this,r[n])},N[C]=function(){for(var n=0,r=arguments;n<r[b];++n)e.call(this,r[n])}),r[M](g,c)&&(N[M]=function(r,t){var e=this;return e[(t=n===t?!e[j](r):t)?A:C](r),!!t});else{if(O)try{T({},"support")}catch(G){O=c}x.polyfill=a,i[h]=x,D(i[s],y,v+"Name"),D(i[k+"Link"+s],L,w),D(i[k+"Anchor"+s],L,w),D(i[k+"Area"+s],L,w)}}();


var doc = document,
    win = window,
    body = doc.body,
    raf = win.requestAnimationFrame
      || win.webkitRequestAnimationFrame
      || win.mozRequestAnimationFrame
      || win.msRequestAnimationFrame
      || function(cb) { return setTimeout(cb, 16); },
    initialize_class = 'initialized',
    active_class = 'active',
    event_listener_support = Element.prototype.addEventListener,
    sliderInit = function(el) {
      el.classList.remove('slider-fallback');
      el.classList.add(initializeClass);
    };

doc.documentElement.classList.remove('no-js');
doc.documentElement.classList.add('js');

function btn_fns (str) {
  var attr = 'data-' + str,
      btns = doc.querySelectorAll('[' + attr + ']');
  if (btns.length) {
    forEach(btns, function (btn) {
      var target = doc.querySelector(btn.getAttribute(attr));
      if (target) {
        function btn_core () {
          switch(str) {
            case 'toggle':
              target.classList.toggle(active_class);
              btn.classList.toggle('expanded');
              break;
            case 'add':
              target.classList.add(active_class);
              break;
            case 'remove':
              target.classList.remove(active_class);
              break;
          }
        }

        if (event_listener_support) {
          btn.addEventListener('click', btn_core)
        } else {
          btn.onclick = btn_core;
        }
      }
    });
  }
}
btn_fns('toggle');
btn_fns('add');
btn_fns('remove');

if (event_listener_support) {
  win.addEventListener('click', cancel_click);
} else {
  win.onclick = function(e) {
    cancel_click(e);
  }
}

function cancel_click (e) {
  e = e || window.event;
  var target = e.target || e.srcElement,
      active_els = doc.querySelectorAll('.nav-wrap.active, .keywordOver.active, .select-star-wrapper.active');

  if (target && !lookupByType(target, 'button', ['div', 'ul', 'li', 'article', 'section']) && active_els.length) {
    var active_parent = lookupByClass(target, 'active');

    forEach(active_els, function(el) {
      if (!active_parent || el !== active_parent) {
        el.classList.remove(active_class);
      }
    });
  }
}


function do_panup (selector) {
  var container = doc.querySelector(selector);
  if (container) {
    var items = container.children,
        count = items.length,
        current = 1;

    if (count >= 2) {
      container.classList.add('panup');
      items[0].classList.add('in');

      setTimeout(function() {
        container.classList.add(active_class);
      }, 1000);

      setInterval(function(e) {

        var out_el = current ? items[current - 1] : items[count - 1];
        out_el.className = 'out';
        setTimeout(function() {
          out_el.className = '';
        }, 600);

        items[current].className = 'in';

        current = current === count - 1 ? 0 : current + 1;

      }, 4000);
    }
  }
}
do_panup('.keyword ul');
do_panup('.prayerRQ .prayer');

// home sliders
var mainBox_wrapper = doc.querySelector('.mainBox-slider'),
    mainBox_nav = doc.querySelector('.mainBox-nav'),
    mainBox_count = doc.querySelector('.mainBox .titleBox .count'),
    mainBox_current = doc.querySelector('.mainBox .titleBox .current-index');
if (mainBox_wrapper && mainBox_nav) {
  var mainBox_slider = tns({
    container: mainBox_wrapper,
    autoplay: true,
    autoplayTimeout: 5000,
    // gutter: 10,
    navContainer: mainBox_nav,
    controls: false,
    loop: true,
    onInit: function(info) {
      mainBox_count.innerHTML = info.slideCount;
    },
  });

  mainBox_slider.events.on('transitionStart', function(info) {
    mainBox_current.innerHTML = info.displayIndex;
  });
}

var logo_box_wrapper = doc.querySelector('.logoBox-slider'),
    logo_box_controls = doc.querySelector('.logoBox .titleBox .arrow'),
    logo_box_nav = doc.querySelector('.logoBox .titleBox ul');
if (logo_box_wrapper) {
  var logo_box_slider = tns({
    container: logo_box_wrapper,
    gutter: 10,
    controlsContainer: logo_box_controls,
    navContainer: logo_box_nav,
  });
  
  preventLinkDefault(logo_box_nav);
}

var cmTv_wrapper = doc.querySelector('.cmTv-slider'),
    cmTv_controls = doc.querySelector('.cmTv-controls'),
    cmTv_nav = doc.querySelector('.cmTv-nav'),
    cmTv_count = doc.querySelector('.cmTv .titleBox .count'),
    cmTv_current = doc.querySelector('.cmTv .titleBox .current-index');
if (cmTv_wrapper) {
  var cmTv_slider = tns({
    container: cmTv_wrapper,
    // gutter: 10,
    controlsContainer: cmTv_controls,
    navContainer: cmTv_nav,
    onInit: function(info) {
      cmTv_count.innerHTML = info.slideCount;
    },
  });

  cmTv_slider.events.on('transitionStart', function(info) {
    cmTv_current.innerHTML = info.displayIndex;
  });

  preventLinkDefault(cmTv_nav);
}

var img_wrapper = doc.querySelector('.img-slider'),
    img_prev = doc.querySelector('.img-slider-tools .prev'),
    img_next = doc.querySelector('.img-slider-tools .next'),
    img_count = doc.querySelector('.img-slider-tools .count'),
    img_current = doc.querySelector('.img-slider-tools .current-index');
if (img_wrapper && img_prev && img_next) {
  var img_slider = tns({
    container: img_wrapper,
    gutter: 10,
    prevButton: img_prev,
    nextButton: img_next,
    nav: false,
    loop: false,
    autoHeight: true,
    onInit: function(info) {
      img_count.innerHTML = info.slideCount;
    },
  });

  img_slider.events.on('transitionStart', function(info) {
    img_current.innerHTML = info.displayIndex;
  });
}

var featuredBox_wrapper = doc.querySelector('.featuredBox-slider'),
    featuredBox_nav = doc.querySelector('.featuredBox .titleBox ul');
if (featuredBox_wrapper) {
  var featuredBox_slider = tns({
    container: featuredBox_wrapper,
    gutter: 10,
    navContainer: featuredBox_nav,
    controls: false,
    loop: false,
    autoHeight: true,
  });

  preventLinkDefault(featuredBox_nav);
}

var comicNav_wrapper = doc.querySelector('.comic-nav-slider ul');
if (comicNav_wrapper) {
  var comicNav_slider = tns({
    container: comicNav_wrapper,
    // gutter: 10,
    slideBy: 'page',
    items: 2,
    nav: false,
    loop: false,
    responsive: {
      400: { items: 3 },
      500: { items: 4 },
      640: { items: 5 },
      900: { items: 6 },
      1100: { items: 7 },
    }
  });
}

// select stars
var selectStarBox = doc.querySelector('.select-star-wrapper'),
    selectedBox = doc.querySelector('.select-star-wrapper .selected');
    selectedStar = doc.querySelector('.select-star-wrapper .selected .webtoon-star'),
    selectedStarInput = doc.querySelector('#selected-star');
if (selectStarBox && selectedStar) {
  var optionBox = selectStarBox.querySelector('.select-star');
  if (event_listener_support) {
    optionBox.addEventListener('click', starSelection);
  } else {
    optionBox.onclick = starSelection;
  }
}

function starSelection (e) {
  e = e || window.event;
  var target = e.target || e.srcElement,
      starEl = target.nodeName.toLowerCase() === 'li' ? target.children[0] : lookupByClass(target, 'webtoon-star'),
      exp = /\bstar\d+\b/,
      starStr = exp.exec(starEl.className)[0];

  if (starStr) {
    selectedStar.className = selectedStar.className.replace(exp, starStr);
    selectedStarInput.value = starStr;
  }
  selectStarBox.classList.remove('active');
  selectedBox.classList.remove('expanded');
  console.log(selectedStarInput.value);
}

// utility functions
function preventLinkDefault (el) {
  if (el) {
    var links = el.querySelectorAll('a');
    if (links.length) {
      forEach(links, function(link) {
        if (event_listener_support) {
          link.addEventListener('click', function(e) {
            e.preventDefault();
          });
        } else {
          link.onclick = function(e) {
            e = e || window.event;
            e.preventDefault ? e.preventDefault() : (e.returnValue = false);
          }
        }
      });
    }
  }
}
function forEach (arr, callback, scope) {
  for (var i = 0, l = arr.length; i < l; i++) {
    callback.call(scope, arr[i], i);
  }
}

function lookupByClass (el, cla) {
  if (el === body) { return null; }
  return typeof el.className !== 'string' || el.className.indexOf(cla) < 0 ? lookupByClass(el.parentNode, cla) : el;
}

function lookupByType (el, target_name, arr) {
  if (!arr.length) { arr.push('body'); }
  var name = el.nodeName.toLowerCase();
  if (arr.indexOf(name) >= 0) { return null; }
  return name !== target_name ? lookupByType(el.parentNode, target_name, arr) : el;
}

function getOffsetTop (el) {
  return el.getBoundingClientRect().top + document.documentElement.scrollTop;
}
