(function($) { 
   
	function calendarWidget(el, params) { 
		
		var now   = new Date();
		var thismonth = now.getMonth();
		var thisyear  = now.getYear();
		if (thisyear < 2000) { thisyear += 1900; }

		var opts = {
			month: thismonth,
			year: thisyear
		};
		
		$.extend(opts, params);
		
		var monthNames = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
		var dayNames = ['月', '火', '水', '木', '金', '土', '日'];
		month = i = parseInt(opts.month);
		year = parseInt(opts.year);
		var m = 0;
		var table = '';
		
			// next month
			if (month == 11) {
				var next_month = '<a href="?month=' + 1 + '&amp;year=' + (year + 1) + '">&gt;&gt;次月</a>';
			} else {
				var next_month = '<a href="?month=' + (month + 2) + '&amp;year=' + (year) + '">&gt;&gt;次月</a>';
			}
				
			// previous month
			if (month == 0) {
				var prev_month = '<a href="?month=' + 12 + '&amp;year=' + (year - 1) + '">&lt;&lt;今月</a>';
			} else {
				var prev_month = '<a href="?month=' + (month) + '&amp;year=' + (year) + '">&lt;&lt;今月</a>';
			}		
				
			table += ('<div id="cal-u-wrap" class="clx"><p id="current-month">'+monthNames[month]+' '+year+'</p>');
			if(month===thismonth){
			table += ('<p class="nav-next">'+ next_month +'</p>');
			}else{
			table += ('<p class="nav-prev">'+ prev_month +'</p>');
			}
			table += ('</div><table class="calendar-month" ' +'id="calendar-month'+i+' " cellspacing="0">');	
		
			table += '<tr>';
			
			for (d=0; d<7; d++) {
				if(d===6){
					table += '<th class="weekday last-c">' + dayNames[d] + '</th>';
				}else{
					table += '<th class="weekday">' + dayNames[d] + '</th>';
				}
			}
			
			table += '</tr>';
		
			var days = getDaysInMonth(month,year);
			var firstDayDate=new Date(year,month,1);
			var firstDay=firstDayDate.getDay()
			var firstDay02=firstDayDate.getDay()
			if(firstDay===0){
				firstDay=6;
			}else{
				firstDay=firstDay-1;
			}
			
			var prev_m = month == 0 ? 11 : month-1;
			var prev_y = prev_m == 11 ? year - 1 : year;
			
			var tMonth = month+1;
			var pMonth = month;
			var nMonth = month+2;
			if(tMonth<10){
				tMonth = '0' + tMonth;
			}
			
			if(pMonth===0){
				pMonth=12;
			}
			if(pMonth<10){
				pMonth = '0' + pMonth;
			}
			
			if(nMonth===13){
				nMonth=1;
			}
			if(nMonth<10){
				nMonth = '0' + nMonth;
			}
	
			var i = 0;
			var toTaldays = firstDay+days;
			var nextMonthDay = 7-(toTaldays%7);
			if(nextMonthDay!==7){
				toTaldays02=toTaldays+nextMonthDay;
			}else{
				toTaldays02=toTaldays;
			}
            for (j=0;j<toTaldays02;j++){
			  
              if (j<firstDay){
                table += ('<td class="other-month">&nbsp;</td>');			 
			  }else if (j>=toTaldays){
                table += ('<td class="other-month">&nbsp;</td>');			 
				}
				
				else{
								var day = j-firstDay+1;
								if(day<10){
									day = '0' + day;
								}
                table += ('<td class="current-month day'+ tMonth + day+'"><span class="day">'+(j-firstDay+1)+'</span></td>');
              }
              if (j%7==6)  table += ('</tr>');
            }

            table += ('</table>');

			el.html(table);
			
			// 営業・サービス工場定休日、	法人営業定休日、土日の設定
			$('.calendar-month tr').each(function(){
				$('td',this).each(function(i){
					if(i===1){
						if(!$(this).hasClass('other-month')){
							$(this).addClass('r-hol01');
						}
					}
					if(i===6){
						if(!$(this).hasClass('other-month')){
							$(this).addClass('sun');
						}else{
							$(this).addClass('last-sun');
						}
					}
					if(i===5){
						if(!$(this).hasClass('other-month')){
							$(this).addClass('sat');
						}
					}
				});

		});

			// 第2・4土曜の計算
			if(firstDay02 === 6){
				secSat = '.day' + tMonth + '08';
				forthSat = '.day' +  tMonth + '22';
			}else{
				secSat = 14-firstDay02;
				forthSat = '.day' +  tMonth + eval(secSat+14);
				if(secSat<10){
					secSat = '.day' + tMonth + '0' + secSat;
				}else{
					secSat = '.day' + tMonth + secSat;
				}
			}
			$(secSat).addClass('r-hol02');
			$(forthSat).addClass('r-hol02');

		var defaultHol = new Array("0101","0114","0211","0321","0429","0503","0504","0505","0721","0921","0923","1014","1103","1123","1223");

		// 成人の日/体育の日(第2月曜日)の計算
		if((month == 0 || month == 9)){
			if(firstDay02 <= 1){
				happyMon = 7 + (2 - firstDay02);
			}else{
				happyMon = 14 - (firstDay02 - 2);
			}
			if(happyMon < 10){
				happyMon = "0" + happyMon;
			}
			if(month == 0){
				defaultHol[1] = "01" + happyMon;
			}
			else{
				defaultHol[11] = "10" + happyMon;
			}
		}
		// 海の日/敬老の日(第3月曜日)の計算
		if((month == 6 || month == 8)){
			if(firstDay02 <= 1){
				happyMon = 14 + (2 - firstDay02);
			}else{
				happyMon = 21 - (firstDay02 - 2);
			}
			if(month == 6){
				defaultHol[8] = "07" + happyMon;
			}
			else{
				defaultHol[9] = "09" + happyMon;
			}
		}

		for (var i = 0; i < setHol.length; i++) {
			if(setHol[i]!==undefined){
				defaultHol[i]= setHol[i];
			}
		}

		//国民の祝日と国民の祝日に挟まれた日は休み
		//この状況が発生するのは2011年現在　9月の敬老の日と秋分の日の間のみ
		if((defaultHol[10].substring(2,4)-defaultHol[9].substring(2,4))===2){
			var addHol = eval(defaultHol[9].substring(2,4))+1;
			addHol='.day09'+ addHol;
			$(addHol).addClass('holiday');
		}
		
		//臨時休業日設定
		if(setHol02.length!==0){
			for (var i = 0; i < setHol02.length; i++) {
				var hol = '.day'+ setHol02[i];
				if($(hol).size!==0){
					$(hol).addClass('ir-hol01');
				}
			}
		}
		
		//祝日設定
		for (var i = 0; i < defaultHol.length; i++) {
			var hol = '.day'+ defaultHol[i];
			if($(hol).size!==0){
				if(!$(hol).hasClass('sun') && !$(hol).hasClass('holiday')){
					$(hol).addClass('holiday');
				}else{
					var d = hol.substring(6,8);
					var m = hol.substring(4,6);
					if(d<10){
						d=eval(d.split('0')[1])+1;
						if(d<10){
							hol='.day'+m+'0'+d;
						}else{
							hol='.day'+m+d; 
						}
					}else{
						d=eval(d)+1;
						hol='.day'+m+d;
					}
					$(hol).addClass('holiday');
				}
			}
		}
		$('.nav-next a,.nav-prev a').click(calChange);
	}

	function getDaysInMonth(month,year)  {
		var daysInMonth=[31,28,31,30,31,30,31,31,30,31,30,31];
		if ((month==1)&&(year%4==0)&&((year%100!=0)||(year%400==0))){
		  return 29;
		}else{
		  return daysInMonth[month];
		}
	}
	
	// jQuery plugin initialisation
	$.fn.calendarWidget = function(params) {    
		calendarWidget(this, params);		
		return this; 
	}; 
	
})(jQuery);

$(function(){
	$("#calendar").calendarWidget();
	eventSet();
});

var calChange = function(){
	var showObj = $(this).attr('href');
	var thismonth = showObj.split('month=')[1].split('&')[0]-1;
	var thisyear  = showObj.split('month=')[1].split('&year=')[1];
	if (thisyear < 2000) { thisyear += 1900; }
	$("#calendar").calendarWidget({
		month: thismonth,
		year: thisyear
	});
	eventSet();
	return false;
}

var eventSet = function(){
	/* カレンダーイベント読み込み */
	/* ----------------------------------------------------- */
	$.ajaxSetup({
			cache: false
	});	
	$('#events-list').load("/setting/cal_event.html",
		function(){
			$('#events-list').find('p').each(function(){
				var day = '.day' + $(this).attr('class').split('event')[1];
				if($(day).size()!==0){
					$(day).addClass('has-event');
					var html ="";
					html += '<div><p>' + $(this).html() + '</p></div>' + $(day).html() + '<span class="e-icon">&nbsp;</span>';
					$(day).html(html);
				}
				$(this).remove();
			});
			
			$('.has-event').each(function (){
				// options
				var distance = 0;
				var time = 250;
				var hideDelay = 250;
				var hideDelayTimer = null;
		
				// tracker
				var beingShown = false;
				var shown = false;
		
				var trigger = $(this);
				var popup = $(this).find('p').css('opacity', 0);
		
				// 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
						var posAdj = -$(this).height()-10;
						
						if($(this).find('p').size()===0){
							var posAdj = -$(this).height()-10;
						}else{
							posAdj = -$(this).find('p').height()-10;
						}
						// reset position of popup box
						popup.css({
							top: posAdj,
							left: -76,
							display: 'block' // brings the popup back in to view
						})
		
						// (we're using chaining on the popup) now animate it's opacity and position
						.animate({
							top: '+=' + distance + 'px',
							opacity: 0.8
						}, time, 'swing', function() {
							// once the animation is complete, set the tracker variables
							beingShown = false;
							shown = true;
						});
					}
				}).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({
							top: '-=' + 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);
				});
			});
		}
	);
}
