// 「今日ならマークアップ」の下ごしらえ
	var nowdate = new Date();
	var nowdateYear = nowdate.getFullYear(); // 年
	var nowdateMon  = nowdate.getMonth() + 1; // 月
	var nowdateDate = nowdate.getDate(); // 日
	

// イベント最終月
var lastMonth = "200912";

// アクセス時に表示する schedule の月
var indexYear = "2009";
var indexMonth = nowdateMon;

var showMonth = "";


// 前日／翌日
var gLastDay = "";
var gNextDay = "";

// 日付の配列
var gDayArray = [];

// 月の範囲 scope（あとでMTではきだす）
var monthScope = [11, 12];

// 日付の範囲 scope
var dayScope_First = "20091101";
var dayScope_End = "20091231";



$(function(){

	// DayCal用の要素をカレンダー要素のすぐ後に追加する。
	$("#scheduleCalDiv").after("<div id='dayCal'></ div>");
	$("#dayCal").append("<div id='prev' /><div id='current' /><div id='next' />");
			


function addSchedule(){

	// * 「Loading」中の表示
	//$("table#scheduleCal").text("Loading...");
	
	
	// 「今日ならマークアップ」の下ごしらえ
	var nowdate = new Date();
	var nowdateYear = nowdate.getFullYear(); // 年
	var nowdateMon  = nowdate.getMonth() + 1; // 月
	var nowdateDate = nowdate.getDate(); // 日
	
	if( nowdateMon < 10) 
	{
		nowdateMon = "0" + nowdateMon;
	}
	
	if( nowdateDate < 10) 
	{
		nowdateDate = "0" + nowdateDate;
	}
	
	
	
	
	// 最初のアクセスなら、indexMonthを表示する。それ以外は、showMonth の値をそのまま利用する。
	//1001-
	//( showMonth == "" ) ? (showMonth = indexMonth) : showMonth;
	showMonth = "12";
	
	// * ajax通信を行います
    $.ajax({
    
        dataType: "json",    // * データ形式は JSON を指定します。
        cache: true,          // * キャッシュを使用します。
        //1001-
		//url: "jsonmonth/" + indexYear + showMonth + ".json",
        url: "jsonmonth/" + 200912 + ".json",
        
        // 失敗
        error: function (XMLHttpRequest, status, errorThrown) {

	    	$("#current").append("<h3>サーバーが混雑しているようです。後でもう一度リロードしてください。</ h3>");
		},
	        
        // 成功
        success: function (data) {
			
			// 「Loading」表示を削除する。
            $("table#scheduleCal").empty().append("<tr><th><img src='assets/calender/week/1_mon.gif' alt='mon' /></th><th><img src='assets/calender/week/2_tue.gif' alt='tue' /></th><th><img src='assets/calender/week/3_wed.gif' alt='wed' /></th><th><img src='assets/calender/week/4_thu.gif' alt='thu' /></th><th><img src='assets/calender/week/5_fri.gif' alt='fri' /></th><th><img src='assets/calender/week/6_sat.gif' alt='sat' /></th><th><img src='assets/calender/week/7_sun.gif' alt='sun' /></th></tr>");
            
       
            // 行番号の初期化
            var trNum = 0;
            
            // 曜日配列。
            var calWeekDay = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat","Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat","Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat","Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
            
            // * 配列 dataの数だけ繰り返す。データは item に代入。
			$.each(data, function(i,item){
				
				// 一意の日付ID
				if(item.calendarDay < 10) 
				{
					var itemDateID = item.calendarYM + "0" + item.calendarDay;
				}
				else
				{
					var itemDateID = item.calendarYM + item.calendarDay;
				}
				
				// 日付の配列に push する。
				gDayArray.push(itemDateID);
				
				
				// カレンダーセルナンバー。曜日の算出。
				var calendarCellNum = ( item.calendarCellNumber );
				
				
				// 日付画像の割当
				var itemMonth = String(item.calendarYM).slice(4);
				
				var eventDateImg = "<img src='assets/day_event/num/"+itemMonth+".gif' alt='"+itemMonth+"' /><img src='assets/day_event/negi/day_negi.gif' alt='/' /><img src='assets/day_event/num/"+item.calendarDay+".gif' alt='"+item.calendarDay+"' /><img src='assets/day_event/week/"+String(calWeekDay[calendarCellNum-1])+".gif' alt='"+String(calWeekDay[calendarCellNum-1])+"' class='"+String(calWeekDay[calendarCellNum-1])+"' />";
				
				var eventDateImgON = "<img src='assets/day_event/num_on/"+itemMonth+".gif' alt='"+itemMonth+"' /><img src='assets/day_event/negi_on/day_negi.gif' alt='/' /><img src='assets/day_event/num_on/"+item.calendarDay+".gif' alt='"+item.calendarDay+"' /><img src='assets/day_event/week_on/"+String(calWeekDay[calendarCellNum-1])+".gif' alt='"+String(calWeekDay[calendarCellNum-1])+"' class='"+String(calWeekDay[calendarCellNum-1])+"' />";
				
				
				
				
				// （イベントがない日用）カレンダーの日付画像をどこからとってくるか
				var dayDirectory = "";
				
				// 今日なら、
				if(itemDateID === String(nowdateYear)+String(nowdateMon)+String(nowdateDate))
				{
					dayDirectory = "today";
					eventDateImg = eventDateImgON;
				}
				else
				{
					dayDirectory = "day";
				}
				
				
				// カレンダー画像に class 要素 archive を入れると「斜線」表示。
				var imgClass = "";
				
				// 今日より以前なら
				if(itemDateID < String(nowdateYear)+String(nowdateMon)+String(nowdateDate))
				{
					imgClass = "archive";
				}
				else
				{
					imgClass = "";
				}
				
				
				
				// -- テーブル要素を生成する。 ---------------------------------------------------------------------------------------------------
				// 新しい tr 要素、および月曜でお休み。
				if( (calendarCellNum == 2) || (calendarCellNum == 9) || (calendarCellNum == 16) || (calendarCellNum == 23) || (calendarCellNum == 30) )
				{
					trNum++;
					
					$("table#scheduleCal").append("<tr id='"+ trNum +"'><td id='" + itemDateID + "' class='date_has_event mon'><img src='assets/calender/day/"+item.calendarDay+".gif' alt='' class='holiday out' /><img src='assets/calender/today/"+item.calendarDay+".gif' alt='' class='holiday on' /><div class='events'><ul><li><span class='holiday'>Regular Holiday</span></li></ul></div></td></tr>");
				}
				
				// 火曜〜日曜
				else 
				{
					if ( item.eventContent == "" )
					{
						// イベントが無い日。
						$("table#scheduleCal tr#" + trNum).append("<td id='" + itemDateID + "' class=''><img src='assets/calender/"+dayDirectory+"/"+item.calendarDay+".gif' alt='' class='"+imgClass+"' /></td>");
					}
					else
					{
						if (item.id != "end")
						{
							// イベントがある日。td のクラス要素に主催者を追加する。
							$("table#scheduleCal tr#" + trNum).append("<td id='" + itemDateID + "' class='date_has_event " + item.eventContent.office + "'><a href='day/" + itemDateID + ".html'><img src='assets/calender/day/"+item.calendarDay+".gif' alt='' class='"+imgClass+" out' /><img src='assets/calender/today/"+item.calendarDay+".gif' alt='' class='"+imgClass+" on' /></a><div id='"+ itemDateID +"' class='events'><ul><li id='" + itemDateID + "'><span class='desc date eventoff'>" + eventDateImg + "</span><img class='thumb' alt='' src='assets/office_" + item.eventContent.office + ".gif' /><span class='title'>" + item.eventContent.eventTitle + "</span><span class='desc'>" + item.eventContent.host + "</span></ li></ ul></div></td>" );
							
							$("table#scheduleCal tr#" + trNum + " td.date_has_event span.eventon").hide();
							
						}
					}
				}
				
				
				
				$("img.on").hide();
				
			});
			
			
			// 月表示変更 および 前月次月へのリンク付け。
			$("div#scheduleCalMonth").append( addMonthScope() );
			
			// 今月分のみ表示する
			$("table#scheduleCal").append(hideOtherMonth( String(showMonth) ));
			
			// popupの追加
			$("table#scheduleCal").append( addDateHasEvent());
			
			
			// DayCalの操作
			$("table#scheduleCal").append( addDayfromSchedule() );
				
        }
    });
}

// 最初の Schedule 生成。
addSchedule();




// -- Day ページへ遷移。htmlで実現。 ---------------------------------------------------------------------------------
function addDayfromSchedule() {

	
	$('td.date_has_event ul').each(function (ev){

		// id が空でないとき、（holiday対策）
		if( $("li", this).attr("id") ){		
			
			$(this).hover(function(){
				
				// カーソルの表示を変更。
				$(this).css({ 'cursor':'pointer'});
				
				/*
				// 日付画像をredに。
				$("span.eventoff", this).hide(0);
				$("span.eventon", this).show(0);
				*/
				
				/*
				// fukidashi _on
				$('.eventhead', this).empty().append('<img src="assets/bk_event_head_on.gif" alt="" />');
				$('.eventfoot', this).css({ 'background':'transparent url(assets/bk_event_foot_on.gif) top left no-repeat'});
				
				$('li', this).css({'background':'transparent url(assets/bk_event_on.gif) top left repeat-y'});
				*/
				
			},function(){
				
				//$(this).css({ 'cursor':'default'}); 
				
				/*
				// 日付画像を通常に。
				$("span.eventon", this).hide();
				$("span.eventoff", this).show();
				*/
				
				/*
				// fukidashi
				$('.eventhead', this).empty().append('<img src="assets/bk_event_head.gif" alt="" />');
				$('.eventfoot', this).css({ 'background':'transparent url(assets/bk_event_foot.gif) top left no-repeat'});
				
				$('li', this).css({'background':'#000 url(assets/bk_event.gif) top left repeat-y'});
				*/
			});

			// td.date_has_event ul li のクリック処理。
			$(this).click(function (ev) {
			
				// Dayページ表示（html）
				//$.append("day/"+$(this).attr("id")+".html");
			    location.href = "day/"+$("li", this).attr("id")+".html";
				
				
				// td.date_has_event ul li の id を格納（json ファイル名などになる）。
				//var jsonDate = $(this).attr("id");
				
				// Dayページ表示（json）
				//addDay(jsonDate);
			
			});
		}
		
	});
}

// ***************************************************************************
// 月表示変更 および 前月次月へのリンク付け。
function addMonthScope() {
	
	// 最初のアクセスなら、indexMonthを表示する。それ以外は、showMonth の値をそのまま利用する。
	//( showMonth == "" ) ? (showMonth = indexMonth) : showMonth;
	
	$("div#scheduleCalMonth h3").empty().append("<img alt='09/"+indexMonth+"' src='assets/calender/month/"+showMonth+".gif' />");
	
	
	var lastMonthIs = ($.inArray((Number(showMonth)-1), monthScope));
	var nextMonthIs = ($.inArray((Number(showMonth)+1), monthScope));
	
	// 月おくりに関する設定
	if( lastMonthIs == -1 ){
		
		$("div#scheduleCalMonth p.toLastMonth").fadeTo(0, 20);// ×
		$("div#scheduleCalMonth p.toLastMonth").removeAttr("id");
	}
	else
	{
		$("div#scheduleCalMonth p.toLastMonth").attr("id", indexYear+monthScope[lastMonthIs]);
		
		$("div#scheduleCalMonth p.toLastMonth").one("click",function(){
		//$("div#scheduleCalMonth p.toLastMonth").click(function(ev){
			var sm = $(this).attr("id");
			showMonth = sm.toString().slice(4);
			addSchedule();
		});
	}
	
	if( nextMonthIs == -1 ){
		$('div#scheduleCalMonth p.ahover').fadeTo(0, 20);// ×
		$("div#scheduleCalMonth p.toNextMonth").removeAttr("id");
	}
	else
	{
		$("div#scheduleCalMonth p.toNextMonth").attr("id", indexYear+monthScope[nextMonthIs]);
		
		$("div#scheduleCalMonth p.toNextMonth").one("click",function(){
		//$("div#scheduleCalMonth p.toNextMonth").click(function(ev){
			var sm = $(this).attr("id");
			showMonth = sm.toString().slice(4);
			addSchedule();
		});
		
	}
	
}


// 今月分のみ表示する
function hideOtherMonth(tMonth) {

	if( String(tMonth) == "11" ){

		$("tr#1").hide();
		$("tr#2").hide();
		$("tr#3").hide();
	
		$("tr#10").hide();
		$("tr#11").hide();
		$("tr#12").hide();
		$("tr#13").hide();
	}
	
	if( String(tMonth) == "12" ){

		$("tr#1").hide();
		$("tr#2").hide();
		$("tr#3").hide();
		$("tr#4").hide();
		
		$("tr#10").hide();
		$("tr#11").hide();
		$("tr#12").hide();
		$("tr#13").hide();
	}
		
}


function addDateHasEvent() {
	
	$('td.date_has_event').each(function () {
	
		// options
		var distance = 10;
		//var time = 250;
		var time = 200;
		var hideDelay = 250;
	
		var hideDelayTimer = null;
	
		// tracker
		var beingShown = false;
		var shown = false;
	
		var trigger = $(this);
		var popup = $('.events ul', this).css('opacity', 0);
		var coverdown = $('.cover', this).css('top', 0);
		
		
		
		
		// 「今日ならマークアップ」の下ごしらえ
		var nowdate = new Date();
		var nowdateYear = nowdate.getFullYear(); // 年
		var nowdateMon  = nowdate.getMonth() + 1; // 月
		var nowdateDate = nowdate.getDate(); // 日
		
		if( nowdateMon < 10) 
		{
			nowdateMon = "0" + nowdateMon;
		}
		
		if( nowdateDate < 10) 
		{
			nowdateDate = "0" + nowdateDate;
		}
		
		
		
		// 今日なら、
		if($('.events ul li', this).attr("id") === String(nowdateYear)+String(nowdateMon)+String(nowdateDate))
		{
			
			// fukidashi _on
		
			$('.events ul li', this).css({'background':'transparent url(assets/bk_event_on.gif) top left repeat-y'});
	
			$('.events ul', this).prepend('<div class="eventhead"><img src="assets/bk_event_head_on.gif" alt="" /></div>');
			$('.events ul', this).append('<div class="eventfoot"><span alt="" style=" display:block; height:19px;" /></span></div>');
			$('.events ul .eventfoot', this).css({ 'background':'transparent url(assets/bk_event_foot_on.gif) top left no-repeat'});
		
		/*
			$('.eventhead', this).empty().append('<img src="assets/bk_event_head_on.gif" alt="" />');
			
			$('li', this).css({'background':'transparent url(assets/bk_event_on.gif) top left repeat-y'});
			$('.eventfoot', this).css({ 'background':'transparent url(assets/bk_event_foot_on.gif) top left no-repeat'});
		*/	
		}
		else
		{
			// fukidashi
			$('.events ul li', this).css({'background':'transparent url(assets/bk_event.gif) top left repeat-y'});
	
			$('.events ul', this).prepend('<div class="eventhead"><img src="assets/bk_event_head.gif" alt="" /></div>');
			$('.events ul', this).append('<div class="eventfoot"><span alt="" style=" display:block; height:19px;" /></span></div>');
			$('.events ul .eventfoot', this).css({ 'background':'transparent url(assets/bk_event_foot.gif) top left no-repeat'});
			
//			$('.events ul .eventfoot:after', this).css({ 'height': '0', 'visibility': 'hidden', 'content': '.', 'display': 'block', 'clear': 'both'});

		}
		
		
		
		
		// -- Calの日付画像へのマウス操作 ------------------------------------
		// id が空でないとき、（holiday対策）
		if( $("li", this).attr("id") ){		
			
			// 今日なら、
			if($("li", this).attr("id") === String(nowdateYear)+String(nowdateMon)+String(nowdateDate))
			{
				
				// カーソルの表示を変更。
				$(this).css({ 'cursor':'pointer'});
					
				$("img.out", this).hide();
				$("img.on", this).show();
				
			}
			else
			{
			
				$([trigger.get(0), popup.get(0)]).mouseover(function () {
				
					// カーソルの表示を変更。
					$(this).css({ 'cursor':'pointer'});
					
					// 画像の差し替え
					$("img.out", this).hide();
					$("img.on", this).show();
					
				
				}).mouseout(function () {
				
					// 画像の差し替え
					$("img.on", this).hide();
					$("img.out", this).show();
					
				}).click(function (ev) {
				
					// Dayページへ遷移（html）
					location.href = "day/"+$("li", this).attr("id")+".html";
				});
				
			}
		};
		
		
		
		// css: fukidashi archive
		/*
		$('.events ul.archive li', this).css({'background':'#FFF url(assets/bk_slit.gif) top left'});
		$('.events ul.archive li span', this).css({'color':'#333'});
		$('.events ul.archive li span.title', this).css({'color':'#333'});
		*/
		
		
		// -- event（フキダシ）へのマウス操作 ------------------------------------
		// set the mouseover and mouseout on both element
		$([trigger.get(0), popup.get(0)]).mouseover(function () {
			
			// stops the hide event if we move from the trigger to the popup element
			if (hideDelayTimer) clearTimeout(hideDelayTimer);
	
			// don't trigger the animation again if we're being shown, or already visible
			if (beingShown || shown) {
				return;
			} else {
				beingShown = true;
	
				// reset position of popup box
				popup.css({
					bottom: 60,/*52*/
					left: -135,/*-123*/
					display: 'block' // brings the popup back in to view
				})
	
				// (we're using chaining on the popup) now animate it's opacity and position
				.animate({
					//bottom: '+=' + distance + 'px',
					bottom: '-=' + distance + 'px',
					opacity: 1
				}, time, 'swing', function() {
					// once the animation is complete, set the tracker variables
					beingShown = false;
					shown = true;
				});
			}
			
			//coverdown.stop().animate({top:'30px'},{queue:false,duration:80/*duration:160*/});
			
		}).mouseout(function () {
			// reset the timer if we get fired again - avoids double animations
			if (hideDelayTimer) clearTimeout(hideDelayTimer);
	
			// store the timer so that it can be cleared in the mouseover if required
			hideDelayTimer = setTimeout(function () {
				hideDelayTimer = null;
				popup.animate({
					//bottom: '-=' + distance + 'px',
					bottom: '+=' + distance + 'px',
					opacity: 0
				}, time, 'swing', function () {
					// once the animate is complete, set the tracker variables
					shown = false;
					// hide the popup entirely after the effect (opacity alone doesn't do the job)
					popup.css('display', 'none');
				});
			}, hideDelay);
			
			//coverdown.stop().animate({top:'0px'},{queue:false,duration:160});
			
		});
	});
}




});


