// FFO Plugin


var linkdic;
var wordregexp;
var word2id;

function linkdic_expand(node) {
	var i;
	var html = node.html();
	if(!html) {
		return;
	}
	
	var totalarticle = linkdic[0];
	$("#menu>ul>li>a[href$='/html/index_top.html']").html('索引　' + '(全' + totalarticle + '件)');
	
	
	var max = linkdic.length;
	
	// make regexp & hash
	if(!wordregexp) {
		word2id = {};
		var regexpstring = '';
		for(i = 1; i < max; i++) {
			regexpstring += linkdic[i][0] + '|';
			word2id[linkdic[i][0]] = linkdic[i][1];
		}
		regexpstring = regexpstring.replace(/\|$/, '');
		regexpstring = regexpstring.replace(/\+/g, '\\+');
		regexpstring = regexpstring.replace(/\./g, '\\.');
		regexpstring = regexpstring.replace(/\?/g, '\\?');
		regexpstring = regexpstring.replace(/\!/g, '\\!');
		wordregexp = new RegExp("(" + regexpstring + ")", 'g');
	}

	// [[]]のリンク
	html = html.replace(/\[\[([^\[\]]*)\]\]/g, function(basestr, match1){
		var str = match1;
		var link = match1;
		var linkstr = match1;
		if(match1.match(/^([^\|]*)\|(.*)$/)) {
			linkstr = RegExp.$1;
			link = RegExp.$2;
		}
		
		if(word2id[link]) {
				return '<a href="/html/' + word2id[link] + '.html">'
					+ linkstr + '</a>';
		} else {
			return ('<a href="/wiki.cgi?Command=NewWrite&title='
				+ encodeURIComponent(link) + '&CCC='
				+ encodeURIComponent("愛") + '" target="_blank">' + linkstr + '?</a>');
		}
	});
	
	
	html = html.replace(new RegExp("(^|>)([^<]*)", 'g'), 
		function(basestr, match1, match2){
			match2 = match2.replace(wordregexp,
				function(basestr, match1){
					return ('<a href="/html/' + word2id[match1] + '.html">' + match1 + '</a>');
			});
			return match1 + match2;
		}
	);
	

	// 2重リンク解除
	var newhtml;
	while(1) {
		newhtml = html.replace(/(<a [^>]*href="[^"]*"[^>]*>[^<]*)<a [^>]*href="[^"]*"[^>]*>([^<]*)<\/a>/ig, '$1$2');
		if(newhtml == html) {
			break;
		}
		html = newhtml;
	}
	
	node.html(html);
	
	link_rewrite(node);
}

function link_rewrite(node){
	
	// ファイル内リンクの書き換え
	$("a.comment_link", node).click(function(){
		var href = $(this).attr("href");
		href = href.replace(/^.*(#.*)$/, '$1');
		$(href).highlightFade({color:'red',speed:3000,iterator:
				function(s,e,t,c) { return parseInt(s+(Math.pow((c<0.1?0:((c-0.1)/0.9))/t,2))*(e-s)); }
			})
		return true;
	}).attr({ "class": "comment_link2" });
	
}

var history_failure = 0;
function history_relink(text, status) {
	if(history_failure == 0 && status != 'success') {
		history_failure = 1;
		$('#history').load("/html/history/word_newest.html?" + (new Date()).getTime(), history_relink);
	} else {
		history_failure = 0;
		$('.history_link').add('.history_daylink').click(function(){
				$.cookie('ff14_history_date', $(this).attr('href'));
				$('#history').load($(this).attr('href') + "?" + (new Date()).getTime(), history_relink);
				return false;
			});
	}
}

var searchquery = '';
var searchindex;
function search_check() {
	
	var current_query = $("#searchword").val();
	if(searchquery != current_query) {
		searchquery = current_query;
		search_update();
	}
}


var content_is_searchresult = false;
var historyindex;
var history_loading;
function search_update() {
	var $searchword = $("#searchword");
	if(!$searchword.size()) {
		return;
	}
	
	if(!historyindex) {
		if(!history_loading) {
			history_loading = 1;
			$("#content").html("検索データ読み込み中．．．");
			$.get("/historyindex.txt?" + (new Date()).getTime(), function(text){
				historyindex = eval(text);
				search_update();
			});
		}
		return;
	}
	
	if(!searchindex) {
		searchindex = [];
		var datei;
		var datemax = historyindex[0].length;
		var text1 = '/';
		var html1 = '<a href="/html/';
		var html2 = '.html">';
		var html3 = '</a>';
		var html4 = ' (';
		var html5 = ')';
		var html6 = '';
		var html7 = '<br />';
		for(datei = 0; datei < datemax; datei++) {
			var dayindex = historyindex[0][datei];
			var i;
			var max = dayindex.length;
			for(i = 1; i < max; i++) {
				var indexrecord = dayindex[i];
				var searchtitle = indexrecord[0].toLowerCase();
				if(indexrecord[2] != undefined) {
					searchtitle += text1 + indexrecord[2].toLowerCase();
				}
				var resultstr;
				if(indexrecord[2]) {
					resultstr = [html1, indexrecord[1], html2, indexrecord[0], html3,
						html4, indexrecord[2], html5, html7]
				} else {
					resultstr = [html1, indexrecord[1], html2, indexrecord[0], html3,
						html6, html7]
				}
				searchindex.push([searchtitle, resultstr.join('')]);
			}
		}
		$("#searchdiv").html('検索 (全' + searchindex.length + '件)');
	}
	
	var searchword = $searchword.val();
	if(searchword == "") {
		return;
	}
	searchword = searchword.toLowerCase();
	
	var result = '<div class="searchresult">';
	var count = 0;
	var i;
	var max = searchindex.length;
	for(i = 0; i < max; i++) {
		if(searchindex[i][0].indexOf(searchword) >= 0) {
			count++;
			if(count > 100) {
				result = "件数が多すぎるため最初の100件を表示します。" + result;
				count = String(count - 1) + "+";
				break;
			}
			result += searchindex[i][1];
		}
	}
	result += '</div>';
	
	if(count != 0) {
		var title = '<div class="article"><div class="title">"' + searchword + '" の検索結果 <span class="yomi">'
			+ count
			+ '件</span></div></div>';
		
		$("#content").html(title + result);
		link_rewrite($("#content"));
	} else if(!content_is_searchresult) {
		content_is_searchresult = true;
		var title = '<div class="article"><div class="title">"' + searchword + '" の検索結果 <span class="yomi">'
			+ count
			+ '件</span></div></div>';
		
		$("#content").html(title + result);
	}
	
}

$(document).ready(function(){
	// リンク辞書読み込み
	$.get("/linkindex.txt?" + (new Date()).getTime(), function(text){
		linkdic = eval(text);
		linkdic_expand($('.content'));
		linkdic_expand($('.comment'));
	});
	
	// 更新履歴読み込み
	var history_day = $.cookie('ff14_history_date');
	if(history_day) {
		$('#history').load(history_day + "?" + (new Date()).getTime(), history_relink);
	} else {
		$('#history').load("/html/history/word_newest.html?" + (new Date()).getTime(), history_relink);
	}
	
	//リーヴ表示
	update_time();
	setInterval(update_time, 60 * 1000);
	
	// 検索フォーム表示
//	$("#searchform").submit(function(){return false;});
//	var myloc = location.pathname;
//	$("#searchdiv").show();
//	$("#searchform").show();
//	setInterval(search_check, 50);
	
});

//リーヴ時間表示
function update_time() {
	
	var epoch = (new Date()).getTime() / 1000;
	var next_count = (Math.floor(epoch / (60 * 60 * 36)) + 1);
	var next_time = next_count * 60 * 60 * 36;
	var add_count = 0;
	if(next_time < epoch) {
		var next_time = (next_count + 1) * 60 * 60 * 36;
		add_count = 1;
	}
	var to_next_second = next_time - epoch;
	
	$("#at_hour").text(Math.floor(to_next_second / 3600));
	$("#at_min").text(Math.floor(to_next_second / 60) % 60);

	var youbi = ["日", "月", "火", "水", "木", "金", "土"];
	var sche = '';
	for(var i = 1; i < 6; i++) {
		var next_time = (Math.floor(epoch / (60 * 60 * 36)) + i + add_count) * 60 * 60 * 36;
		var next_date = new Date(next_time * 1000);
		
		sche += "<li>" + (next_date.getMonth() + 1) + "/" + next_date.getDate() + "(" + youbi[next_date.getDay()] + ") "
			+ (next_date.getHours() < 12 ? 'AM' : 'PM') + (next_date.getHours() % 12)
			+ " </li>";
	}
	$("#sche").html(sche);
	
}



