
var isTouch;
var eventLock = false;

const touchStartPos = {};

const g = {};

g['degubMode'] = true;




//g['scrollMode'] = 'scroll';//通常スクロール
//g['scrollMode'] = 'static';//scroll+SPのアドレスバー表示固定
if(isPC){
    g['scrollMode'] = 'easing'
}else{
    g['scrollMode'] = 'scroll'
}
//g['scrollMode'] = 'easing';//イージングスクロール
//g['scrollMode'] = 'onepage';//ワンページスクロール

g['obj_sitebody'] = '#scrollBody';
g['obj_sitebody_dummy'] = '#scrollBodyDummy';
g['obj_sitebody_container'] = '#container';

g['obj_sitemain'] = '#siteMain';
g['obj_sitemain_target'] = 'section.page';

g['obj_sitenav'] = '#siteNav';
g['obj_sitebg'] = '#siteBG';


g['winWidth'];
g['winHeight'];

g['container_height'];

g['stagePos'] = {};
g['stagePos'].top = 0;
g['stagePos'].now = 0;

g['direction'] = 'stop';

g['smoothScrollSpeed'] = 0.1;
g['smoothScroll'] = {};
g['smoothScroll'].y = 0;
g['Scroll'] = {};
g['Scroll'].y = 0;


g['sectionData'] = [];
g['sectionStatus'] = {max_count:null,now_number:null,now_label:null};


g['actionFlag'] = false;
g['actionFlag_Wait'] = 1000;//ms




//console
function c(data,mode){
    
    if(mode !== false){
       //console.log(data);
     }
    
}

//GAイベント
function Fn_gaEvent(params_1, params_2, params_3) {
  if (debugGA) {
    console.log(' ga send = event , params:[ ' + params_1 + ' , ' + params_2 + ' , ' + params_3 + ']');
  }
  gtag('event', params_2, {
    'event_category': params_1,
    'event_label': params_3
  });
}


//サイトアクティブ時（イントロ、初期表示など）
function Fn_siteActive(){
    //c('Fn_siteActive');
   
    Fn_bodyInit();
    Fn_statusUpdate();
    
     if(g['scrollMode'] == 'onepage'){
        const first_contents = 0;
        $(g['obj_sitemain']).find(g['obj_sitemain_target']).eq(first_contents).addClass('in');
        $(g['obj_sitemain']).find(g['obj_sitemain_target']+':not(:eq('+first_contents+'))').addClass('stby');

        $(g['obj_sitebg']).find('ul li').eq(first_contents).addClass('in');
        $(g['obj_sitebg']).find('ul li:not(:eq('+first_contents+'))').addClass('stby');
     }
    
    
    Fn_statusUpdate();
    
    
    g['actionFlag'] = true;
}

//ページ内スクロール
function Fn_pageScroll(target, scroll_speed, offset) {

  //var target_pos = target.position();
  var target_pos_fix = target.offset().top;
  if (!scroll_speed) {
    var speed = 500;
  } else {
    var speed = scroll_speed;
  }
  target_pos_fix = target_pos_fix + Number(offset);

  //$("#pageScroll").css({ 'transform': 'translate3d(0px, -'+target_pos_fix+'px, 0px)'});
  $(g['obj_sitebody']).animate({
    scrollTop: target_pos_fix
  }, speed, 'easeInOutExpo', function () {

  });
}



function Fn_globalInit() {
    c('Fn_globalInit',false);
    g['winWidth'] = window.innerWidth;
    g['winHeight'] = window.innerHeight;
    
    if(g['scrollMode'] == 'easing'){
        
        $('html,body').addClass('scrollMode_easing');
    }else if(g['scrollMode'] == 'onepage'){
        $('html,body').addClass('scrollMode_onepage');
    }else if(g['scrollMode'] == 'static'){
        $('html,body').addClass('scrollMode_static');
        $(g['obj_sitebody_dummy']).remove();
    }else{
        $(g['obj_sitebody_dummy']).remove();
    }
    
    
    if(g['scrollMode'] == 'onepage'){
        var html ='';
        $(g['obj_sitemain']+' '+g['obj_sitemain_target']+'.page').each(function (index, element) {
            var label = $(this).attr('id');
            html += '<li class="'+label+'" data-page="'+index+'"><span>'+label+'</span></li>';
        });
        $(g['obj_sitenav']).append('<div class="sectionNavWrap"><ul>'+html+'</ul></div>');
        
        $(g['obj_sitebg']).append('<ul>'+html+'</ul>');

        $(g['obj_sitenav'] + ' ul li').on('click',function(){
                const index = $(this).attr('data-page');
                Fn_pageChange(index,'direct');
        });
    }
}
function Fn_bodyInit() {
    //c('Fn_bodyInit');
    g['container_height'] = $(g['obj_sitebody_container']).outerHeight() ;

    $(g['obj_sitemain']+' '+g['obj_sitemain_target']+'.page').each(function (index, element) {
        const id = $(this).attr('id');
        g['sectionData'].push(id);
    });

    if(g['scrollMode'] == 'easing'){$(g['obj_sitebody_dummy']).height(g['container_height']);}
}

function Fn_scrollUpdate(mode) {
      c('Fn_scrollUpdate',false);
    
    if(mode == 'scroll' || mode == 'easing'){
        g['stagePos'].top = $(window).scrollTop();
    }else{
        g['stagePos'].top = $('#scrollBody').scrollTop();
    }
      

      if (g['stagePos'].now == g['stagePos'].top) {
        g['direction'] = 'stop';
      } else if (g['stagePos'].now < g['stagePos'].top) {
        g['direction'] = 'down';
      } else {
        g['direction'] = 'up';
      }
    
      //if (g['stagePos'].now != g['stagePos'].top) {$('body').addClass('scrollMove');}else{$('body').removeClass('scrollMove');}
    

      //c('now_direction='+ g['direction']+' stagePos.top='+ g['stagePos'].top);

      g['stagePos'].now = g['stagePos'].top;
      g['Scroll'].y += (g['stagePos'].top - g['Scroll'].y);

    if(mode == 'easing'){
        
        if(!bodyLockFlag){
            g['smoothScroll'].y += (g['stagePos'].top - g['smoothScroll'].y) * g['smoothScrollSpeed'];
            $(g['obj_sitebody_container']).css({
              transform: 'translate3d(0,' + (-g['smoothScroll'].y) + 'px,0)'
            });
        }
        
        
        
        var container_h = $('#container').outerHeight();
        
        $('body').css({height:container_h});
        
    }
    
    if(mode == 'scroll' || mode == 'static' || mode == 'easing'){
        
        $(g['obj_sitemain']+' '+g['obj_sitemain_target']+'.page').each(function (index, element) {
            
                const elemOffset = $(this).position().top;
                const elem_area = $(this).outerHeight();
                const wh = $(window).height();
            
                
                c(elemOffset);
                const active_point = elemOffset - wh + (wh / 2);
                const deactive_point = elemOffset - wh + (wh / 2) + elem_area;
                if(g['stagePos'].top > active_point && g['stagePos'].top < deactive_point){
                  $(this).addClass('active');
                }else{
                  $(this).removeClass('active');
                }
        });

    }
    
    
    
    
    
}//Fn_scrollUpdate


function Fn_pageChange(target,mode) {
        if(target >=0 && target < g['sectionStatus'].max_count && !g['actionFlag']){
            g['actionFlag'] = true;

            //範囲内
            const target_section = $(g['obj_sitemain']+' '+g['obj_sitemain_target']);
            const target_bg = $(g['obj_sitebg'] + ' ul li');

            if(mode == 'back'){
                target_section.eq(g['sectionStatus'].curPage).removeClass('in out').addClass('stby');
                target_bg.eq(g['sectionStatus'].curPage).removeClass('in out').addClass('stby');
            }
            if(mode == 'next'){
                target_section.eq(g['sectionStatus'].curPage).removeClass('in stby').addClass('out');
                target_bg.eq(g['sectionStatus'].curPage).removeClass('in stby').addClass('out');
            }
            if(mode == 'direct'){
                $(g['obj_sitemain']).find(g['obj_sitemain_target']+':not(:eq('+target+'))').removeClass('in stby').addClass('out');
                $(g['obj_sitebg']).find('ul li:not(:eq('+target+'))').removeClass('in stby').addClass('out');
                
                target_section.eq(target).nextAll().removeClass('out').addClass('stby');
                target_bg.eq(target).nextAll().removeClass('out').addClass('stby');
            }

            target_section.eq(target).removeClass('out stby').addClass('in');
            target_bg.eq(target).removeClass('out stby').addClass('in');

            g['sectionStatus'].curPage = target;
            Fn_statusUpdate();
        
            setTimeout(function(){
                g['actionFlag'] = false;
            },g['actionFlag_Wait']);
        }
}

function Fn_scrollInit(){
        const MOUSE_WHEEL_EVENT = 'onwheel' in document ? 'onwheel' : 'onmousewheel' in document ? 'onmousewheel' : 'DOMMouseScroll';
        window[MOUSE_WHEEL_EVENT] = function(event){
        const dlt = event.deltaY ? event.deltaY:event.wheelDelta;

         if(!dlt) return;
            if(Math.abs(dlt)>10){
              if(dlt>0){
                Fn_pageChange(g['sectionStatus'].curPage + 1,'next');
              }else{
                Fn_pageChange(g['sectionStatus'].curPage - 1,'back');
              }
            }
        }
}

function Fn_swipeInit(){
    $('.contents').on('touchstart', function(event) {
      //event.preventDefault();
      touchStartPos.x = event.changedTouches[0].pageX;
      touchStartPos.y = event.changedTouches[0].pageY;
      isTouch = true;
    });
    $('.contents').on('touchend', function(event) {
      if(isTouch){
        const dlt = touchStartPos.y - event.changedTouches[0].pageY;
        if(Math.abs(dlt)>50){
          if(dlt>0){
            Fn_pageChange(g['sectionStatus'].curPage + 1,'next');
          }else{
            Fn_pageChange(g['sectionStatus'].curPage - 1,'back');
          }
        }
        isTouch = false;
      }
    });
}



function Fn_statusUpdate(){
    c('Fn_statusUpdate',false);
    g['sectionStatus'].max_count = $(g['obj_sitemain']+' '+g['obj_sitemain_target']).length;
    g['sectionStatus'].curPage = $(g['obj_sitemain']+' '+g['obj_sitemain_target']+'.in').index();
    g['sectionStatus'].curPage_label = $(g['obj_sitemain']+' '+g['obj_sitemain_target']+'.in').attr('id');
    
    if($(g['obj_sitenav'] + ' ul li').length){
        $(g['obj_sitenav'] + ' ul li').removeClass('active');
        $(g['obj_sitenav'] + ' ul li.'+g['sectionStatus'].curPage_label).addClass('active');  
    }
    //c(g['sectionStatus']);     
}



function Fn_loop() {
//c('Fn_loop');
      if(g['scrollMode'] == 'easing'){
        Fn_scrollUpdate('easing');
      }
      if(g['scrollMode'] == 'scroll'){
        Fn_scrollUpdate('scroll');
      }
      if(g['scrollMode'] == 'static'){
        Fn_scrollUpdate('static');
      }
      if(g['degubMode']){
          var html = '';
          if(g['scrollMode'] == 'onepage'){
                html += 'curPage = ' + g['sectionStatus'].curPage + '<br>';
                html += 'curPage_label = ' + g['sectionStatus'].curPage_label + '<br>';
          }else{
                html += 'Scroll = ' + g['Scroll'].y + '<br>';
                 if(g['scrollMode'] == 'easing'){
                        html += 'smoothScroll = ' + Math.round(g['smoothScroll'].y) + '<br>';
                 }
          }
              
           
     
          
          $('#debugWrap .contents').html(html);
      }
      window.requestAnimationFrame(Fn_loop);
}


function Fn_artistChange(obj,mode){
    console.log('modalmode='+mode);
    var modalActionWait = 1;
    if(mode == 'prev' || mode == 'next'){
        modalActionWait = 500;
        
       $('body').addClass('modalChange modalLock');
        
       setTimeout(function(){
           $('body').removeClass('modalChange');
       },modalActionWait+500);
        
    
        setTimeout(function(){
           $('body').removeClass('modalLock');
       },modalActionWait+1000);
        
    }
    
    setTimeout(function(){
          $('#artistMoadl .modalContents .image').empty();
                setTimeout(function(){
    
                        $('#artistMoadl .deactive').removeClass('deactive');

                        obj.addClass('active');

                        if(!obj.next().length){
                           $('#artistMoadl .nextBtn').hide();
                         }else{
                            $('#artistMoadl .nextBtn').show();
                         }

                        if(!obj.prev().length){
                           $('#artistMoadl .prevBtn').hide();
                         }else{
                            $('#artistMoadl .prevBtn').show();
                         }
                        $('#artistMoadl').show();
                        $('body').addClass('modalOpen');

                        var image = obj.attr('data-image');
                        var name = obj.attr('data-name');
                        var officialweb = obj.attr('data-officialweb');
                        var twitter = obj.attr('data-twitter');
                        var facebook = obj.attr('data-facebook');
                        var instagram = obj.attr('data-instagram');
                        var youtube = obj.attr('data-youtube');
                        var spotify = obj.attr('data-spotify');

                        var contents = obj.attr('data-contents');




                        $('#artistMoadl .modalContents .image').html('<img src="'+image+'">');

                        $('#artistMoadl .modalContents .name').html(name);

                        $('#artistMoadl .modalContents .moreArea a').attr('href',officialweb);
                        if(!officialweb){$('#artistMoadl .modalContents .moreArea').addClass('deactive');}

                        $('#artistMoadl .modalContents .links ul .twitter a').attr('href',twitter);
                        if(!twitter){$('#artistMoadl .modalContents .links ul .twitter').addClass('deactive');}

                        $('#artistMoadl .modalContents .links ul .facebook a').attr('href',facebook);
                       if(!facebook){$('#artistMoadl .modalContents .links ul .facebook').addClass('deactive');}

                        $('#artistMoadl .modalContents .links ul .instagram a').attr('href',instagram);
                        if(!instagram){$('#artistMoadl .modalContents .links ul .instagram').addClass('deactive');}

                        $('#artistMoadl .modalContents .links ul .youtube a').attr('href',youtube);
                        if(!youtube){$('#artistMoadl .modalContents .links ul .youtube').addClass('deactive');}

                        $('#artistMoadl .modalContents .links ul .spotify a').attr('href',spotify);
                        if(!spotify){$('#artistMoadl .modalContents .links ul .spotify').addClass('deactive');}

                        $('#artistMoadl .modalContents .text').html(contents);
                },200);
    
                  setTimeout(function(){
                       eventLock = false;
                   },1000);
    },modalActionWait);
    
}



function Fn_scrollActionUI(){




					var scrollPos = $(window).scrollTop();
					var wh = $(window).height();
					var delay_time = 1000;
				
					  
					  $('.inView').each(function(index, element){
						  	var elemOffset = $(this).offset().top;
						  	var view_delay_time = $(this).attr('data-viewdelay');
						  	if(chkTouch){
							  	view_delay_time = 0;
						  	}
						  	if(!view_delay_time){view_delay_time = 0;}
						  	
						    if(scrollPos > elemOffset - (wh*0.7)){
								setTimeout(function($_) {
											return function(){
												$_.addClass("in");
												}
								}($(this)), index*view_delay_time);
								
								
							} 					
					  }) //each
					  
					  
				
		}//Fn_scrollAction


$(function () {
    
    var url_path = location.pathname;
    
    if(location.hash){
        
         setTimeout(function(){
             console.log('load hashchange');
               var anchor = location.hash;
      
        var adjust = 0;
        var speed = 400;
        var target = $(anchor);
        var position = target.offset().top + adjust;
        $('body,html').animate({scrollTop:position}, speed, 'swing');

        
        
      
           history.pushState(null, null, url_path);
       },1000);
        
    }
    
  $(window).hashchange( function(event){
      
      
      console.log('hashchange');
        $('body').removeClass('menuOpen');
      bodyFixed('off');
      
      setTimeout(function(){
           
        
        var anchor = location.hash;
      
        var adjust = 0;
        var speed = 400;
        var target = $(anchor);
        var position = target.offset().top + adjust;
          console.log('position'+position);
        $('body,html').animate({scrollTop:position}, speed, 'easeInOutQuart');

           history.pushState(null, null, url_path);
       },200);
      
       
  })
    
    
    if(g['degubMode']){
        const html = '<div id="debugWrap"><div class="contents"></div></div>'; 
        $('body').append(html);
    }
    Fn_globalInit();
    
    if(g['scrollMode'] == 'onepage'){
       Fn_scrollInit();
        Fn_swipeInit();
        
        
        $('html').keyup(function(e){
            var target = g['sectionStatus'].curPage;
            switch(e.which){
                case 39: // Key[→]
                var target_fix = target + 1;
                break;

                case 37: // Key[←]
                var target_fix = target - 1;
                break;

                case 38: // Key[↑]
                var target_fix = target - 1;
                break;

                case 40: // Key[↓]
               var target_fix = target + 1;
                break;
            }
            Fn_pageChange(target_fix,'direct');
            
        });

    }
    

    $(window).on('load resize', function () {
        Fn_bodyInit();
        Fn_statusUpdate();
    });

    $(window).on('scroll', function () {

    });
    
    
    $('.artistsEntry').on('click', function () {
        
        Fn_artistChange($(this));

            bodyFixed('on');
        
    });
    
    $('#artistMoadl .prevBtn').on('click', function () {
        if(!eventLock){
            eventLock = true;
            console.log('prevBtn');
            var target = $('.artistsEntry.active').prev();

            $('.artistsEntry').removeClass('active');
            Fn_artistChange(target,'prev');
        }
     });
     $('#artistMoadl .nextBtn').on('click', function () {
         
         if(!eventLock){
            eventLock = true;
              console.log('nextBtn');
            var target = $('.artistsEntry.active').next();
             $('.artistsEntry').removeClass('active');
            Fn_artistChange(target,'next');
        }
         
        
        
     });
    
    $('#artistMoadl .closeBtn').on('click', function () {

        bodyFixed('off');
        $('.artistsEntry').removeClass('active');
        $('body').addClass('modalClose');
        
         setTimeout(function(){
             $('body').removeClass('modalOpen modalClose');
             setTimeout(function(){
                $('#artistMoadl .deactive').removeClass('deactive');
              },500);
           
        },500);
 
     });
    
    $('#fixNavi').on('click', function () {
       
        if($('body').hasClass('menuOpen')){
           $('body').removeClass('menuOpen');
            bodyFixed('off');
           }else{
           $('body').addClass('menuOpen')
               bodyFixed('on');
           }
        
        
        
     });
    
    $('#globalHeader .anchor , .anchor.btnlink').on('click', function (event) {

        var adjust = 0;
        var speed = 400;
        var target = $(this).attr('data-href');
        var position = $(target).offset().top + adjust;
          console.log('position'+position);
        $('body,html').animate({scrollTop:position}, speed, 'easeInOutQuart');
     });
        
        
});



			(function loop(){
			    window.requestAnimationFrame(loop);
			    
		
			    
                    if(g['actionFlag']){
                       Fn_scrollActionUI();
                     }
  
					   		

			})();
