$(document).ready(function(){

var NS = (function createNS(){
   var host = window.location.host;
   var ns_name = (host != "")?(host.replace(/\./g,"_")).toUpperCase():"NAMESPACE";
   return window[ns_name] = {};
})();

NS.methods = {
  toMaxlength : function(text,num){
    if(text.length > num) text = text.substring(0,num)+"...";
    return text ;
  },
  toDateFormat : function(date){
    if(typeof date == "string") date = new Date(date);
    return date.getFullYear() +"."+ NS.methods.toZeroPad((date.getMonth()+1),2) +"."+ NS.methods.toZeroPad(date.getDate(),2) ;
  },
  toZeroPad : function(str,digit){
    var arr = ["","0","00","000","0000","00000"];
    if(typeof str == "number") str = str.toString();
    return (str.length < digit) ? arr[digit-str.length]+str : str ;
  }
};

// NS.GoogleMaps Class ////////////////////////////////////////////

NS.GoogleMaps = function(target/* #idname */,coordinates/* arr */,zoom){
  var _this = this ;
  
  this.target = $(target);
  if(!this.target[0]) throw new Error("\""+ target +"\" Element not Found!");
  
  this.coordinates = coordinates ;
  this.zoom = zoom ;

  this.markers = [];
  this.zindex_count = 100 ;

  var map = new GMap2(this.target[0]);
  map.setCenter(new GLatLng(this.coordinates[0],this.coordinates[1]),zoom);
  map.setUIToDefault();

  //キーボードで操作
  new GKeyboardHandler(map);

  this.map = map;
};
NS.GoogleMaps.prototype = {
  addMarker : function(coordinates/* arr */,text/* htmltxt */){
    
    var _this = this ;
    var marker = new GMarker(new GLatLng(coordinates[0],coordinates[1]));
    
    this.map.addOverlay(marker);
    
    GEvent.addListener(marker,'click',function(){    
      marker.openInfoWindowHtml(text);
      marker.fm.style.zIndex = _this.zindex_count ;
      _this.zindex_count++;
    });
    
    this.markers.push(marker);
  },
  addCustomMarker : function(setting/* obj */){
    
    var _this = this ;
    
    var icon = new GIcon();
    icon.image = setting.image;
    icon.iconSize = new GSize(setting.size[0],setting.size[1]);
    icon.iconAnchor = new GPoint(setting.anchor[0],setting.anchor[1]);
    icon.infoWindowAnchor = new GPoint(setting.anchor[0],0);

    if(setting.shadow){
      icon.shadow = setting.shadow;
      icon.shadowSize = new GSize(setting.shadowSize[0],setting.shadowSize[1]);
    }
  
    var marker = new GMarker(new GLatLng(setting.coordinates[0],setting.coordinates[1]),icon);
    
    if(setting.text){
      GEvent.addListener(marker,'click',function(){
        marker.openInfoWindowHtml(setting.text);
        marker.fm.style.zIndex = _this.zindex_count ;
        _this.zindex_count++;
      });
    }

    this.map.addOverlay(marker);
    this.markers.push(marker);
  }
};


// Copyright Updater ////////////////////////////////////////////
$("#year").text((new Date()).getFullYear());


// Entries Json Data ////////////////////////////////////////////
NS.blogs = [];

$.ajax({
   url : "/dir/ticket/special_plan/api/entries.json",
   dataType : "jsonp" ,
   jsonp : "callback",
   type : "GET" ,
   success : getEntries17 = function(data,status){
      NS.blogs.push({
         name : "スペシャルプラン（Special Plan）",
         id   : "17",
         entries : data
      });
   }
});

$.ajax({
   url : "/dir/contents/teamblueman/api/entries.json",
   dataType : "jsonp" ,
   jsonp : "callback",
   type : "GET" ,
   success : getEntries16 = function(data,status){
      NS.blogs.push({
         name : "チームブルーマン",
         id   : "16",
         entries : data
      });
   }
});

$.ajax({
   url : "/dir/topbnrdata/api/entries.json",
   dataType : "jsonp" ,
   jsonp : "callback",
   type : "GET" ,
   success : getEntries19 = function(data,status){
      NS.blogs.push({
         name : "トップバナー更新",
         id   : "19",
         entries : data
      });
   }
});

$.ajax({
   url : "/dir/news/api/entries.json",
   dataType : "jsonp" ,
   jsonp : "callback",
   type : "GET" ,
   success : getEntries15 = function(data,status){
      NS.blogs.push({
         name : "ニュース(News)",
         id   : "15",
         entries : data
      });
   }
});

$.ajax({
   url : "/mobile/api/entries.json",
   dataType : "jsonp" ,
   jsonp : "callback",
   type : "GET" ,
   success : getEntries20 = function(data,status){
      NS.blogs.push({
         name : "ブルーマン・モバイルサイト",
         id   : "20",
         entries : data
      });
   }
});

$.ajax({
   url : "/dir/about/message/api/entries.json",
   dataType : "jsonp" ,
   jsonp : "callback",
   type : "GET" ,
   success : getEntries26 = function(data,status){
      NS.blogs.push({
         name : "著名人からのメッセージ(Message)",
         id   : "26",
         entries : data
      });
   }
});

$.ajax({
   url : "/dir/theatre/gourmet/api/entries.json",
   dataType : "jsonp" ,
   jsonp : "callback",
   type : "GET" ,
   success : getEntries25 = function(data,status){
      NS.blogs.push({
         name : "近隣グルメマップ(Gourmet)",
         id   : "25",
         entries : data
      });
   }
});

$.ajax({
   url : "/dir/ticket/today/api/entries.json",
   dataType : "jsonp" ,
   jsonp : "callback",
   type : "GET" ,
   success : getEntries18 = function(data,status){
      NS.blogs.push({
         name : "当日券情報",
         id   : "18",
         entries : data
      });
   }
});

$.ajax({
   url : "/dir/viewpoint/api/entries.json",
   dataType : "jsonp" ,
   jsonp : "callback",
   type : "GET" ,
   success : getEntries14 = function(data,status){
      NS.blogs.push({
         name : "新しいブルーマンのみどころ(What's Blue Man Group 2010?)",
         id   : "14",
         entries : data
      });
   }
});


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

showPopupNav("#toTicket","#popnavTicket");
showPopupNav("#toTheatre","#popnavTheatre");
showPopupNav("#toAbout","#popnavViewPoint");

function showPopupNav(target,popup){
  target = $(target);
  popup = $(popup);

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


// topIndex ////////////////////////////////////////////
   (function(){
      if(!($("#topIndex")[0])) return ;

      // International Sites
      if(!$("#toInternational")[0]) return ;
      var target = $("#toInternational dd").css("visibility","visible").hide();

      $("#toInternational dt > a").mouseover(function(e){
         target.show();
         $(this).addClass("hover");
      });
      target.mouseover(function(){
         $(this).show();
         $("#toInternational dt > a").addClass("hover");
      });
      target.mouseout(function(){
         $(this).hide();
         $("#toInternational dt > a").removeClass("hover");
      });
      
      /* Twetter Ballon  2010.04.14 del
      $("#ballon").hide();
      $("#toTwitter").mouseover(function(){
         $("#ballon").fadeIn(300);
      });
      $("#toTwitter").mouseout(function(){
         $("#ballon").fadeOut(300);
      });
      */

      // Balllons  2010.04.14 add
      createBallon("toGroup","ballonGroup","会社のレクリエーションや修学旅行にも！");
      createBallon("toEnglish","ballonEnglish","English Ticketing Information");
      createBallon("toTwitter","ballonTwitter","twitterでブルーマンがつぶやく!?");

      function createBallon(btnid,ballon_id,baloontxt){
         if(!$("#" + btnid)[0]) return ;
         var ballon = $("<li><em>"+baloontxt+"</em></li>").addClass("ballon").attr("id",ballon_id).hide().insertAfter("#" + btnid);
         $("#" + btnid).mouseover(function(){
            ballon.fadeIn(300);
         });
         $("#" + btnid).mouseout(function(){
            ballon.fadeOut(300);
         });
      }

      // setNewIcon 2010.04.08 add
      setNewIcon($("#toStaff"));
      
      function setNewIcon(jqobj){
        if(!jqobj[0]) return ;
        $("<strong><span>NEW</span></strong>").addClass("iconNew Replace").insertAfter(jqobj);
      }
   })();

// topIndex Tweet ////////////////////////////////////////////
   (function (){
      if(!($("#topIndex")[0])) return ;
      if(!($("#tweet")[0])) return ;
      var url = "http://twitter.com/statuses/user_timeline/";
      var reg_url = /https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:@&=+$,%#]+/g;

      var count = 0 ;
      $.getJSON(url + "109214870" + ".json?callback=?",function(res){
         NS.tweet = res ;
         var act = null ;
         var run = false ;

/* mouseover start
         $("#toTwitter a").bind("mouseover",showTweets);
         $("#toTwitter a").mouseout(function(){
            $("#tweet").children().fadeOut(300,function(){
               $("#tweet").empty();
               clearInterval(act);
               run = false ;
            });
         });
*/
        showTweets();

         function showTweets(e){
            if(run) return ;
            run = true ;

            var prof = "<img src=\"" + res[0].user.profile_image_url + "\" />";
            $("<div class=\"profimg\">" + prof + "</div>").appendTo($("#tweet")).hide().fadeIn(600);
            var tweets = [] ;
            tweets[count] = createTweet(res,count).hide().fadeIn(600,function(){
               act = setInterval(function(){
                  var prv = count ;
                  count = (count+1)%res.length;
                  tweets[count] = createTweet(res,count).hide();
                  tweets[prv].slideUp(300,function(){
                     tweets[count].slideDown(300,function(){
                        tweets[prv].remove();
                     });
                  });
               },10000);
            });

            function createTweet(res,num){
               var txt = replaceURL(res[num].text);
               var time = new Date(res[num].created_at);
               return $("<div class=\"tweetbox\"><p>"+ txt +"</p><p class=\"time\">"+ convert_time(time) +"</p></div>").appendTo($("#tweet"));    
            }

            function convert_time(d){
               var year = d.getFullYear();
               var month = pad(d.getMonth()+1);
               var day = pad(d.getDate());
               var hour = pad(d.getHours());
               var min = pad(d.getMinutes());
               return year + "." + month + "." + day + " " + hour + ":" + min;

               function pad(num){
                 return ((num.toString()).length == 1)?("0" + num.toString()):num;
               }
            }

            function replaceURL(txt){
               return txt.replace(reg_url,"<a href=\"$&\" target=\"_blank\">$&</a>");
            }
         }

      });
   })();


   
// UpdateTxt ////////////////////////////////////////////
   (function(){
      return ;
      if(!(($("#ticketIndex")[0] || $("#theatreIndex")[0]) || $("#scheduleIndex")[0])) return ;
      
      var url = "/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);
      });
   })();

      /* 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 ;
    
    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(){
      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]];
            
      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].fm.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 ;
 
    var target = $("#loadTweets") ;
    var interval = 1 * 60 * 1000 ;
    
    $.getScript("/dir/js/tweet.js",function(){
      target.empty();
      var tweet = NS.tweets = new NS.Tweets(target);
      tweet.cacheExpire = interval ;
      tweet.searchKeywordCustom({keyword : "#BlueMan",maxlength:30});

      setInterval(function(){
          tweet.searchKeywordCustom({keyword : "#BlueMan",maxlength:30});
        }
        ,interval)
      });
  })();



// 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();
      });
   })();


});
