function getDate(date){
    return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
}

function showCalendar(currentDate){
    var cal = jQuery('#calendar');
    var naviRow = jQuery('<div id="monthNavi"></div>');
    var table = jQuery('<table></table>');
    var description = jQuery('<div id="description"></div>');

    cal.append('<h2>営業日カレンダー</h2>');
    var prevMLink = jQuery('<span class="prevMonth"><a href="#"><<先月</a></span>').click(function() {
	cal.empty();
	var prevMonth = currentDate.clone().addMonths(-1);
	showCalendar(prevMonth);
	return false;
    });
    //当月の場合は先月へのリンクを表示させない
    if (currentDate.getMonth() != (new Date()).getMonth()){
	naviRow.append(prevMLink);
    }


    var nextMLink = jQuery('<span class="nextMonth"><a href="#">翌月>></a></span>').click(function() {
	cal.empty();
	var nextMonth = currentDate.clone().addMonths(1);
	showCalendar(nextMonth);
	return false;
    });
    naviRow.append(nextMLink);
    cal.append(naviRow);

    //caption
    table.append('<caption>' + currentDate.toString('yyyy年MMMM') + '</caption>');
    
    //Build up the head
    var thead = jQuery('<thead></thead>');
    headRow = jQuery('<tr></tr>');
    for (var i = 1; i < 8; i++) {
	var weekday = i % 7;
	var wordday = Date.CultureInfo.abbreviatedDayNames[weekday];
	if (weekday == 0){
	    headRow.append('<th class="sunday">' + wordday + '</th>');
	} else if (weekday == 6) {
	    headRow.append('<th class="saturday">' + wordday + '</th>');
	} else {
	    headRow.append('<th class="weekday">' + wordday + '</th>');
	}
    }
    thead.append(headRow);
    table.append(thead);

    //Build up the body
    var tbody = jQuery('<tbody></tbody>');
    
    daysInMonth = currentDate.getDaysInMonth();
    gridOffset = (currentDate.clone().moveToFirstDayOfMonth().getDay() + 6) % 7;
    gridRows = Math.ceil((gridOffset + daysInMonth) / 7);
    totalCells = gridRows * 7;

    var loc = window.location;
    var url = '/wp-content/plugins/holiday-calendar/module.php';
    var param = {action: "init", dt:getDate(currentDate)};
    var holidays = [];
    var types = [];
    var comment = '';
    var events = [];
    var title = [];
    var href = [];
    jQuery.ajax({
	type: "GET",
	async: false,
	url: url,
	data: param,
	dataType: "json",
	cache: false,
	success: function(data){
	    for(i=0; i<data.holidays.length; i++){
		holidays[i] = parseInt(data.holidays[i].StartDateTime.substr(8), 10);
		types[i] = data.holidays[i].Title;
	    }

	    for(j=0; j<data.events.length; j++){
		events[j] = data.events[j].dt;
		title[j] = data.events[j].title;
		href[j] = data.events[j].guid;
	    }
	    comment = data.comment;
	}
    });


    for (var i = 0; i < totalCells; i++) {

	if (i % 7 == 0 || i == 0) {
		row = jQuery("<tr></tr>");
		tbody.append(row);
	}
	
	if (i < gridOffset || i >= gridOffset + daysInMonth){
	    row.append('<td></td>');
	} else {
	    day = i - gridOffset + 1;

	    td = jQuery('<td>' + day + '</td>');

	    //休業日設定
	    holiday_index = jQuery.inArray(day, holidays);
	    if ( holiday_index != -1){
		td.addClass(types[holiday_index]);
	    }

	    //イベント日設定
	    text = '';
	    for(j = 0; j < events.length; j++){
		if( events[j] == day ) {
		    text = text + '<li>'+title[j]+'<br />&nbsp;>>&nbsp;<a href="'+href[j]+'">詳細はこちら</a></li>';
		}
	    }

	    if ( text.length > 0 && types[holiday_index] != '全面休業') {
		td.addClass('eventday').qtip({
		    content: { text: '<ol>' + text + '</ol>' },
		    style: {
			border: {
			    width: 10,
			    radius: 6,
			    color: '#99CCff'
			},
			tip: 'bottomLeft',
			'font-size':12,
			width: { min: 200, max: 300 },
			name: 'blue',
			background: '#99CCff'				
		    },
		    show: { when: { event: 'mouseover'} },
		    hide: { when: { event: 'mouseout' }, fixed: true },
		    position: {
			corner: {
			    target: 'topMiddle',
			    tooltip: 'bottomLeft'
			}
		    }
		}).hover(
		    function(){
			jQuery(this).css("background-image", "url(/wp-content/plugins/holiday-calendar/img/eventday-star2.gif)");
		    },
		    function(){
			jQuery(this).css("background-image", "url(/wp-content/plugins/holiday-calendar/img/eventday-star.gif)");
		    }
		);
	    }

	    row.append(td);
	}
    }

    tbody.append(row);
    table.append(tbody);
    cal.append(table);

    setCaution(types, events);

    if(comment != null){
	description.append(comment);
	cal.append(description);
    }
}

function setCaution(types, events){
    var caution = jQuery('#calendar-caution').empty();
    if(events.length > 0){
	caution.append('<img alt="イベント開催日" src="/wp-content/plugins/holiday-calendar/img/calendar-hanrei-event.gif"><br>');
    }

    if(types.length > 0){
	if(jQuery.inArray('全面休業', types) != -1){
	    caution.append('<img alt="休業日" src="/wp-content/plugins/holiday-calendar/img/calendar-hanrei-holiday.gif">');
	}
	if(jQuery.inArray('営業休業', types) != -1){
	    caution.append('<img alt="営業休み" src="/wp-content/plugins/holiday-calendar/img/calendar-hanrei-eigyo.gif">');
	}
	if(jQuery.inArray('サービス休業', types) != -1){
	    caution.append('<img alt="サービス休み" src="/wp-content/plugins/holiday-calendar/img/calendar-hanrei-service.gif">');
	}
    }
}

jQuery().ready(function(){
    showCalendar(new Date());
});
