var filepath = "/dir/js/";

(function($){$(document).ready(function(){
$.getScript(filepath +"namespace.js",function(){
                             
var NS = window.getNameSpace();

// gnv popupnav ////////////////////////////////////////////

showPopupNav("toNews");
showPopupNav("toTheatre");
showPopupNav("toAbout");

function showPopupNav(className){
  var gnv = $("#globalNav");
  var target = gnv.find("dt."+ className);
  var popup = gnv.find("dd."+ className);

  target
  .mouseover(function(e){popup.css("visibility","visible");})
  .mouseout(function(e){popup.css("visibility","hidden");});
  
  popup
  .mouseover(function(e){popup.css("visibility","visible");})
  .mouseout(function(e){popup.css("visibility","hidden");});
}

// fnv popupnav ////////////////////////////////////////////

showPopupFNav("#fnv .toInternational","#internationallink");

function showPopupFNav(target,popup){
  var active = "active" ;
  target     = $(target);
  target_a   = target.find("a");
  popup      = $(popup);
      
  target
  .mouseover(mover)
  .mouseout(mout);
  
  popup
  .mouseover(mover)
  .mouseout(mout);
  
  function mover(){
    popup.css("display","block");
    target_a.addClass(active);
  }
  function mout(){
    popup.css("display","none");
    target_a.removeClass(active);
  }
}

// topIndex ////////////////////////////////////////////
   (function(){
    if(!($("#topIndex")[0])) return ;
        
    createBalloon($("#socialNav .toYoutube"),"dir/images/201106/balloon_youtube.png","公式ブルーマンチャンネル");
    createBalloon($("#socialNav .toTwitter"),"dir/images/201106/balloon_twitter_bm.png","Twiterでブルーマンがつぶやく!?");
    createBalloon($("#socialNav .toFacebook"),"dir/images/201106/balloon_facebook.png","ブルーマンの情報を共有しよう！");
    createBalloon($("#qr"),"dir/images/201106/balloon_mobile.png","ブルーマンケータイサイトはこちら");

      function createBalloon(elm,imgpath,txt){
      var img = $("<img>").attr({src : imgpath , alt : txt}).css("position","absolute").hide().appendTo("body");
      
      elm
      .mouseover(function(){
        img
        .css({
          left : elm.offset().left - img.width()*0.5 + elm.width()*0.5 ,
          top  : elm.offset().top - img.height() -2 ,
          zIndex : 10
        })
        .fadeIn(300);
      })
      .mouseout(function(){
        img.fadeOut(300);          
      });
      }
    
    $.getScript(filepath +"slideshow.js",function(){
      var mainrotation = new NS.Slideshow({
        target     : "#mainRotationBnr",
        width      : 695 ,
        height     : 405 ,
        interval   : 6000 ,
        effecttime : 600 ,
        autoPlay   : true ,
        enable     : {
          nav          : true ,
          touchControl : true
        }
      });
      $("#mainRotationBnr .wrap").find("a").hover(
        function(){
          $(this).parent().css("background","#fff");
          $(this).fadeTo(200,0.9)  ;
        },
        function(){
          var _this = $(this);
          _this.fadeTo(200,1.0,function(){
            _this.parent().css("background","transparent");
          })  ;
        }
      );


      var recommend = new NS.Slideshow({
        target     : "#recommendBnr",
        width      : 195 ,
        height     : 140 ,
        interval   : 5000 ,
        effecttime : 400 ,
        autoPlay   : false ,
        enable     : {
          touchControl : true
        }
      });
      recommend.play = function(){
        var _this = this ;
  
        if(_this.items.length < 2) return ;
        
        if(_this.isPlaying) return ;
        _this.isPlaying = true ;
        _this.timestamp = parseInt((new Date()).getTime());
        if(_this.progress)_this.progressReset();
        
        if(_this.progress){
          _this.progressReset();
          _this.progressON();
        }
        
        _this.intervalId = setInterval(function(){        
          var next = _this.getNext();
          _this.change(next,_this.CLASS.ANIMGO);
        },_this.interval);
      };
      recommend.change = function(next,direction){
        var _this = this ;
              
        if(_this.items.length < 2) return ;
        
        _this.isChanging = true ;
        
        _this.wrap.css("overflow","hidden");
        
        var currentitem = $(_this.items[_this.current]) ;
        var nextitem    = $(_this.items[next]).show() ;
        
        if(_this.nav){
          _this.navbtns[_this.current].removeClass(_this.CLASS.CURRENT);
          _this.navbtns[next].addClass(_this.CLASS.CURRENT);
        }
        
        if(_this.environment.browser != "Webkit"){
          if(direction){
            currentitem.addClass(direction);
            nextitem.addClass(direction);
          }
          
          var data ;
          if(direction == _this.CLASS.ANIMGO){
            nextitem.css("left",195);
            data = {
              marginLeft : "-=195px"
            };
          }
          if(direction == _this.CLASS.ANIMBACK){
            nextitem.css("left",-195);
            data = {
              marginLeft : "+=195px"
            };
          }
          
          currentitem.animate(
            data,
            {
              duration : _this.effecttime
            }
          );
          nextitem.addClass(_this.CLASS.NEXT).animate(
            data,
            {
              duration : _this.effecttime ,
              complete : function(){
                currentitem.removeClass(_this.CLASS.CURRENT).removeClass(direction).hide().css("margin","auto");
                $(this).removeClass(_this.CLASS.NEXT).removeClass(direction).addClass(_this.CLASS.CURRENT).css("margin","auto").css("left","");
                _this.current = next ;
      
                _this.isChanging = false ;
                _this.elm.trigger(_this.EVENT.CHANGE);
                _this.timestamp = parseInt((new Date()).getTime());
                if(_this.progress)_this.progressReset();
              }
            }
          );
        }
        else {
          if(direction){
            if(_this.getEnvironment().os == "iOS") _this.setWrapStateSwipe();
            currentitem.addClass(direction);
            nextitem.addClass(direction);
          }
          currentitem.addClass(_this.CLASS.ANIMATION +" "+ _this.CLASS.ANIMOUT).bind(_this.EVENT.ANIMATIONEND,animOutEndCSS3);
          nextitem.addClass(_this.CLASS.ANIMATION +" "+ _this.CLASS.ANIMIN).bind(_this.EVENT.ANIMATIONEND,animInEndCSS3);
        }
        
        function animOutEndCSS3(){
          $(this)
            .removeClass(_this.CLASS.ANIMATION)
            .removeClass(_this.CLASS.ANIMOUT)
            .removeClass(_this.CLASS.CURRENT)
            .removeClass(direction ? direction : "")
            .unbind(_this.EVENT.ANIMATIONEND,animOutEndCSS3);
        }
        
        function animInEndCSS3(){
          $(this)
            .removeClass(_this.CLASS.ANIMATION)
            .removeClass(_this.CLASS.ANIMIN)
            .removeClass(direction ? direction : "")
            .addClass(_this.CLASS.CURRENT)
            .unbind(_this.EVENT.ANIMATIONEND,animInEndCSS3);        
          _this.current = next ;
  
          _this.isChanging = false ;
          _this.elm.trigger(_this.EVENT.CHANGE);
          _this.timestamp = parseInt((new Date()).getTime());
          if(_this.progress)_this.progressReset();
          if(direction) _this.removeWrapStateSwipe();
        }
      };
      recommend.createLateralNav = function(){
        var _this = this ;

        if(_this.items.length < 2) return ;
        
        var lateralnav = $("<ul>").addClass(_this.CLASS.LATERALNAV).insertAfter(_this.target);
        _this.navPrev = createLateralNavItem(_this.VALUE.PREVHREF);
        _this.navNext = createLateralNavItem(_this.VALUE.NEXTHREF);
        
        function createLateralNavItem(hrefval){
          var navitem = $("<a>").attr("href",hrefval).appendTo(lateralnav).wrap("<li class=\"Btn\">");
          
          if(hrefval == _this.VALUE.NEXTHREF){
            navitem.addClass(_this.CLASS.NAVNEXT).text(_this.VALUE.NEXTTXT).bind("click",function(e){
              var next = _this.getNext();
              if(!_this.isChanging && next != _this.current){
                _this.stop();
                _this.change(next,_this.CLASS.ANIMGO);
              }          
              e.preventDefault();
            });
          }
          if(hrefval == _this.VALUE.PREVHREF){
            navitem.addClass(_this.CLASS.NAVPREV).text(_this.VALUE.PREVTXT).bind("click",function(e){
              var prev = _this.getPrev();
              if(!_this.isChanging && prev != _this.current){
                _this.stop();
                _this.change(prev,_this.CLASS.ANIMBACK);
              }          
              e.preventDefault();
            });
          }
          
          return navitem ;
        }
      };
      recommend.autoPlay = true ;
      recommend.createLateralNav();
      recommend.play();
    });

    if(NS.methods.getCurrentEnvironments().os == "iOS") {
      $.getScript(filepath +"youtubeload_html5.js");
    }
    else {    
      $.getScript(filepath +"youtubeload.js",function(){
        var playerobj = NS.youtube.players[0] ;
      
        // 公式チャンネルリンク生成
        $("<a>").text("公式チャンネル").attr({href:"http://www.youtube.com/bluemanjapan",target:"_blank"}).appendTo(playerobj.overlay);
        
        // 音声ボタン
        var audio_off = "OFF" ;
        var audio_on  = "ON" ;
        var btnAudio_wrap = $("<p>").addClass("Btn btnAudio").insertAfter(playerobj.overlay);
        var btnAudio      = $("<a>").attr("href","#").text(audio_on).appendTo(btnAudio_wrap).bind("click",function(e){
          if(playerobj.player.isMuted()){
            btnAudio.text(audio_on).removeClass("Off");
            playerobj.player.unMute();
          }
          else {
            btnAudio.text(audio_off).addClass("Off");
            playerobj.player.mute();
          }          
          e.preventDefault();
        });

        // ループ再生
        $(window).bind("yt"+ playerobj.video_id +"Load",function(){
          window["topYTMovieStateChange"] = function(){
            // 未開始（-1）、終了（0）、再生中（1）、一時停止中（2）、バッファリング中（3）、頭出し済み（5）
            if(playerobj.player.getPlayerState() == 0){
              playerobj.player.seekTo(0,true);
              playerobj.player.playVideo();
            }
          };
          playerobj.player.addEventListener("onStateChange","topYTMovieStateChange");
        });
      });
    }
    
    $.getScript(filepath +"tweet.js",function(){
      $("#timeline").empty();

      var BMmanager = window.BMmanager = new NS.Tweets("#timeline");
      //BMmanager.setting.hideReplyLink = true ;
      BMmanager.setting.disableTweetPermaLink = true ;  
      BMmanager.setting.hideAccountRealName = true ;
      BMmanager.setting.hideClientName = true ;
      //BMmanager.setting.hideAccountImg = true ;
      BMmanager.getUserTimeline({
        userid : "BMmanager",
        maxlength : 50
      });
      BMmanager.setRotationItems(8000);
      
      /*
      var tweets = new NS.Tweets("#timeline");
      //tweets.setting.hideReplyLink = true ;
      tweets.setting.hideFavLink = true ;
      tweets.setting.disableTweetPermaLink = true ;  
      tweets.setting.hideAccountRealName = true ;
      tweets.setting.hideClientName = true ;
      //tweets.setting.hideAccountImg = true ;
      tweets.searchKeywordFromCacheScript({
        url      : "http://blueman.jp/dir/php/twitter/search.php" ,
        funcname : "res"  
      });
      tweets.setRotationItems(8000);
      */
    });
    
   })();
   
// UpdateTxt ////////////////////////////////////////////

   (function(){
      return ;
      //if(!(($("#ticketIndex")[0] || $("#theatreIndex")[0]) || $("#scheduleIndex")[0])) return ;
      
      var url = "/mt5_web/blueman/dir/data/index.html";
      var insertTo = $("#pageTitle");
      
      $.ajax({
         async  : true ,
         type: "GET",
         url: url,
         cache : false ,
         dataType : "text" ,
         success: function(data){

            var dl = $("<dl>").attr("id","update").insertAfter(insertTo).hide();
            var updates = data.split("\n");
            
            $.each(updates, function(){
               var update = this.split(",");
               if(update[0].replace(/\s*/,"") == "") return ;
               
               if(update[1] != null){
                  var target = (!update[2])?"":"target=\"" + update[2] + "\"";
                  $("<dt><a href=" + update[1] + " "+ target +">" + update[0] + "</a></dt>").appendTo(dl);
               }
               else $("<dt>").text(update[0]).appendTo(dl);
            });
            
            setTimeout(function(){dl.fadeIn(400);},100);
         }
      });
      
   })();


// Pager If Empty ////////////////////////////////////////////
   (function(){
      if(!$("#pager")[0]) return ;
      if($("#pager dd").first().text() == "") $("#pager").remove();
   })();

// viewpointPage Settings ////////////////////////////////////////////
   (function(){
      if($("body").attr("class") != "viewpointPage") return ;
      $(".section p img").parent("p").css("padding","0");
      $(".section").last().addClass("lastChild");
   })();

// newsPage Settings ////////////////////////////////////////////
   (function(){
      if($("body").attr("class") != "newsPage") return ;
      $(".section").last().addClass("lastChild");
      $(".section object + a[href=http://www.ustream.tv/]").hide();
   })();

// ticketPage Settings ////////////////////////////////////////////
   (function(){
      if($("body").attr("class") != "ticketPage") return ;
      var klass = "JsActive" ;
      var hash = window.location.hash ;

      $(".tabContents").hide();
      if(hash.match(/^#f.+/) != null){
         $(hash).show();
         $("#toFor"+ hash.substring(4)).addClass(klass);
         if(hash == "#forToday") setTimeout(function(){window.scroll(0,300);},300);
         else window.scroll(0,0);   
      }
      else {
         $("#forWeb").show();
         $("#toForWeb").addClass(klass);         
      }

      $("#playGuideTab li a , #playGuide .tabContents a , #globalNav .popup a").click(function(e){

         var target_id = $(this)[0].hash;
         if(target_id.match(/^#/) == null) return ;

         $(".tabContents").hide();
         $(target_id).show();
         $("#playGuideTab li").removeClass(klass)
         $("#toFor"+ target_id.substring(4)).addClass(klass);   
         //$(this).parent().addClass(klass);

         e.preventDefault();
         e.stopPropagation();
         if(target_id == "#forToday") window.scroll(0,300);
      });

      /* 2011.02.23 add
      (function(){
        var famima = $("#famima .shoplogo");
        if(!famima[0]) return ;

        // mekakushi
        $("<div>").css({
          position : "absolute" ,
          top : -2 ,
          left : 301 ,
          width : 138 ,
          height : 2 ,
          background : "#000"
        }).prependTo("#forShop");

        $("#forShop").css("zIndex", 1000);
        famima.css("position","relative");
        famima_logo = famima.find("[alt=ファミリーマート]");
        famima_linktxt  = $("#famima p a");

        var popup = $("<img>")
          .attr({
            src : "images/popup_machiuke.gif",
            alt : "今なら＜携帯電話Flash待受時計＞がもらえる！"
          })
          .css({
            position : "absolute",
            top      : -55 ,
            left     : 5 ,
            opacity  : 0
          })
          .appendTo(famima);

        famima_logo
          .bind("mouseover",function(e){
            popup.animate({
              opacity : 1.0 ,
              top     : -70
            }, 300 );
          })
          .bind("mouseout",function(e){
            popup.animate({
              opacity : 0 ,
              top     : -55
            }, 300 );
          });

        famima_linktxt
          .bind("mouseover",function(e){
            famima_logo.trigger("mouseover");
          })
          .bind("mouseout",function(e){
            famima_logo.trigger("mouseout");
          });
      })();
      2011.02.23 add */

    /* 2011.03.08 add
    (function(){
      var thanks = $("#thanks .shoplogo");
      if(!thanks[0]) return ;
      
      // mekakushi
      $("<div>").css({
        position : "absolute" ,
        top : -2 ,
        left : 301 ,
        width : 138 ,
        height : 2 ,
        background : "#000"
      }).prependTo("#forShop");
      
      $("#forShop").css("zIndex", 1000);
      thanks.css("position","relative");
      thanks_logo = thanks.find("[alt=サークルK・サンクス]");
      thanks_linktxt  = $("#thanks p a");
                  
      var popup = $("<img>")
        .attr({
          src : "images/popup_goods.gif",
          alt : "ブルーマンオリジナルグッズもれなくもらえる！"
        })
        .css({
          position : "absolute",
          top      : -55 ,
          left     : 5 ,
          opacity  : 0
        })
        .appendTo(thanks);
      
      thanks_logo
        .bind("mouseover",function(e){
          popup.animate({
            opacity : 1.0 ,
            top     : -70
          }, 300 );
        })
        .bind("mouseout",function(e){
          popup.animate({
            opacity : 0 ,
            top     : -55
          }, 300 );
        });
      
      thanks_linktxt
        .bind("mouseover",function(e){
          thanks_logo.trigger("mouseover");
        })
        .bind("mouseout",function(e){
          thanks_logo.trigger("mouseout");
        });
    })();
    2011.03.08 add */


      /* 2010.08.04 --------------- */
      (function(){
        var date_0806_1000 = new Date(2010,7,6,10,0);
        var date_0807_1000 = new Date(2010,7,7,10,0);
        var now = (new Date()).getTime();

        //timer
        //if(now < date_0806_1000.getTime()) return ;
        //if(date_0807_1000.getTime() < now) return ;

        $("#baloon0806").show();
      })();
      /* 2010.08.04 --------------- */

   })();

// theatre gourmetIndex ////////////////////////////////////////////
  (function(){
    if(!$("#gourmetIndex")[0]) return ;
    if(!$("#googleMaps")[0]) return ;

    $.getScript(filepath +"googlemaps.js",function(){
    
    var path = "../../../dir/theatre/gourmet/images/";
    var map = NS.map = new NS.GoogleMaps("#googleMaps",[35.65910072430367,139.7331976890564],16);
    
    map.addCustomMarker({
      coordinates : [35.65910072430367,139.7331976890564],
      image : path + "marker_theatre.png",
      size : [67,57],
      anchor : [25,57]
    });
    
    $.each($("#shops .item"),function(i,val){
      var num = $(this).attr("id").match(/\d+/);
      var name = $(this).find("h2").text();
      var address = $(this).find("address");
      var coordinates = [address.attr("title").split("+")[1],address.attr("title").split("+")[2]];

      // if(i == 0) $("<span>").css("color","#E51785").text("[NEW]").appendTo($(this).find("h2"));
            
      map.addCustomMarker({
        coordinates : coordinates,
        image : path + "marker" + num +".png",
        size : [32,35],
        anchor : [13,35],
        text : "<div style='padding : 20px;'>"+ name +"</div>"
      });

      $(this).find("img").click(function(){
        if($.browser.safari) $("body").animate({scrollTop:0},500);
        else $("html").animate({scrollTop:0},500);

        map.markers[num].Xk.style.zIndex = map.zindex_count ;
        map.zindex_count++;
        map.markers[num].openInfoWindowHtml("<div style='padding : 20px;'>"+ name +"</div>");     
      }).css("cursor","pointer");

    });

    });
  })();
// twitterIndex ////////////////////////////////////////////
  (function(){
    if(!$("#twitterIndex")[0]) return ;
    if(!$("#loadTweets")[0]) return ;

    $.getScript(filepath +"tweet.js",function(){
      $("#loadTweets").empty();
      var tweets = window.tweets = new NS.Tweets("#loadTweets");
      //tweets.setting.hideReplyLink = true ;
      tweets.setting.disableTweetPermaLink = true ;  
      tweets.setting.hideAccountRealName = true ;
      tweets.setting.hideClientName = true ;
      //tweets.setting.hideAccountImg = true ;
      tweets.searchKeywordFromCacheScript({
        url      : "http://blueman.jp/dir/php/twitter/search.php" ,
        funcname : "res"  
      });
    });

  })();
// shopItem ////////////////////////////////////////////
  (function(){
    if(!$("#shopItem")[0]) return ;
   
    (function(){
      var itemphotos = $("#itemPhotos");
      var current    = "current";
    
      if(!itemphotos[0]) return ;
    
      var photos = itemphotos.find(".photo").find("li");
      var thumbs = itemphotos.find(".inner").find("a");
    
      photos.hide().eq(0).show().addClass(current);
      thumbs.fadeTo(100,0.7).eq(0).fadeTo(300,1.0).addClass(current);
    
      thumbs.bind("click",function(e){
        var _this = $(this);
      
        photos.filter("."+ current).removeClass(current).fadeOut(300);
        photos.eq(_this.parent().index()).fadeIn(300).addClass(current);
      
        thumbs.filter("."+ current).removeClass(current).fadeTo(100,0.7);
        _this.fadeTo(300,1.0).addClass(current);

        e.preventDefault();
      });
   
    })();

    (function(){
      var sendOK = true ;
      var selects = $("select");

      $.each(selects,function(i,val){
        var _this = $(this);
        var alert_txt = $("<p>").addClass("alert").text("！選択されていません").hide().appendTo(_this.parent());
    
        _this.bind("blur",function(){
          if(_this.val() == ""){
            alert_txt.hide().fadeIn(300);
            sendOK = false ;
          }
          else alert_txt.fadeOut(200);
        });
      });
   
      $("form").bind("submit",function(){
        sendOK = true ;
        selects.trigger("blur");
        if(!sendOK) return false ;
      });
    })();

  })();
  
// popupKosodate ////////////////////////////////////////////
  (function(){
    if(!$("#popupKosodate")[0]) return ;
    $.getScript(filepath +"slideshow.js",function(){
      var slideshow = NS.slideshow = new NS.Slideshow({
        target     : "#Slideshow",
        width      : 370 ,
        height     : 259 ,
        interval   : 3000 ,
        effecttime : 600 ,
        autoPlay   : true ,
        enable     : {
          nav        : true
        }
      });
   });
  })();  

//popupDLBMGClock
   (function(){
      if(!$("#popupDLBMGClock")[0]) return ;
      NS.methods.initViewPort(650);
   })();

// Popup & Lightbox ////////////////////////////////////////////
   (function(){
      if(!$.browser.safari) return ;
      if(!navigator.userAgent.match(/Version\/3.\d.\d/)) return ;
      $("a[rel^=superbox[image]] > span").text("Picture Expand");
   })();

   (function(){
      NS.popups = {};
      if((document.body.id).match(/^popup/)) return ;

      $.superbox.settings = {
         overlayOpacity: .7,
         loadTxt: "Loading...",
         closeTxt: "Close"
      };
      $.superbox();

      $("a[rel^=popup]").click(function(e){
         
         var sizes = ($(this).attr("rel")).replace("popup=","").split("+");
         
         if(!NS.popups[sizes[2]] || NS.popups[sizes[2]].closed) NS.popups[sizes[2]] = window.open($(this).attr("href"),"","width=" + sizes[0] +",height=" + sizes[1] +",resizable=yes,toolbar=0,scrollbars=yes");
         if(window.focus){
            NS.popups[sizes[2]].focus();
            NS.popups[sizes[2]].location = $(this).attr("href") ;
         }               
      
         e.preventDefault();
         e.stopPropagation();
      });
   })();

});
});})(jQuery);
