/**
 * jCalendar 0.5
 *
 * Some code based on jQuery Date Picker (http://kelvinluck.com/assets/jquery/datePicker/)
 *
 * Copyright (c) 2007 Theodore Serbinski (http://tedserbinski.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 */
var old_ym = '';

jQuery.jcalendar = function() {
	var months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
	var days = ['日', '月', '火', '水', '木', '金', '土'];
	var navLinks = {p:'&lt;&lt;先月', n:'次月&gt;&gt;', t:'今日'};
	var _firstDayOfWeek;
	var _firstDate;
	var _lastDate;
	var _selectedDate;

	var _drawCalendar = function(dateIn, a, day, month, year) {
		var today = new Date();
		var d;

		if (dateIn == undefined) {
			// start from this month.
			d = new Date(today.getFullYear(), today.getMonth(), 1);
			/*
			year.val(today.getFullYear());
			month.val(today.getMonth()+1);
			day.val(today.getDate());
			*/
		}
		else {
			// start from the passed in date
			d = dateIn;
			d.setDate(1);
		}

		// check that date is within allowed limits
		if ((d.getMonth() < _firstDate.getMonth() && d.getFullYear() == _firstDate.getFullYear()) || d.getFullYear() < _firstDate.getFullYear()) {
			d = new Date(_firstDate.getFullYear(), _firstDate.getMonth(), 1);
		}
		else if ((d.getMonth() > _lastDate.getMonth() && d.getFullYear() == _lastDate.getFullYear()) || d.getFullYear() > _lastDate.getFullYear()) {
			d = new Date(_lastDate.getFullYear(), _lastDate.getMonth(), 1);
		}

		var firstMonth = true;
		var firstDate = _firstDate.getDate();

		// create prev and next links
		if (!(d.getMonth() == _firstDate.getMonth() && d.getFullYear() == _firstDate.getFullYear())) {
			// not in first display month so show a previous link
			firstMonth = false;
			var lastMonth = d.getMonth() == 0 ? new Date(d.getFullYear()-1, 11, 1) : new Date(d.getFullYear(), d.getMonth()-1, 1);
			var prevLink = jQuery('<a href="" class="link-prev"> '+ navLinks.p +'</a>').click(function() {
				jQuery.jcalendar.changeMonth(lastMonth, this, day, month, year);
				return false;
			});
		}

		var finalMonth = true;
		var lastDate = _lastDate.getDate();

		if (!(d.getMonth() == _lastDate.getMonth() && d.getFullYear() == _lastDate.getFullYear())) {
			// in the last month - no next link
			finalMonth = false;
			var nextMonth = new Date(d.getFullYear(), d.getMonth()+1, 1);
			var nextLink = jQuery('<a href="" class="link-next">'+ navLinks.n +' </a>').click(function() {
				jQuery.jcalendar.changeMonth(nextMonth, this, day, month, year);
				return false;
			});
		}

		var todayLink = jQuery('<a href="" class="link-today">'+ navLinks.t +'</a>').click(function() {
			day.val(today.getDate());
			jQuery.jcalendar.changeMonth(today, this, day, month, year);
			return false;
		});

		// update the year and month select boxes
		year.val(d.getFullYear());
		month.val(d.getMonth()+1);

		var headRow = jQuery("<tr></tr>");
		for (var i=_firstDayOfWeek; i<_firstDayOfWeek+7; i++) {
			var weekday = i%7;
			var wordday = days[weekday];
			var c = 'weekday';
					if(weekday == 0){
						c = 'weekstart';
					}else if(weekday == 6){
						c = 'weekend';
					}
			headRow.append('<th class="'+ c +'">'+ wordday +'</th>');
		}
		headRow = jQuery("<thead></thead>").append(headRow);

		var tBody = jQuery("<tbody></tbody>");
		var lastDay = (new Date(d.getFullYear(), d.getMonth()+1, 0)).getDate();
		var curDay = _firstDayOfWeek - d.getDay();
		if (curDay > 0) curDay -= 7;

		var todayDate = today.getDate();
		var thisMonth = d.getMonth() == today.getMonth() && d.getFullYear() == today.getFullYear();

		/* 月を取得 */
		var nowMon = jQuery('#c-month').val();

		// render calendar
		var myyear = jQuery('#c-year').val();
		var mymonth = '';
		var myweek = 0;
		var myday = '';
		do {
			var thisRow = jQuery("<tr></tr>");
			for (var i=0; i<7; i++) {
				var weekday = (_firstDayOfWeek + i) % 7;
				var c = 'weekday';

				if (curDay < 0) {
					var preMonthLastDay = (new Date(d.getFullYear(), d.getMonth(), 0)).getDate();
					dayStr = '<div class="no-act">'+(preMonthLastDay + curDay + 1)+'</div>';

					mymonth = (nowMon - 1 != 0 ? nowMon - 1 : 12);
					myday = preMonthLastDay + curDay + 1;
				}else if(curDay >= lastDay){
					dayStr = '<div class="no-act">'+(curDay - lastDay + 1)+'</div>';

					mymonth = (nowMon + 1 != 13 ? nowMon + 1 : 1);
					myday = curDay - lastDay + 1;
				}
				else if (firstMonth && curDay < firstDate-1) {
					dayStr = curDay+1;

					mymonth = nowMon;
					myday = curDay+1;
					atts['class'] += 'inactive';
				}
				else if (finalMonth && curDay > lastDate-1) {
					dayStr = curDay+1;

					mymonth = nowMon;
					myday = curDay+1;
					atts['class'] += 'inactive';
				}
				else {
					d.setDate(curDay+1);
					mymonth = nowMon;
					myday = curDay+1;

					var mm = (mymonth.toString().length > 1 ? mymonth : '0'+mymonth);
					var dd = (myday.toString().length > 1 ? myday : '0'+myday);
					var mykey = jQuery('#c-year').val()+'-'+mm+'-'+dd;

					var now = '20081008';

					if((myyear+mm+dd) <= now){
					dayStr = jQuery('<a href="" rel="'+ d +'">'+ (curDay+1) +'</a>').click(function(e) {
						if (_selectedDate) {
							_selectedDate.removeClass('selected');
						}
						_selectedDate = jQuery(this);
						_selectedDate.addClass('selected');
						day.val(new Date(_selectedDate.attr('rel')).getDate());
/*
						// ラジオボタンの選択値を取得
						var vi = jQuery('input[@name=vi]:checked').val();
						if(vi == 'w'){
							var wd = new Date(ly = jQuery('#c-year').val(), jQuery('#c-month').val(), jQuery('#c-day').val());
							var ww = wd.getDay() - 3;
							if(ww < 0){
								ww += 7;
							}
							var ws = jQuery('#c-day').val() - ww;
						}else if(vi == 'm'){

						}
*/
						return false;
					});
					}else{
						dayStr = '<div class="no-act">'+(curDay+1)+'</div>';
					}

					// highlight the current selected day
					if ((myyear+mm+dd) == now) {
						_selectedDate = dayStr;
						_selectedDate.addClass('selected');
					}
				}

				/*
				if (thisMonth && curDay+1 == todayDate) {
					atts['class'] += 'today';
				}
				*/

				c += ' w'+myweek+' m'+mymonth;
				var atts = {'class':c};
				thisRow.append(jQuery("<td id='d"+mymonth+'-'+myday+"'></td>").attr(atts).append(dayStr));
				curDay++;
			}

			tBody.append(thisRow);
			myweek++;
		} while (curDay < lastDay);

		jQuery('#canvas_calender').html('<table cellpadding="0" cellspacing="1" id="calendar"></table><div id="c-nav" class="page"></div>');
		jQuery('#calendar').append(headRow, tBody);
		jQuery('#c-nav').append(prevLink, todayLink, nextLink);
		getNikki();
	};

	return {
		show: function(a, day, month, year) {
			_firstDate = a._startDate;
			_lastDate = a._endDate;
			_firstDayOfWeek = a._firstDayOfWeek;

			// pass in the selected form date if one was set
			var selected;
			if (year.val() > 0 && month.val() > 0 && day.val() > 0) {
				selected = new Date(year.val(), month.val()-1, day.val());
			}
			else {
				selected = null;
			}
			_drawCalendar(selected, a, day, month, year);
		},
		changeMonth: function(d, e, day, month, year) {
			_drawCalendar(d, e, day, month, year);

			return false;
		},
		/**
		* Function: setLanguageStrings
		*
		* Allows you to localise the calendar by passing in relevant text for the english strings in the plugin.
		*
		* Arguments:
		* days		-	Array, e.g. ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
		* months	-	Array, e.g. ['January', 'Febuary', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
		* navLinks	-	Object, e.g. {p:'Prev', n:'Next', c:'Close', b:'Choose date'}
		**/
		setLanguageStrings: function(aDays, aMonths, aNavLinks) {
			days = aDays;
			months = aMonths;
			navLinks = aNavLinks;
		},
		/**
		* Function: setDateWindow
		*
		* Used internally to set the start and end dates for a given date select
		*
		* Arguments:
		* i			-	The id of the INPUT element this date window is for
		* w			-	The date window - an object containing startDate and endDate properties
		*				e.g. {startDate:'24-11-1981', endDate:'25-12-2012}
		**/
		setDateWindow: function(i, w, year) {
			if (w == undefined) w = {};
			if (w.startDate == undefined) {
				// set the minimum browseable date equal to January of the min year in the select box
				// don't get the first option because that is an empty year

				// note we can't do this: year.find('option:eq(1)').val()
				// it doesn't work in 1.0 since find() is destructive
				// so we copy the object to a new var
				i._startDate = new Date(jQuery(year).find('option:eq(1)').val(), 0, 1);
			}
			else {
				dateParts = w.startDate.split('-');
				i._startDate = new Date(dateParts[2], Number(dateParts[1])-1, Number(dateParts[0]));
			}
			if (w.endDate == undefined) {
				// set the maximum browseable date equal to December of the max year in the select box

				// note we can't do this: year.find('option:last').val()
				// it doesn't work in 1.0 since find() is destructive
				// so we copy the object to a new var
				i._endDate = new Date(jQuery(year).find('option:last').val(), 11, 1);
			}
			else {
				dateParts = w.endDate.split('-');
				i._endDate = new Date(dateParts[2], Number(dateParts[1])-1, Number(dateParts[0]));
			}
			i._firstDayOfWeek = w.firstDayOfWeek == undefined ? 0 : w.firstDayOfWeek;
		}
	};
}();

jQuery.fn.jcalendar = function(a) {
	this.each(function() {
		var year = jQuery('#c-year');
		var month = jQuery('#c-month');
		var day = jQuery('#c-day');

		jQuery('div.c-lists').after('<div id="canvas_calender"></div>');
		jQuery.jcalendar.setDateWindow(this, a, year);
		jQuery.jcalendar.show(this, day, month, year);

		day.change(function() {
			// only if a valid day is selected
			d = new Date(year.val(), month.val()-1, this.value);
			jQuery.jcalendar.changeMonth(d, a, day, month, year);
		});

		month.change(function() {
			// only if a valid month is selected
			d = new Date(year.val(), this.value-1, 1);
			jQuery.jcalendar.changeMonth(d, a, day, month, year);
		});

		year.change(function() {
			// only if a valid year is selected
			d = new Date(this.value, month.val()-1, 1);
			jQuery.jcalendar.changeMonth(d, a, day, month, year);
		});
	});
	return this;
};



function getNikki(){
	if(old_ym != jQuery('#c-year').val()+jQuery('#c-month').val()){
		old_ym = jQuery('#c-year').val()+jQuery('#c-month').val();
		jQuery.ajax({
			'type':'POST',
			'url':'/note/meal_diary.html',
			'dataType':'json',
			'data':{'pu': jQuery('#pu').val(), 'y': jQuery('#c-year').val(), 'm' : jQuery('#c-month').val()},
			'success':function(response){
									for(k in response){
										var d_obj = jQuery('#d'+jQuery('#c-month').val()+'-'+response[k]);
										d_obj.css('background', "url('/note/img/cld-d-back3.gif') no-repeat");
										d_obj.css('font-weight', 'bold');
									}
								}
		});
	}
}
