$(function() {
	// 連携キット、local時はexit
	if ($.LiVE.bdkit && location.protocol=="file:") return;
	
	var $calendar = $(".detail_b", $.LiVE.Elements.PANELS.calendar);
	
	$calendar.each(function() {	
		var $this = $(this),
			$board = $this.find(".board"),
			_id = $this.parent().attr("id"),
			_today = new Date(),
			pref = $.LiVE.panel[_id];
		
			if ( pref.data ) {
				for ( keys in pref.data ) {
					switch(keys) {
						case "width":
							var calW = pref.data[keys];
							if (calW) {
								$board.css("width",calW);
							}
						break;
						case "height":
							var calH = pref.data[keys];
							if (calH) {
								$board.css("height",calH);
							} else {
								calH = $.LiVE.winHeight();
								var $block = $this.find(".block"),
									mtbptb = nopxNum($block.css('marginTop')) + nopxNum($block.css('marginBottom')) + nopxNum($block.css('paddingTop')) + nopxNum($block.css('paddingBottom'));
								$board.height(calH-mtbptb);
							}
						break;
					}
				}
			}
			
			//pxを省いてnumber型で返す関数
			function nopxNum(pxNum) {
				if (typeof(pxNum) == 'undefined') return 0;
				var num = pxNum.replace('px','');
				return parseInt(num);
			}
			
		// dialog
		var dlg = $('<div class="cal-dialog">');
		dlg.append($('<a href="javascript:;" class="cal-desc">詳細</a>'));
		dlg.append($('<a href="javascript:;" class="cal-import">自分のカレンダーに追加</a>'));
		dlg.append($('</div>'));
		dlg.appendTo(this.parentNode);
		
		// for hide dialog
		var hideDialog = function() {
			var tm = setTimeout(function(){
				dlg.hide();
			}, 1500);
			
			$.data(dlg[0], 'tm', tm);
		};
		
		// for cancel 'hide dialog'
		var cancelHideDialog = function() {
			var tm = $.data(dlg[0], 'tm');
			if (typeof(tm) != 'undefined') clearTimeout(tm);
		};
		
		dlg.mouseover(cancelHideDialog).mouseout(hideDialog);
		
		function _tilemaker() {
			var arr = arguments;
			var entry = arr[3];
			var term = _getTermData(entry);
			entry["term"] = term;
			
			var $tile = $("<div/>").addClass("tile").appendTo($board),
				_date = $("<h3/>").addClass("calendar-date").appendTo($tile),
				_title = $("<h2/>").addClass("calendar-title").appendTo($tile),
				_a = $("<a/>").attr({href:"javascript:;"}).appendTo(_title)
				_place = $("<p/>").addClass("calendar-place").appendTo($tile),
				_detail = $("<p/>").addClass("calendar-detail").appendTo($tile);
			
			_a.mouseover(entry, function(evt){
				cancelHideDialog();
				
				var diff = $(window).scrollTop() - $this.parent().offset().top;
				dlg.css({
					top: evt.clientY + diff + 10,
					left: evt.clientX - 140
				});
				
				var ancs = $('a', dlg).unbind();
				ancs.filter('.cal-desc').click(function(){
					var url = "";
					for (var i=0; i<evt.data.link.length; i++) {
						var link = evt.data.link[ i ];
						if (link.type == "text/html") {
							url = link.href;
							break;
						}
					}
					
					if (url!="") window.open(url, 'gcalevent', 'width=700,height=600');
				});
				ancs.filter('.cal-import').click(function(){
					var eventUrl = 'http://www.google.com/calendar/event?action=TEMPLATE';
					
					// dates
					var dates = '';
					if (evt.data.term.isAllDay) {
						var st = $.fullCalendar.formatDate(evt.data.term.startDt, "yyyyMMdd");
						dates = st + '/' + st;
					} else {
						var st = $.fullCalendar.formatDate(evt.data.term.startDt, "yyyyMMdd'T'HHmmss");
						var ed = $.fullCalendar.formatDate(evt.data.term.endDt, "yyyyMMdd'T'HHmmss");
						dates = st + '/' + ed;
					}
					
					eventUrl += '&dates=' + dates;
					
					// title, desc
					eventUrl += '&text=' + evt.data.title.$t + '&details=' + evt.data.content.$t + '&location=' + evt.data['gd$where'][0].valueString;
					
					if (eventUrl.length > 256) {
						eventUrl = eventUrl.substring(0, 256) + "…";
					}
					
					window.open(eventUrl, 'live-cal-win');
				});
				
				dlg.show();
				
			}).mouseout(function(){
				hideDialog();
			});
			
			_date.text(arr[0] + "年 " + arr[1] + "月 " + arr[2] + "日");
			_a.text(arr[3].title.$t);
			_place.html($.LiVE.util.formatLink(arr[3].gd$where[0].valueString));
			_detail.html($.LiVE.util.formatLink(arr[3].content.$t));
			
			// 現在より以前で、当日じゃない
			var dt = arr[4];
			if (_today.getTime() > dt.getTime()
				&& !(_today.getFullYear() == dt.getFullYear() && _today.getMonth() == dt.getMonth() && _today.getDate() == dt.getDate())) {
				$tile.addClass("old");
			}
		}
		
		function _getTermData(e) {
			var startTime = e['gd$when'][0].startTime;
			var allDay = (startTime.indexOf("T") == -1);
			var startDt = $.fullCalendar.parseISO8601(startTime, true);
			var endDt = $.fullCalendar.parseISO8601(e['gd$when'][0].endTime, true);
			
			var term = _formatDate(startDt);
			if (allDay) {
				term += " 終日";
			} else {
				term += " " + _formatTime(startDt) + " 〜 " + _formatDate(endDt) + " " + _formatTime(endDt);
			}
			
			return {
				isAllDay: allDay,
				startDt: startDt,
				endDt: endDt,
				term: term
			};
		}
		
		function _formatDate(dt) {
			return dt.getFullYear() + "年" + (dt.getMonth()+1) + "月" + dt.getDate() + "日";
		}
		
		function _formatTime(dt) {
			return dt.getHours() + ":" + _addZero(dt.getMinutes());
		}
		
		function _formatDesc(src) {
			src = src.replace(/\r\n/g, "<br />");
			src = src.replace(/(\n|\r)/g, "<br />");
			src = src.replace(/((ftp|https?):\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?)/gm,'<a href="$1" target="_blank">$1</a>');
			return src;
		}
		
		function _addZero(src) {
			var buf = ""+src;
			for (var i=0; i<2-buf.length; i++) {
				buf = "0" + buf;
			}
			return buf;
		}
		
		function _nextize() {
			$board.find(".tile[class!='tile old']").eq(0).addClass("next");	//oldクラスのついてない最初の「tile」
		}
		
		function findLink(links) {
			for (var i=0; i<links.length; i++) {
				var link = links[i];
				if (link.type == "text/html") return link.href;
			}
			return "";
		}
		
		_today.setHours(0);
		_today.setMinutes(0);
		_today.setSeconds(0);
		
		var toMonth = new Date(_today.getTime());
		toMonth.setMonth(toMonth.getMonth()+11);	// last 12months
		toMonth.setDate($.LiVE.dateutil.maxDays(toMonth));
		
		var startMin = $.fullCalendar.formatDate(_today, "u");
		var startMax = $.fullCalendar.formatDate(toMonth, "u");
		
		$.ajax({
			type: "GET",
			dataType: "jsonp",
			url: pref.data.url.replace(/\/basic$/, "/full") + "?alt=json-in-script&&orderby=starttime&&sortorder=ascend&callback=?",
			data: {
				"start-min": startMin,
				"start-max": startMax,
				"singleevents": true,
				"max-results": 9999
			},
			cache: false,
			success: function(data) {
				$.each(data.feed.entry, function(i, e) {
					var dt = $.fullCalendar.parseISO8601(e['gd$when'][0]['startTime'], true);
					_tilemaker(dt.getFullYear(), dt.getMonth() + 1, dt.getDate(), e, dt);
				});
				_nextize();
				
				if ($.LiVE.mobile.check) {
					$board.height($board[0].scrollHeight);
				}
			}
		});
		
	});
});