// jQuery additional element 
// JavaScript glider

$(document).ready(function() {
    var hash = location.hash.replace(/^#/, '');
    var start = hash == 'firefox' ? 2 : 1;
    var opt = {
        start: start,
        itemLastOutCallback: itemLastOutCallback,
        buttonNextCallback: buttonNextCallback,
        buttonPrevCallback: buttonPrevCallback
    };
    $('#gliderParent').jcarousel(opt);
});

function itemLastOutCallback(evt, state, prevLast) {
  var sectionId = (prevLast == 1) ? "firefox" : "shiretoko";
  
  // スムーズスクロール
  var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
  var offset = $('#gliderBoxTop').offset();
  if (scrollTop > offset.top && offset) {
    VCOMN.smoothScroll("gliderBoxTop");
  }
  
  // アクセス解析
  track_dynamic_page_view(sectionId);
  
  // 戻る/進む対応
  location.hash = "#" + sectionId;
}

function buttonCallback(parent, button, enabled, imageNames) {
    var imgs = $('img', button);
    if (!imgs.length) return;
    if (!button._exts) {
        var initial = true;
        button._exts = [];
        for (var i = 0; i < imgs.length; i++) {
            button._exts[i] = imgs[i].src.replace(/^.*(\.\w+)$/, '$1');
        }
    }
    for (var i = 0; i < imgs.length; i++) {
        var imageName = undefined;
        for (var j = 0; j < imageNames.length; j++) {
            if (imgs[i].src.indexOf(imageNames[j][0]) != -1) {
                imageName = imageNames[j];
                break;
            }
        }
        if (imageName) {
            var search = imageName[enabled ? 1 : 0] + button._exts[i];
            var replace = imageName[enabled ? 0 : 1] + button._exts[i];
            imgs[i].src = imgs[i].src.replace(search, replace);
        } else {
            var parentNode = $(imgs[i].parentNode);
            if (initial) {
                imgs[i].parentNode.style.display = enabled ? 'block' : 'none';
            } else {
                if (enabled) {
                    parentNode.fadeIn("fast");
                } else {
                    parentNode.fadeOut("fast");
                }
            }
        }
        if (imgs[i].style.display == 'none' && imgs[i].nextSibling.style.filter) {
            imgs[i].nextSibling.style.filter = imgs[i].nextSibling.style.filter.replace(search, replace);
        }
    }
}
function buttonNextCallback(parent, button, enabled) {
    var imageNames = [
        ['btn-stories-fx', 'btn-stories-fx-ac']
    ];
    buttonCallback(parent, button, enabled, imageNames);
    var nextElem = undefined;
    var i = 0;
    nextElem = button;
    while ((nextElem = nextElem.nextSibling) !== null && nextElem.nodeType != 1);
    if (nextElem) {
        nextElem.style.display = enabled ? 'none' : 'block';
    }
}
function buttonPrevCallback(parent, button, enabled) {
    var imageNames = [
        ['btn-stories-sh', 'btn-stories-sh-ac']
    ];
    buttonCallback(parent, button, enabled, imageNames);
}
