/*
 * Catan Script
 * Creator: Catan Association
 *
 **/

var Today = new Date();
var placeOrder = ["北海道","青森県","岩手県","宮城県","秋田県","山形県","福島県","茨城県","栃木県","群馬県","埼玉県","千葉県","東京都","神奈川県","新潟県","富山県","石川県","福井県","山梨県","長野県","岐阜県","静岡県","愛知県","三重県","滋賀県","京都府","大阪府","兵庫県","奈良県","和歌山県","鳥取県","島根県","岡山県","広島県","山口県","徳島県","香川県","愛媛県","高知県","福岡県","佐賀県","長崎県","熊本県","大分県","宮崎県","鹿児島県","沖縄県","ドイツ","アメリカ","中国","台湾","香港","上海","タイ","韓国"];
var prefs = {};

jQuery(document).ready(function()
{
	$('a.gotoTop').click(function(){
		$('html, body').animate({scrollTop:0}, 'slow');
	});

	if($.support.opacity){
		doOval();
	}

	if(isIE(7) || isIE(8)){
		$('.r2s, .r8, #content, .oval, .thumbnail').each(function() { try { PIE.attach(this);} catch(e){}   });
	}

}) /*ready*/

function isIE(version)
{
	if (/MSIE (\d+\.\d+);/.test(navigator.userAgent))
	{ 
		var ieversion=new Number(RegExp.$1);
		if (version == ieversion) return true;
	}
	return false;
}


function showLoading(targetId){
	$(targetId+" > div.status").html('<span class="loading">読み込み中...</span>');
	$(targetId+" > div.status>span").fadeIn();
}
function hideLoading(targetId){
	$(targetId+" > div.status>span").fadeOut().slideUp();
}
function removeLoading(targetId){
	$(targetId+" > div.status>span").fadeOut("fast",function(){ $(targetId+" > div.status").slideUp();} );
}
function showNotice(targetId, notice){
		$(targetId+" > div.status").html('<span class="notice">' + notice + '</span>');
		$(targetId+" > div.status>span").fadeIn().delay(1000).fadeOut("fast",function(){ $(targetId+" > div.status").slideUp();} );
}
function showFixedMessage(targetId, notice){
		$(targetId+" > div.status").html('<span class="notice">' + notice + '</span>');
		$(targetId+" > div.status>span").fadeIn();
}

function showLoadingError(targetId){
	$(targetId+" > div.status").empty().html('<span class="error">エラー：イベント情報を読み込めませんでした</span>');
	$(targetId+" > div.status>span").fadeIn();
}
function showLoadMore(targetId)
{
	var cnt = countAry(SCH);
	$(targetId+" > div.status").empty().html('<span class="load-more"><a href="javascript:void(0);" onclick="catanAjax(\''+targetId+'\',{\'offset\':'+cnt+'})">さらに読み込む</a></span>');
	$(targetId+" > div.status>span").show();
}

function catanCommunityAjax(targetMapId, targetId, opt)
{
	if ($(targetId).children().length <=0){
		$(targetId).append("<ul></ul><div class='status'></div>");
	}

	if (!opt) opt = {};

	showLoading(targetId);

	$.post(
		PLUGIN_DIR + "catanAjax.php",
		{"tp":"community"} ,
		function(data, status){
			if (status != "success"){
				showLoadingError(targetId);
				return;
			}
			eval(data);
			showGooglePlaceMap(targetMapId);
			createPlaceList(targetId, "community", {col:2, width:300, layout:"complex"});
		}
	);
}

function catanShopAjax(targetMapId, targetId, opt)
{
	if ($(targetId).children().length <=0){
		$(targetId).append("<ul></ul><div class='status'></div>");
	}

	if (!opt) opt = {};

	showLoading(targetId);

	$.post(
		PLUGIN_DIR + "catanAjax.php",
		{"tp":"places"} ,
		function(data, status){
			if (status != "success"){
				showLoadingError(targetId);
				return;
			}
			eval(data);
			showGooglePlaceMap(targetMapId);
			createPlaceList(targetId, "retail", {col:3, width:280});
		}
	);
}

function catanProductAjax(postId)
{
	var targetId = "#product-description";
	var targetFaqId = "#product-faq";
	
	$(targetId).append("<div class='status'></div>");
	showLoading(targetId);

	$.post(
		PLUGIN_DIR + "catanAjax.php",
		{"tp":"product", "since_id":postId},
		function(data, status){
			if (status != "success"){
				showLoadingError(targetId);
				return;
			}
			eval(data); // product
			removeLoading(targetId);

			$(targetId).html(
				"<header>" + product.title + "</header>" + 
				"<p>" + product.content + "</p>"
			);

			$(targetFaqId).html("<header>関連する質問</header>");
			for (var i=0;i<product.faqs.length;i++){
				$(targetFaqId).append(
					'<article id="faq-'+product.faqs[i].id+'"><a class="faq" href="javascript:void(0);" onclick="catanFaqAjax('+product.faqs[i].id+');">Ｑ. ' + product.faqs[i].title + '</a></article>'
				);
			}
		}
	);
}


function catanFaqAjax(postId)
{
	var targetId = "#faq-" + postId;
	
	$(targetId).append("<div class='status'></div>");
	showLoading(targetId);

	$.post(
		PLUGIN_DIR + "catanAjax.php",
		{"tp":"faq", "since_id":postId},
		function(data, status){
			if (status != "success"){
				showLoadingError(targetId);
				return;
			}
			eval(data); // faq
			removeLoading(targetId);
			$(targetId).append("<p id='answer-"+faq.id+"' style='display:none;'></p>");
			$("#answer-"+faq.id).append( faq.content ).delay(300).slideDown();
		}
	);
}


function showLangs(seq, opt)
{
	var ary = seq.split(",");
	var hash = {};
	var s = "";
	for (var i=0;i<ary.length;i++){
		hash[ary[i]] = true;
	}
	if (hash["jp"]) s += '<img src="' + THEME_DIR + '/images/icon/jp_20x20.png" title="日本語版">';
	if (hash["attach"]) s += '<img src="' + THEME_DIR + '/images/icon/wayaku_37x20.png" title="和訳付きの海外版">';
	if (hash["de"]) s += '<img src="' + THEME_DIR + '/images/icon/germany_20x20.png" title="ドイツ語版">';
	if (hash["en"]) s += '<img src="' + THEME_DIR + '/images/icon/us_20x20.png" title="英語版">';
	if (hash["etc"]) s += '<img src="' + THEME_DIR + '/images/icon/globe_20x20.png" title="その他の海外版">';

	document.writeln(s);

}

function createPlaceList(targetId, sceneTag , opt)
{
	if (!opt) opt = {};
	var columnCount = opt.col ? opt.col : 3 ;
	var columnWidth = opt.width ? opt.width : 213;
	var layout = opt.layout ? opt.layout : "default";
	var allCount = 0;

	for (var pid in PLACES){
		if (PLACES[pid][sceneTag] && PLACES[pid][sceneTag] == true){
			var p = PLACES[pid]['prefecture'];
			if (!prefs[p]) {
				prefs[p] = [];
				allCount++;
			}
			prefs[p].push(pid);
			allCount++;
		}
	}

	/** GENERATE HTML **/
	var maxCount = parseInt(allCount / columnCount, 10);
	var countdown = maxCount;

	var prefix = "<section style='width:"+columnWidth+"px'>";
	var suffix = "</section>";
	var html = prefix;

	// CUSTOM LAYOUT 1 (complex list)
	if (layout == "complex"){
		for (var i=0;i<placeOrder.length;i++){
			if (prefs[placeOrder[i]]){
				html += "<h5>"+placeOrder[i]+"("+prefs[placeOrder[i]].length+")</h5>";
				countdown--; if (countdown<=0){ html += suffix + prefix; countdown = maxCount;}
				for (var j=0; j<prefs[placeOrder[i]].length; j++){
					var pid = prefs[placeOrder[i]][j];
					html += "<p><a href='javascript:void(0);' onclick='showPlaceDescription("+pid+");return false;'>"+PLACES[pid]['city'] + " - " + PLACES[pid]['title']+"</a>";
					if (PLACES[pid]['link'].length>10){
						html += "&nbsp;<a href='"+PLACES[pid]['link']+"' target='_blank'><i>[リンク]</i></a>";
					}
					html += "</p>";
					countdown--; if (countdown<=0){ html += suffix + prefix; countdown = maxCount;}
				}
			}
		}
	} else {
	// DEFAULT LAYOUT (simple list)
		for (var i=0;i<placeOrder.length;i++){
			if (prefs[placeOrder[i]]){
				html += "<h5>"+placeOrder[i]+"("+prefs[placeOrder[i]].length+")</h5>";
				countdown--; if (countdown<=0){ html += suffix + prefix; countdown = maxCount;}
				for (var j=0; j<prefs[placeOrder[i]].length; j++){
					var pid = prefs[placeOrder[i]][j];
					html += "<p><a href='javascript:void(0);' onclick='showPlaceInfoWindow("+pid+");return false;'>・"+PLACES[pid]['title']+"</a></p>";
					countdown--; if (countdown<=0){ html += suffix + prefix; countdown = maxCount;}
				}
			}
		}
	}

	// finally
	if (countdown != maxCount) html += suffix;
	$("#"+targetId).html(html);

}

function showPlaceDescription(pid)
{	
	var hp = "";
	var lnk = "";

	if (PLACES[pid]['places'].length>0){
		for (var i=0; i<PLACES[pid]['places'].length; i++){
			hp += "<li><a href='javascript:void(0);' onclick='showPlaceInfoWindow("+PLACES[pid]['places'][i][0]+");return false;'>"+PLACES[pid]['places'][i][1]+"</a></li>";
		}
		hp = "<header>よく使う場所</header><ul>" + hp + "</ul>";
	}

	if (PLACES[pid]['link'].length>0){
		lnk = "<span class='aside'><a href='"+PLACES[pid]['link']+"' target='_blank'>[リンク]</a></span>"
	}

	$("#place-description").html(
		"<header>" + PLACES[pid]['title'] + lnk + "</header>" +
		"<article>" +
		"<p>" + decodeURI(PLACES[pid]['comment']) + "</p></article>" +
		hp
	);

}


function catanEventAjax(targetId, opt)
{
	if ($(targetId).children().length <=0){
		$(targetId).append("<ul></ul><div class='status'></div>");
	}

	if (!opt) opt = {};

	showLoading(targetId);

	$.post(
		PLUGIN_DIR + "catanAjax.php",
		opt,
		function(data, status){
			if (status != "success"){
				showLoadingError(targetId);
				return;
			}
			var expandFlg = (countAry(SCH) == 0 && opt.expand) ? true : false;
			var r = opt.r ? opt.r : "future";
			eval(data);

			if (data.length == 0){
				if (countAry(SCH)==0){
					showFixedMessage(targetId,"現在登録されているイベント情報はありません");
				} else {
					showNotice(targetId,"これ以降のデータは登録されていません");
				}
				return;
			}

			var newllyAddedCount = refreshScheduleList(targetId, getSortedScheduleId(r), expandFlg);
			if (newllyAddedCount == 0){
				showLoadMore(targetId);
			} else {
				showNotice(targetId,"これ以降のデータは登録されていません");
			}
		}
	);


}

function getMapLink(eventId)
{
		//var q = SCH[eventId]['place']['search'] == 1 ? SCH[eventId]['place']['formatted_address'] : SCH[eventId]['place']['title'];
		var q = SCH[eventId]['place']['search'] == 1 ? "" : SCH[eventId]['place']['title'];

		var googleMapLink = 'http://maps.google.co.jp/maps?' +
				'hl=ja' + 
				'&q=loc:'+SCH[eventId]['place']['latlng']+'+'+encodeURI(q) +
				'&ll='+SCH[eventId]['place']['latlng']+
				'&='+SCH[eventId]['place']['latlng']+
				'&ie=UTF8' + 
				'&ct=clnk' + 
				'&cd=1' + 
				'&geocode=' + 
				'&split=0' + 
				'&z=16';
		var placeLink =  SCH[eventId]['place']['link'].length > 10 ? 
			'<a href="'+SCH[eventId]['place']['link']+'" target="_blank">' + SCH[eventId]['place']['title'] + '</a>' : SCH[eventId]['place']['title'];
		placeLink += '<a href="'+ googleMapLink +'" title="Googleマップで場所を確認" target="_blank">[<b>地図</b>]</a>';
		return placeLink;	
}


function refreshScheduleList(targetId, ids, expandFlg)
{
	var newllyAddedCount = 0;
	
	for (var i=0; i<ids.length;i++)
	{
		var eventId = ids[i];
		if ($("#post-" + eventId).length == 0)
		{
			var html = createScheduleListHtml(targetId, eventId);
			(i==0) ? $(targetId + ">ul").prepend(html) : $("#post-" + ids[i-1]).after(html);
			newllyAddedCount++;
		}
	}

	$('a[href^=#]').unbind("click").click(function() {
		showEventDescription(this.hash);
		return false;
	});

	if (expandFlg) {
		setTimeout(function(){showEventDescription("#post-"+ids[0]); }, 300);
	}

	return newllyAddedCount;
}	

function formatYMD(ymd){
	var y = ymd.substr(0,4);
	var m = parseInt(ymd.substr(4,2),10);
	var d = parseInt(ymd.substr(6,2),10);
	var _ymd = y+"/"+m+"/"+d;
	return ((y == (new Date()).getFullYear()) ? "": y+'年') + m + '月' + d + '日('+ getWeekStr(_ymd) +')';
}

function getComingSoon(ymd, eventTypeStr)
{
	// DATE
	var y = ymd.substr(0,4);
	var m = parseInt(ymd.substr(4,2),10);
	var d = parseInt(ymd.substr(6,2),10);
	var ymd = y+"/"+m+"/"+d;

	// DAY OFFSET
	var thisDay = new Date(ymd);
	var offsetDay = Math.ceil((thisDay - Today)/(60*60*24*1000));
	var attention = "";
	if (offsetDay < -1) { attention = '<p class="past-event event-attention"><span>この'+eventTypeStr+'は終了しました</span></p>'; }
	else if (offsetDay == -1) { attention = '<p class="yesterday-event event-attention"><span>この'+eventTypeStr+'は昨日開催されました</span></p>'; }
	else if (offsetDay == 0) { attention = '<p class="today-event event-attention"><span>この'+eventTypeStr+'は本日開催です！</span></p>'; }
	else if (offsetDay == 1) { attention = '<p class="tomorrow-event event-attention"><span>この'+eventTypeStr+'は明日の開催です</span></p>'; }
	else if (offsetDay == 2) { attention = '<p class="upcoming-event event-attention"><span>この'+eventTypeStr+'は明後日の開催です</span></p>'; }
	else if (offsetDay == 3) { attention = '<p class="upcoming-event event-attention"><span>この'+eventTypeStr+'は３日後の開催です</span></p>'; }
	else if (offsetDay < 7) { attention = '<p class="upcoming-event event-attention"><span>この'+eventTypeStr+'はもうすぐ開催です</span></p>'; }
	document.writeln('<div style="margin-top:4px;margin-bottom:4px;">'+attention+'</div>');

}

function createScheduleListHtml(targetId, eventId)
{
		// EYECATCH
		var eyecatch = SCH[eventId]['eyecatch'];
		if (eyecatch.length < 10) eyecatch = THEME_DIR + "images/icon/no-image_44x44.png";
		eyecatch = '<img src="' + eyecatch + '" title="'+SCH[eventId]['title']+'">';

		// DATE
		var y = SCH[eventId]['ymd'].substr(0,4);
		var m = parseInt(SCH[eventId]['ymd'].substr(4,2),10);
		var d = parseInt(SCH[eventId]['ymd'].substr(6,2),10);
		var ymd = y+"/"+m+"/"+d;

		// DAY OFFSET
		var thisDay = new Date(ymd);
		var offsetDay = Math.ceil((thisDay - Today)/(60*60*24*1000));
		var attention = "";
		if (offsetDay < -1) { attention = '<p class="past-event event-attention"><span>この'+SCH[eventId]['pattern']+'は終了しました</span></p>'; }
		else if (offsetDay == -1) { attention = '<p class="yesterday-event event-attention"><span>この'+SCH[eventId]['pattern']+'は昨日開催されました</span></p>'; }
		else if (offsetDay == 0) { attention = '<p class="today-event event-attention"><span>この'+SCH[eventId]['pattern']+'は本日開催です！</span></p>'; }
		else if (offsetDay == 1) { attention = '<p class="tomorrow-event event-attention"><span>この'+SCH[eventId]['pattern']+'は明日の開催です</span></p>'; }
		else if (offsetDay == 2) { attention = '<p class="upcoming-event event-attention"><span>この'+SCH[eventId]['pattern']+'は明後日の開催です</span></p>'; }
		else if (offsetDay == 3) { attention = '<p class="upcoming-event event-attention"><span>この'+SCH[eventId]['pattern']+'は３日後の開催です</span></p>'; }
		else if (offsetDay < 7) { attention = '<p class="upcoming-event event-attention"><span>この'+SCH[eventId]['pattern']+'はもうすぐ開催です</span></p>'; }

		

		return (
			'<li id="post-'+eventId+'" class="collapse">' +
				'<table>' +
				'<tr>' +
				'<td class="info">' +
					'<table><tr><td class="eyecatch">' + eyecatch + '<span>'+SCH[eventId]['pattern']+'</span></td>' +
					'<td class="date-and-place">' +
						'<p>' +
							  '<span class="ymd">' + ((y == (new Date()).getFullYear()) ? "": y+'年') + m + '月' + d + '日('+ getWeekStr(ymd) +')' + '</span><br>' +
								SCH[eventId]['time'] + 
						'</p>' +
						'<p>' + 
							SCH[eventId]['place']['prefecture']+'・'+SCH[eventId]['place']['city']+'<br>' +
							getMapLink(eventId) + 
						'</p>' +
					'</td></tr></table>' +
				'</td>' +
				'<td class="summary">' +
					'<h3>' + SCH[eventId]['title'] + '</h3>' +
					attention + 
					'<p class="catch">'+SCH[eventId]['catch']+' ...<a class="more" href="#post-' + eventId + '"><b>もっと詳しく</b></a></p>' +
				'</td>' +
				'</tr>' +
				'<tr><td colspan="2" id="eventform-'+eventId+'"></td></tr>' + 
				'</table>' +
			'</li>'
		);

}

function showEventDescription(hash_targetId)
{
	$(hash_targetId + " a.more").hide();

	var eventId = hash_targetId.split("-")[1];

	showGoogleMiniMap(hash_targetId.split("#")[1]);

	// ADDRESS
	var ary = SCH[eventId]['place']['formatted_address'].split("日本,");
	var adr = $.trim(ary[ary.length-1]);

	// PHOTOS
	var photoStr = "";
	var pAry = SCH[eventId]['place']['photo'];
	var width_height= pAry.length == 3 ? "width=90 height=90" : "width=120 height=120";
	for (var i=0; i<pAry.length; i++){
		photoStr += '<a href="'+pAry[i]['original']+'" rel="lightbox['+ eventId +']" class="cboxElement">' +
			'<img alt="" src="'+pAry[i]['thumbnail']+'" title="'+pAry[i]['title']+'" '+width_height+' class="size-thumbnail wp-image-'+pAry[i]['pid']+' alignnone">' +
			'</a>';
	}

	$(hash_targetId + " .summary").append(
		'<p class="contents">'+ SCH[eventId]['contents'] + '</p>' +
		'<table>' + 
			'<tr><td class="header" nowrap>参加方法</td><td class="data">' + SCH[eventId]['contact'] + '</td>' +
			'<tr><td class="header">参加費</td><td class="data">' + SCH[eventId]['charge'] + '</td></tr>' +
			'<tr><td class="header">主　催</td><td class="data">' + SCH[eventId]['host'] + '</td></tr>' +
			'<tr><td class="header">会　場</td>' +
				'<td class="data">' + getMapLink(eventId) + '</a>' + 
				'<div>' +
					'最寄り：'+ SCH[eventId]['place']['closest'] + '<br>' +
					'住　所：'+ adr + '<br>' +
					'備　考：'+ decodeURI(SCH[eventId]['place']['comment']) +
				'</div>' +
			'</td></tr>' +
		'</table>' + 
		photoStr
	);

	if (SCH[eventId]['form'].length>0){
		$("#eventform-"+eventId).html( SCH[eventId]['form'].replace(/<br>/ig,'').replace(/&quot;/ig,'"').replace(/&gt;/ig,">").replace(/&lt;/ig,"<") );
	}

	$("a[rel*=lightbox]").colorbox({opacity:0.8,current:"　 {current} / {total}",previous:"前へ",next:"次へ",close:"閉じる"});


}



var map;
function showGooglePlaceMap(targetMapId)
{
	var geocoder;
	geocoder = new google.maps.Geocoder();
	var latlng = new google.maps.LatLng(37,135); 

	var myOptions = {
		zoom: 5,
		center: latlng,
		disableDefaultUI: true,
		navigationControl: true,
		navigationControlOptions : google.maps.NavigationControlStyle.SMALL,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	}
	map = new google.maps.Map(document.getElementById(targetMapId), myOptions)
	map.setCenter(latlng);

	for (var pid in PLACES){
		var ary = PLACES[pid]['latlng'].split(",");

		PLACES[pid]['marker'] = new google.maps.Marker({
			map: map, 
			position: new google.maps.LatLng(ary[0], ary[1]),
			title: PLACES[pid]['title'],
			pid : pid
		});
		
		google.maps.event.addListener(PLACES[pid]['marker'], 'click', function()
		{
			showPlaceInfoWindow(this.pid);
		});
	}
}

function showPlaceInfoWindow(pid)
{
	if (!PLACES[pid])
	{
		PLACES[pid] = true;
		$.post(
			PLUGIN_DIR + "catanAjax.php",
			{"tp":"place", "id":pid},
			function(data, status){
				if (status != "success"){
					return;
				}
				eval(data); // product
				showPlaceInfoWindow(pid);
			}
		);
		return;
	}

	var ary = PLACES[pid]['latlng'].split(",");
	var latlng = new google.maps.LatLng(ary[0], ary[1]);

	map.setCenter(latlng);
	map.setZoom(16);

	// ADDRESS
	var ary = PLACES[pid]['formatted_address'].split("日本,");
	var adr = $.trim(ary[ary.length-1]);

	// GOOGLE MAP
	var q = PLACES[pid]['search'] == 1 ? "" : PLACES[pid]['title'];
	var googleMapLink = 'http://maps.google.co.jp/maps?' +
		'hl=ja' + 
		'&q=loc:'+PLACES[pid]['latlng']+'+'+q + 
		'&ll='+PLACES[pid]['latlng']+
		'&='+PLACES[pid]['latlng']+
		'&ie=UTF8' + 
		'&ct=clnk' + 
		'&cd=1' + 
		'&geocode=' + 
		'&split=0' + 
		'&z=16';

	var infowindow = new google.maps.InfoWindow({
		content: 
				'<div style=line-height:1.3em;><b>' + 
				(PLACES[pid]['link'].length < 10 ? 
					PLACES[pid]['title']:
					'<a title="ショップのホームページへ" href="'+PLACES[pid]['link']+'" target=_blank>'+PLACES[pid]['title']+'</a>'
				) + 
				'</b></div>' + 
				'<div>' + adr + '</div>' + 
				'<div>' + PLACES[pid]['phone'] + '</div>' + 
				'<div><a href="' + googleMapLink + '" target=_blank>[大きな地図で見る]</a></div>',
		position: latlng
	});
	infowindow.open(map, PLACES[pid]['marker']);
	

}



function showGoogleMiniMap(targetId)
{
	var map;
	var geocoder;
	var eventId = targetId.split("-")[1];
	var targetMapId = targetId+'-map';
	var a= SCH[eventId]['place']['latlng'].split(",");

	$("#"+ targetId + " td.info").append('<div class="map-mini" id="'+ targetMapId + '"></div>');

	geocoder = new google.maps.Geocoder();

	var latlng = new google.maps.LatLng(a[0],a[1]);

	var myOptions = {
		zoom: 16,
		center: latlng,
		disableDefaultUI: true,
		navigationControl: true,
		navigationControlOptions : google.maps.NavigationControlStyle.SMALL,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	}
	map = new google.maps.Map(document.getElementById(targetMapId), myOptions)

	map.setCenter(latlng);

	var marker = new google.maps.Marker({
			map: map, 
			position: latlng
	});

}


function getSortedScheduleId(r)
{
	var ary = new Array();

	for (var entry_id in SCH){
		ary.push({'entry_id':entry_id, 'ymd':SCH[entry_id]['ymd']});
	}

	if (r == "all"){
		return (Ary.getAryOf(Ary.arsort(ary,"ymd"),"entry_id"));
	} else {
		return (Ary.getAryOf(Ary.asort(ary,"ymd"),"entry_id"));
	}

}

function doOval() {
	/* firefox oval image */
	// by http://html-coding.co.jp/knowhow/tips/000276/
	$(".oval, .oval-8, .cfg_img").load(function() {
		$(this).wrap(function(){
			return '<span class="' + $(this).attr('class') + '" style="background:url(' + $(this).attr('src') + ') no-repeat center center; width: ' + $(this).width() + 'px; height: ' + $(this).height() + 'px;" />';
		});
		$(this).css("opacity","0");
	});
}


function twitterSimpleWidget()
{
	var fileref = document.createElement('script');
	fileref.setAttribute("type","text/javascript");
	fileref.setAttribute("src", "http://api.twitter.com/1/statuses/user_timeline/catan_japan.json?callback=twitterCallback2&count=20&include_rts=true");
	document.getElementsByTagName("head")[0].appendChild(fileref);

	/* search.twitter.com での from:を使った検索 ← アンダースコアがあると検索できないので、使用しないこと。。。 */

}

function twitterCallback2(twitters) 
{
  var statusHTML = [];
  for (var i=0; i<twitters.length; i++)
  {
    var username = twitters[i].user.screen_name;
    var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
      return '<a href="'+url+'">'+url+'</a>';
    }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
      return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
    });

		if (twitters[i].retweeted_status){
	    statusHTML.push(
	    	'<li>' +
				'<img src="'+twitters[i].retweeted_status.user.profile_image_url+'">' +
				'<span class="retweet">&nbsp;&nbsp;&nbsp;&nbsp;</span>' +
    		'<b><a href="http://twitter.com/' + twitters[i].retweeted_status.user.screen_name + '" target="_blank">' + 
    		twitters[i].retweeted_status.user.screen_name + '</a></b>' +
    		' <span>'+status+'</span> ' +
    		'<span class="time">'+relative_time(twitters[i].created_at)+'</span></li>'
    	);
		} else {
	    statusHTML.push(
	    	'<li>' +
				'<img src="'+twitters[i].user.profile_image_url+'">' +
    		'<b><a href="http://twitter.com/' + twitters[i].user.screen_name + '" target="_blank">' + 
    		twitters[i].user.screen_name + '</a></b>' +
    		' <span>'+status+'</span> ' +
    		'<span class="time">'+relative_time(twitters[i].created_at)+'</span></li>'
    	);
		}

  }
  $('#twitter_update_list').html(statusHTML.join(''));
	$("#container-twitter").mCustomScrollbar("vertical",400,"easeOutCirc",1.03,"auto","yes");
	doOval();	
}

function doClose(){
	// for contact form
	// do nothing
}

function relative_time(time_value) {
  var values = time_value.split(" ");
  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000, 10);
  delta = delta + (relative_to.getTimezoneOffset() * 60);

  if (delta < 60) {
    return '今';
  } else if(delta < 120) {
    return '1分前';
  } else if(delta < (60*60)) {
    return (parseInt(delta / 60),10).toString() + '分前';
  } else if(delta < (120*60)) {
    return '1時間前';
  } else if(delta < (24*60*60)) {
    return '' + (parseInt(delta / 3600)).toString() + '時間前';
  } else if(delta < (48*60*60)) {
    return '1日前';
  } else {
    return (parseInt(delta / 86400,10)).toString() + '日前';
  }
}

var WEEK_STR = ["日","月","火","水","木","金","土"]
function getWeekStr(ymd){
	var d = new Date(ymd);
	var fig = d.getDay();
	if (d.isJpHoliday()) {
		return "<span class='holiday'>" + WEEK_STR[fig] + "・" + d.jp_hol_name + "</span>";
	}
	if (fig == 0 || fig == 6){
		return "<span class='holiday'>" + WEEK_STR[fig] + "</span>";
	} else {
		return "<span class='weekday'>" + WEEK_STR[fig] + "</span>";
	}
}

Ary = {};
Ary.asort = function(hash,key){
 return hash.sort(function(a, b){
   return (a[key] > b[key]) ? 1 : -1;
 });
}
Ary.arsort = function (hash,key){
 return hash.sort(function(a, b) {
   return (a[key] < b[key]) ? 1 : -1;
 });
}
Ary.getAryOf = function (ary,key){
	var a = new Array();
	var i = 0;
	for (var i=0;i<ary.length;i++)
		a.push(ary[i][key]);
	return a;
}

function countAry(array){
	var cnt = 0;
	for(key in array){ cnt++; }
	return cnt;
}


//  ========================================================
//  jp-holidays.js ---- 祝日取得のための Date 拡張
//  Copyright 2008 Kiyoshi Sakai <sakai [アット] d4k [ドット] net>
//  2008/06/23 - JSでの最初のバージョン
//  2008/09/25 - 昭和23(1948)年からの過去を意識しました
//    参考にしたサイト
//      http://www.asahi-net.or.jp/~ci5m-nmr/misc/holiday.html 
//  2008/10/07 - バグ修正
//  version: 0.0.2
//  ========================================================

Date.prototype.one_day_epoch = 1000 * 60 * 60 * 24;
Date.prototype.jp_hol_vernal_equinox_days = {eventId2000 : '3/20',eventId2001 : '3/20',eventId2002 : '3/21',eventId2003 : '3/21',eventId2004 : '3/20',eventId2005 : '3/20',eventId2006 : '3/21',eventId2007 : '3/21',eventId2008 : '3/20',eventId2009 : '3/20',eventId2010 : '3/21',eventId2011 : '3/21',eventId2012 : '3/20',eventId2013 : '3/20',eventId2014 : '3/21',eventId2015 : '3/21'
};
Date.prototype.jp_hol_autumnal_equinox_days = {eventId2000 : '9/23',eventId2001 : '9/23',eventId2002 : '9/23',eventId2003 : '9/23',eventId2004 : '9/23',eventId2005 : '9/23',eventId2006 : '9/23',eventId2007 : '9/23',eventId2008 : '9/23',eventId2009 : '9/23',eventId2010 : '9/23',eventId2011 : '9/23',eventId2012 : '9/22',eventId2013 : '9/23',eventId2014 : '9/23',eventId2015 : '9/23'
};
Date.prototype.getJpHolNationalFoundationDay = function (y) {
	return 1967 <= y ? '2/11' : null;
}
Date.prototype.getJpHolEquinoxDateCalc = function (y, va) {
	var equinox;
	switch(va) {
	case 'vernal':
		// date('2000/03/20').getTime() + (60 * 60 * 24 * 0.69115)
		equinox = 953537715.36;
		break;
	case 'autumnal':
		// date('2000-09-23').getTime() + (60 * 60 * 24 * 0.09)
		equinox = 969642576.00;
		break;
	}

 	// 2000年の春(秋)分点 + 2000年から太陽年の計算 + 太陽年の誤差修正（100年間で約0.53短くなりつつある）
	var i;
	var y_sum = 0;
	for(i = 0; i > y - 2000; i--) {
		y_sum += i;
	}
	for(i = 0; i < y - 2000; i++) {
		y_sum += i;
	}
	var target_date_equinox = new Date((equinox + (3155692525056 * (y - 2000) / 100000) + (53 * y_sum / 10000)) * 1000);

	return (target_date_equinox.getMonth() + 1) + '/' + target_date_equinox.getDate();

}

Date.prototype.isJpHolVernalEquinoxDay = function (y, m_d) {
	var ve_m_d;
	if(this.jp_hol_vernal_equinox_days[y]) {
		ve_m_d = this.jp_hol_vernal_equinox_days[y];
	} else {
		ve_m_d = this.getJpHolEquinoxDateCalc(y, 'vernal');
		this.jp_hol_vernal_equinox_days[y] = ve_m_d;
	}
	return m_d == ve_m_d ? true : false;
}

Date.prototype.isJpHolAutumnalEquinoxDay = function (y, m_d) {
//	return m_d == (this.jp_hol_autumnal_equinox_days[y] ? this.jp_hol_autumnal_equinox_days[y] : this.getJpHolEquinoxDateCalc(y, 'autumnal'));
	var va_m_d;
	if(this.jp_hol_autumnal_equinox_days[y]) {
		va_m_d = this.jp_hol_autumnal_equinox_days[y];
	} else {
		va_m_d = this.getJpHolEquinoxDateCalc(y, 'autumnal');
		this.jp_hol_autumnal_equinox_days[y] = va_m_d;
	}
	return m_d == va_m_d ? true : false;
}

Date.prototype.isJpHoliday = function(by_date_itself) {

	var y = this.getFullYear();
	var m_d = (this.getMonth() + 1) + '/' + this.getDate();
	var y_m_d = y + '/' + m_d;	// 2008-10-07 追加 バグ修正ごめん
	var national_foundation_m_d = this.getJpHolNationalFoundationDay(y);


	if(this.is_jp_holiday && typeof(this.is_jp_holiday) == 'boolean' && this.y_m_d && this.y_m_d == y_m_d) {
		return this.is_jp_holiday;
	}

	this.y_m_d = y_m_d;

	switch(m_d) {
	case '1/1':
		if(1949 <= y) {
			this.jp_hol_name = '元日';
			this.is_jp_holiday = true;
			return true;
		}
		break;
	case '1/15':
		if(1949 <= y && y <= 1999) {
			this.jp_hol_name = '成人の日';
			this.is_jp_holiday = true;
			return true;	// 2008-10-07 追加 バグ修正ごめん
		}
		break;
	case '4/29':
		if(1927 <= y && y <= 1988) {
			this.jp_hol_name = '天皇誕生日';
			this.is_jp_holiday = true;
			return true;
		} else if(1989 <= y && y <= 2006) {
			this.jp_hol_name = 'みどりの日';
			this.is_jp_holiday = true;
			return true;
		} else if(2007 <= y) {
			this.jp_hol_name = '昭和の日';
			this.is_jp_holiday = true;
			return true;
		}
		break;
	case '5/3':
		if(1949 <= y) {
			this.jp_hol_name = '憲法記念日';
			this.is_jp_holiday = true;
			return true;
		}
		break;
	case '5/4':
		if(2007 <= y) {
			this.jp_hol_name = 'みどりの日';
			this.is_jp_holiday = true;
			return true;
		}
		break;
	case '5/5':
		if(1949 <= y) {
			this.jp_hol_name = 'こどもの日';
			this.is_jp_holiday = true;
			return true;
		}
		break;
	case '7/20':
		if(1996 <= y && y <= 2002) {
			this.jp_hol_name = '海の日';
			this.is_jp_holiday = true;
			return true;
		}
		break;
	case '9/15':
		if(1967 <= y && y <= 2002) {
			this.jp_hol_name = '敬老の日';
			this.is_jp_holiday = true;
			return true;
		}
		break;
	case '10/10':
		if(1966 <= y && y <= 1999) {
			this.jp_hol_name = '体育の日';
			this.is_jp_holiday = true;
			return true;
		}
		break;
	case '11/3':
		if(1948 <= y) {
			this.jp_hol_name = '文化の日';
			this.is_jp_holiday = true;
			return true;
		}
		break;
	case '11/23':
		if(1948 <= y) {
			this.jp_hol_name = '勤労感謝の日';
			this.is_jp_holiday = true;
			return true;
		}
		break;
	case '12/23':
		if(1989 <= y) {
			this.jp_hol_name = '天皇誕生日';
			this.is_jp_holiday = true;
			return true;
		}
		break;
	case national_foundation_m_d:	// 政令で定める日
		if(1967 <= y) {
			this.jp_hol_name = '建国記念の日';
			this.is_jp_holiday = true;
			return true;
		}
		break;
	}
	switch((this.getMonth() + 1) + '-' + Math.ceil(this.getDate() / 7) + '-' + this.getDay()) {
	case '1-2-1':	// １月の第２月曜日
		if(2000 <= y) {
			this.jp_hol_name = '成人の日';
			this.is_jp_holiday = true;
			return true;
		}
		break;
	case '7-3-1':	// ７月の第３月曜日
		if(2003 <= y) {
			this.jp_hol_name = '海の日';
			this.is_jp_holiday = true;
			return true;
		}
		break;
	case '9-3-1':	// ９月の第３月曜日
		if(2003 <= y) {
			this.jp_hol_name = '敬老の日';
			this.is_jp_holiday = true;
			return true;
		}
		break;
	case '10-2-1':	// １０月の第２月曜日
		if(2000 <= y) {
			this.jp_hol_name = '体育の日';
			this.is_jp_holiday = true;
			return true;
		}
		break;
	}

	if(this.isJpHolVernalEquinoxDay(y, m_d)) {
		if(1949 <= y) {
			this.jp_hol_name = '春分の日';
			this.is_jp_holiday = true;
			return true;
		}
	}
	if(this.isJpHolAutumnalEquinoxDay(y, m_d)) {
		if(1948 <= y) {
			this.jp_hol_name = '秋分の日';
			this.is_jp_holiday = true;
			return true;
		}
	}

	if(by_date_itself) {
		this.jp_hol_name = null;
		this.jp_hol_engl = null;
		this.jp_hol_desc = null;
		this.is_jp_holiday = false;
		return false;
	}

	var date_before = new Date(this.getTime() - this.one_day_epoch);
	if(date_before.isJpHoliday(true)) {	// 前日が祝日

		if(date_before.getDay() == 0) {	// 前日が祝日かつ日曜ならば
			this.jp_hol_name = '振替休日';
			this.is_jp_holiday = true;
			return true;
		}

		if(1986 <= y) {
			var date_after = new Date(this.getTime() + this.one_day_epoch);
			if(date_after.isJpHoliday(true)) {		// 前日も翌日も祝日ならば
				this.jp_hol_name = '国民の休日';
				this.is_jp_holiday = true;
				return true;
			}
		}

		if(2007 <= y) {
			date_before.setTime(date_before.getTime() - this.one_day_epoch);
			while(date_before.isJpHoliday(true)) {		// 前日以前が祝日の連続になっている場合
				if(date_before.getDay() == 0) {	// 前日以前が祝日の連続で、日曜が重なる場合
					this.jp_hol_name = '振替休日';
					this.is_jp_holiday = true;
					return true;
				}
				date_before.setTime(date_before.getTime() - this.one_day_epoch);
			}
		}

	}


	this.jp_hol_name = null;
	this.jp_hol_engl = null;
	this.jp_hol_desc = null;
	this.is_jp_holiday = false;
	return false;

}



