/*=== Sloths Kid's JS */


/*
call calendar

@lang: String，日历使用的语言，值：cn|en，缺省为en
@date: String, 日期, 值：'YYYY-MM-DD'|null，缺省为系统当前日期
@loadUrl: String，载入json数据（发送：loadUrl?year=xxx&month=xxx，返回{days: [x,xx...]}），缺省不载入数据
@linkTo: String，点击日历上某日期时执行的操作，缺省不执行任何操作，如需执行操作，请修改 linkToFunc
@target: String，要赋值的input的class名，如 $('.someDiv').setCalendar(lang, date, 'hiddenInput')

日历上某日的属性title=YYYMMDD
*/
var calendarTurnFunc;
var lastCalendar;
$.fn.setCalendar = function(lang, date, target, loadUrl, turnFunc) {
	if (!$(this).is(':visible')) {$(this).show();}
	calendarTurnFunc = turnFunc;
	var targetInput = $(target);
	if (targetInput.length == 0) {
		targetInput = $("." + target);
	};
	iniCalendar(this, lang, date, targetInput, loadUrl);	
};

// build calendar
function iniCalendar(obj, lang, date, target, loadUrl) {
	iniDate(obj, date);
	iniContainer(obj, lang);
	iniFunc(obj, lang, target, loadUrl);
};

// initialize calendar's event
function iniFunc(obj, lang, target, loadUrl) {
	if (obj.year < 1900) return;
	var days = obj.find('a');
	obj.find('.calendar_month .calendar_monthSelect').unbind('change').change(function(){
		//alert(this.value);
		iniCalendar(obj, lang, iniTime(obj.year, this.value, obj.today), target, loadUrl);
	});

	obj.find('.calendar_year .calendar_prev').unbind('click').click(function(){
		iniCalendar(obj, lang, iniTime(obj.year - 1, obj.month + 1, obj.today), target, loadUrl);	
	});
	obj.find('.calendar_year .calendar_next').unbind('click').click(function(){
		iniCalendar(obj, lang, iniTime(obj.year + 1, obj.month + 1, obj.today), target, loadUrl);
	});
	days.unbind('click').click(function(){
		linkToFunc(this, target);
		return false;
	});
	if (loadUrl) {
		var year = obj.year;
		var month = obj.month + 1;
		var postParam = {year: year, month: month}
		$.ajax({
			type: "POST",
			url: loadUrl,
			data: postParam,
			dataType: "json",
			success: function(data){
				if (typeof(setEvents) == "function") {
					setEvents(obj, data);
				};
			},
			error: function(data, status, e){
				//alert(e);
			}
		});
	};
	
	if (typeof(calendarTurnFunc) == "function") {
		calendarTurnFunc.apply(obj);
	};
};

// initialize calendar's container
function iniContainer(obj, lang, linkTo) {
//	if (lastCalendar && lastCalendar != obj) {
//		lastCalendar.html("");
//	}
	
	if (!obj.week) {
		var container = '<div class="calendar"><div class="calendar_close" onclick="closeCanlendar($(this).parent())">X</div><div class="calendar_year"></div><div class="calendar_month"></div><div class="calendar_week"></div><div class="calendar_days"></div><div class="calendar_clear"></div></div>';
		
		$(container).appendTo($(obj));
	};

	//remember last calendar, so we can keep only one instance
//	lastCalendar = $(obj);

	var newCon = $(obj).find('.calendar');
	var years = newCon.find('.calendar_year');
	var months = newCon.find('.calendar_month');
	var weeks = newCon.find('.calendar_week');
	var days = newCon.find('.calendar_days');

	if (!obj.week) {
		obj.week = (lang == 'cn') ? ['一', '二', '三','四', '五', '六','日'] : ['Mon', 'Tue', 'Wed','Thu', 'Fri', 'Sat','Sun'];
		$(obj.week).each(function(){
			$('<var>' + this + '</var>').appendTo(weeks);
		});
		
	} else {
		days.html('');
	};
	
	var yearCode = '<input type="button" value="" class="calendar_prev" /><var>' + obj.year + '</var><input type="button" value="" class="calendar_next" />';
	years.html(yearCode);

	var monthCode = "<select class='calendar_monthSelect'><option value='1'>1</option><option value='2'>2</option><option value='3'>3</option><option value='4'>4</option><option value='5'>5</option><option value='6'>6</option><option value='7'>7</option><option value='8'>8</option><option value='9'>9</option><option value='10'>10</option><option value='11'>11</option><option value='12'>12</option></select>";
	months.html(monthCode);
	months.find('.calendar_monthSelect').val(obj.month + 1);

	
	var m = 1;
	for (var i = 0; i < 42; i++) {
		if (m > obj.endDay || i < obj.startDay) {
			$('<var>&nbsp;</var>').appendTo(days);
		} else {
			var title = iniTime(obj.year, obj.month + 1, m);
			var ifToday = m == obj.today ? 'class="calendar_today"' : '';
			var day = '<a title="' + title + '"' + ifToday + 'href="#">' + m + '</a>';
			if ((i + 2) % 7 == 0 || (i + 1) % 7 == 0) {
				$(day).addClass('calendar_holiday').appendTo(days);
			} else {
				$(day).appendTo(days);
			};
			m++;
		};
	};
};

// initialize date
function iniDate(obj, date) {
	if (date != null) {
		var theDate = date.split('-');
		var year = parseInt(theDate[0], 10);
		var month = parseInt(theDate[1], 10);
		var day = parseInt(theDate[2], 10);
		if (year < 1900) 
			year = (new Date()).getFullYear();	
		if (month < 1) 
			month = (new Date()).getMonth() + 1;
		if (day < 1) 
			day = (new Date()).getDate();
		var now = new Date(year, month - 1, day);
		var date = new Date(year, month - 1, 0);
	} else {
		var now = new Date();
		var date = new Date(now.getFullYear(), now.getMonth(), 0);	
	};

	obj.year = now.getFullYear();
	obj.month = now.getMonth();
	obj.today = now.getDate();
	var feblastDay = (((0 == obj.year % 4) && (0 != obj.year % 100)) || (0 == obj.year % 400)) ? 29 : 28;
	obj.lastDay = [31, feblastDay, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
	obj.startDay = date.getDay();
	obj.endDay = obj.lastDay[obj.month];

};

// close canlendar
function closeCanlendar(obj) {
	obj.hide();
};

// date format
function iniTime(year, month, day) {
	return (year + '-' + (month < 10 ? 0 + month.toString() : month) + '-' + (day < 10 ? 0 + day.toString() : day));
};

// 点击日期的操作
function linkToFunc(obj, target) {
	// obj: 被点击的日期a的DOM对象
	// add your code here or add this Function to your HTML
	if (target.length) {
		target.val(obj.title);
		$(this).parent().siblings('.calendar_close').click();
	};
	//return false;
};

