var xmlhttp;
var xmlhttpfi;
var xmlhttpcom;
var xmlhttphi;
var DiaryFeeldObj;
var DiaryFontSize;
var Searching = false;
var SearchResultsObj;
var SearchBoxHolderObj;
var SearchBoxObj;
var SearchIconObj;
var SearchTextCheck = '';
var SearchTextForHighlight = '';
var SearchRegForHighlight;
var HighlightReqList = new Array;
var HighlightTextNodeList = new Array;
var SnapBackObj;
var CurrentEntry;
var HiwihiiObject;

var DefaultSearchIcon = '<label for="SearchBox">検索</label>';
var CloseBoxIcon = '<a href="javascript:ClearSearch()">検索を終わる</a>';

var IEshit = '';
if(navigator.userAgent.indexOf('MSIE') != -1){
	IEshit = '<img src="/images/diary/ie_shit.png" width="7" height="42" class="middlepoz" />';
}

imgpreA = new Image();
imgpreA.src = "/images/diary/searchend.png";
imgpreC = new Image();
imgpreC.src = "/images/diary/progress.png";



// Basic Menu Functions  -----------------------------------------------

function DrawWindowMenu(){
	document.write('<p>');
	for(i = 0; Divs[i]; i++){
		document.write('<a href="javascript:MenuClick(' + Divs[i]);
		document.write(')" id="WindowMenu' + Divs[i] + '">');
		document.write(Titles[i]);
		document.write('</a> ');
	}
	document.write('</p>');
}

function MenuClick(target, comment, searchfrom){
	CurrentEntry = target;
	ReloadUI();
	
	xmlhttp = createXMLHttp();
	ConsoleLog('ユーザーが記事 ' + target + ' 号を要求');
	if(searchfrom){
		target += '&searchfrom=' + searchfrom;
	}else if(Mode == 'index'){
		target += '&refferfrom=index';
	}else{
		target += '&refferfrom=' + DefaultId;
	}

	if(xmlhttp && location.host == 'marblecake.jp'){
		document.getElementById('DiaryFeeld').className = 'incompleted';
		ConsoleLog('XHRオブジェクトへ記事 ' + target + ' 号を要求');
		xmlhttp.onreadystatechange = DisplayEntry;
		xmlhttp.open("GET", 'http://marblecake.jp/diary/?ajax=' + encodeURI(target), true);
		xmlhttp.send(null);
	}else{
		ConsoleLog('該当URIへジャンプします');
		location.href = 'http://marblecake.jp/diary/?id=' + target;
	}
}
function DisplayEntry(){
	if(xmlhttp.readyState == 4){
		if(xmlhttp.status == 200 || xmlhttp.status == 404){
			document.getElementById('DiaryFeeld').className = '';
			ConsoleLog('XHRオブジェクトから記事をダウンロードしました');
			DiaryFeeldObj.innerHTML = xmlhttp.responseText;		
			SetSearchCategories();
			
			if(Searching){
				Highlight();
			}
		}else{
			document.getElementById('DiaryFeeld').className = '';
			DiaryFeeldObj.innerHTML = '記事の表示に失敗(' + xmlhttp.status + ')';	
			ConsoleLog('XHRオブジェクトから記事をダウンロードしましたが、エラー(' + xmlhttp.status + ')が発生');
		}
	}
}

function ReloadUI(){
	PrevAndNext();
	FocusSidebars();
	
	if(SnapBackObj){
		if(target == DefaultId && SnapBackObj.innerHTML){
			SnapBackObj.innerHTML = '';
		}else{
			SnapBackObj.innerHTML = '<a href="javascript:MenuClick(DefaultId)" title="このページにSnapBackで戻ります" class="imagelink"><img src="/images/diary/snapback.png" width="14" height="14" alt="SnapBack" style="width:1.16666666em;height:1.16666666em;vertical-align:-2px;min-height:0;" /></a>';
		}
	}
}

function FocusSidebars(){	
	if(document.getElementsByClass){
		var tempAlist = document.getElementsByClass('sideListSelected');
		for(i = 0; tempAlist[i]; i++){
			tempAlist[i].className = "";
		}
	}else{
		var tempAlist = document.getElementsByTagName('a');
		for(i = 0; tempAlist[i]; i++){
			if(tempAlist[i].className == "sideListSelected"){
				tempAlist[i].className = "";
			}
		}
	}
	
	if(document.getElementById('WindowMenu' + CurrentEntry)){
		document.getElementById('WindowMenu' + CurrentEntry).className = "sideListSelected";
	}
	if(document.getElementById('WindowMenuSearch' + CurrentEntry)){
		document.getElementById('WindowMenuSearch' + CurrentEntry).className = "sideListSelected";
	}
}

function PrevAndNext(){
	if(CurrentEntry < Divs[0] && CurrentEntry + 1 > Divs[0] - WholeDiary){
		PrevLink = '<a href="javascript:MenuClick(' + (CurrentEntry + 1) + ')" class="DirectoryPrev">◀ 新しい記事へ</a>';
	}else{
		PrevLink = '<span class="DirectoryPrev">◀ 新しい記事へ</span>';
	}
	if(CurrentEntry > Divs[0] - WholeDiary){
		NextLink = '<a href="javascript:MenuClick(' + (CurrentEntry - 1) + ')" class="DirectoryNext">古い記事へ ▶</a>';
	}else{
		NextLink = '<span class="DirectoryNext">古い記事へ ▶</span>';
	}
	document.getElementById('PrevAndNext').innerHTML = PrevLink + ' • ' + NextLink;
}



// Search Functions  -----------------------------------------------

function DrawSearch(){
	document.write('<form id="SearchForm" onsubmit="Search();return false"><p id="SearchBoxHolder" class="dammyinput">');
	document.write('<span id="SearchIcon">' + DefaultSearchIcon + '</span><input type="text" name="find" id="SearchBox" placeholder="日記を検索" value="" />');
	document.write('</p></form>');
	
	SearchBoxObj = document.getElementById('SearchBox');
	SearchBoxObj.onkeyup = TrySearchWindowDisable;
	//SearchBoxObj.onchange = TrySearchWindowDisable;
	SearchBoxObj.onsearch = TrySearchWindowDisable;
	SearchBoxObj.onfocus = FocussedSearch;
	SearchBoxObj.onblur = InfocussedSearch;
	SearchBoxHolderObj = document.getElementById('SearchBoxHolder');
}
function DrawSearchResults(){
	document.write('<aside id="SearchResultsBar" class="glrightbar"><div id="SearchResults" class="glscrollbox"></div></aside>');
}
function FocussedSearch(){
	SearchBoxHolderObj.className = 'dammyinput focussed';
	TrySearchWindowDisable();
}
function InfocussedSearch(){
	SearchBoxHolderObj.className = 'dammyinput';
	TrySearchWindowDisable();
}

function SearchIt(srchstr){
	SearchBoxObj.value = srchstr;
	Search();
}
function Search(){
	var target = SearchBoxObj.value;
	if(CheckSearchQueryTrueOrNot() == false){
		return false;
	}
	
	if(isWebkitMobile || isWebkitTablet){
		SearchBoxObj.blur();
	}
	SetSearchTextForHighlight();
	SearchTextCheck = target;
	
	xmlhttpfi = createXMLHttp();
	ConsoleLog('ユーザーが文字列 ' + target + ' の検索を要求');
	
	if(xmlhttpfi && location.host == 'marblecake.jp'){
		SearchResultsObj.innerHTML = '<h3>検索結果</h3><p class="centering"><img src="/images/diary/progress.png" /></p>';
		TrySearchWindowEnable();
		ConsoleLog('XHRオブジェクトへ文字列 ' + target + ' の検索を要求');
		xmlhttpfi.onreadystatechange = DisplaySearch;
		xmlhttpfi.open("GET", 'http://marblecake.jp/diary/search?find=' + encodeURI(target) + '&ram=' + parseInt((new Date()).getTime() / 60000), true);
		xmlhttpfi.send(null);
	}else if(xmlhttpfi){
		ConsoleLog('該当URIへジャンプします');
		location.href = 'http://marblecake.jp/diary/?search=' + target;
	}else{
		SearchResultsObj.innerHTML = '申し訳ありませんが、お使いのブラウザはXMLHttpRequest機能に未対応のようです。最新のバージョンのブラウザをお使い下さい。';
		TrySearchWindowEnable();
	} 
}
function DisplaySearch(){
	if(xmlhttpfi.readyState == 4){
		if(xmlhttpfi.status == 200){
			SearchResultsObj.innerHTML = xmlhttpfi.responseText;
			TrySearchWindowEnable();
			ConsoleLog('XHRオブジェクトから検索結果をダウンロードしました');
		}else{
			SearchResultsObj.innerHTML = '<p>検索に失敗(' + xmlhttpfi.status + ')</p>';
			TrySearchWindowEnable();
			ConsoleLog('XHRオブジェクトから検索結果をダウンロードしましたが、エラー(' + xmlhttpfi.status + ')が発生');
		}
	}
}
function TrySearchWindowEnable(){
	Searching = true;
	document.getElementById('GLRailForSearch').className = 'gltray onright';
	FocusSidebars();
	
	if(SearchIconObj){
		SearchIconObj.innerHTML = CloseBoxIcon;
	}
}
function TrySearchWindowDisable(){
	ConsoleLog('検索ウインドウを閉じられるか確認');
	if(SearchBoxObj.value == ''){
		Searching = false;
		document.getElementById('GLRailForSearch').className = 'gltray';
		
		if(SearchIconObj){
			SearchIconObj.innerHTML = DefaultSearchIcon;
		}
		
		SearchResultsObj.innerHTML = '';
		SearchTextCheck = '';
	}else if(SearchIconObj){
		SearchIconObj.innerHTML = CloseBoxIcon;
	}
}
function CheckSearchQueryTrueOrNot(){
	if(SearchBoxObj.value == '' || SearchBoxObj.value == ' ' || SearchBoxObj.value == '　' || SearchTextCheck == SearchBoxObj.value){
		return false;
	}else{
		return true;
	}
}

function ClearSearch(){
	SearchBoxObj.value = '';
	TrySearchWindowDisable();
}

function ShowAllSearchResults(){
	document.getElementById('ShowAllResultButton').style.display = 'none';
	document.getElementById('ShowAllResult').style.display = 'block';
	TrySearchWindowEnable();
}

function SetSearchTextForHighlight(){
	SearchTextForHighlight = SearchBoxObj.value;
	SearchTextForHighlight = SearchTextForHighlight.replace(/[ 　]+/g, '|');
	SearchRegForHighlight = new RegExp('(' + SearchTextForHighlight + ')', "gi");
}
function Highlight(){
	HighlightReqList.length = 0;
	HighlightReqList.push(DiaryFeeldObj);
	FindeOutTextNodesAndHighlight();
}
function FindeOutTextNodesAndHighlight(){
	var eleme = HighlightReqList.shift();
	for(i = 0; eleme.childNodes.length > i; i++){
		if(eleme.childNodes[i].nodeType == 3){
			HighlightTextNodeList.push(eleme.childNodes[i]);
		}else if(eleme.childNodes[i].nodeType == 1){
			if(eleme.childNodes[i].className != 'datetime'){
				HighlightReqList.push(eleme.childNodes[i]);
			}
		}
	}
	if(HighlightReqList[0]){
		FindeOutTextNodesAndHighlight();
	}else{
		HighlightText();
	}
}
function HighlightText(){
	for(i = 0; HighlightTextNodeList.length > i; i++){
		HighlightTextNodeList[i].nodeValue = HighlightTextNodeList[i].nodeValue.replace(SearchRegForHighlight, '{{{$1}}}');
	}
	DiaryFeeldObj.innerHTML = DiaryFeeldObj.innerHTML.replace(/{{{/g, '<span class="highlight">');
	DiaryFeeldObj.innerHTML = DiaryFeeldObj.innerHTML.replace(/}}}/g, '</span>');
	HighlightTextNodeList.length = 0;
}

function SetSearchCategories(){
	if(!document.getElementById('Categories')){
		return true;
	}
	
	var CatName = document.getElementById('Categories').innerHTML;
	if(CatName == 'カテゴリ不明'){
		return true;
	}
	document.getElementById('Categories').innerHTML = '<a href="javascript:SearchIt(' + "'カテゴリ:" + CatName + "'" + ')" title="カテゴリ『' + CatName + '』の記事を検索">' + CatName + '</a>';
}


// Hiwihihii Functions  -----------------------------------------------

var HiwiiHead = '<h3><a href="http://twitter.com/n_sumire" id="HiwihiiLink"><span id="HiwiLogo">Twitter</span> @n_sumire</a></h3>';

function ReadHiwihii(){
	xmlhttphi = createXMLHttp();
	ConsoleLog('ヒウィヒーファイルを要求');
	
	document.getElementById('Hiwihii').innerHTML = HiwiiHead + '<p>loading...</p>';
	
	if(xmlhttphi && location.host == 'marblecake.jp'){
		ConsoleLog('XHRオブジェクトへヒウィヒーファイルを要求');
		xmlhttphi.onreadystatechange = DisplayHiwihii;
		xmlhttphi.open("GET", 'http://marblecake.jp/diary/hiwihihii', true);
		xmlhttphi.send(null);
	}else{
		ConsoleLog('ヒウィヒーファイルの読み込みに失敗');
		document.getElementById('Hiwihii').innerHTML = HiwiiHead;
	}
}
function DisplayHiwihii(){
	if(xmlhttphi.readyState == 4 && xmlhttphi.status == 200){
		ConsoleLog('ヒウィヒーファイルをダウンロードしました');
		if(xmlhttphi.responseText.charAt(0) == '['){
			HiwihiiObject = eval("(" + xmlhttphi.responseText + ")");
			DrawHiwihii();
		}else{
			document.getElementById('Hiwihii').innerHTML = HiwiiHead + '<p>データの読み込みに失敗(しばらく待ってね！)</p>';
		}
	}else if(xmlhttphi.readyState == 4){
		document.getElementById('Hiwihii').innerHTML = HiwiiHead + '<p>データの読み込みに失敗(' + xmlhttphi.status + ')</p>';
	}
}
function DrawHiwihii(){
	if(HiwihiiObject.length < 1){
		document.getElementById('Hiwihii').innerHTML = HiwiiHead + '<p>データの解析に失敗なう</p>';
		
		return false;
	}
	
	var DateList = new Array();
	var TempForPrint = '';

	TempForPrint = HiwiiHead;
	
	var count = 0;
	var dateStr = '';
	
	//TempForPrint += '<div id="TwitBox"><div id="TwitBoxInner">';
	
	var TempDataForHttpToLink = new Array();
	
	for(i = 0; i < HiwihiiObject.length; i++){
		
		// 日付データの処理
		var created_at = HiwihiiObject[i].created_at.split(" ");
		
		var post_date  = created_at[1] + " "
		+ created_at[2] + ", "
		+ created_at[5] + " "
		+ created_at[3];

		DateList[i] = new Date(post_date);
		DateList[i].setHours(DateList[i].getHours() - (DateList[i].getTimezoneOffset() / 60));
		
		dateStr = SotaiTime(DateList[i].getTime() / 1000);
		
		if(navigator.userAgent.indexOf('MSIE') != -1){
			HiwihiiObject[i].text = unescape(HiwihiiObject[i].text);
		}
		
		if(HiwihiiObject[i].text.charAt(0) == '@' || HiwihiiObject[i].text.indexOf(' RT @') != -1){
			continue;
		}
		
		if(count >= 3){
			TempForPrint += '<p class="twitry"><span>';
		}else{
			TempForPrint += '<p><span>';
		}
		
		TempDataForHttpToLink = HiwihiiObject[i].text.replace(/\n/g," ").split(" ");
		for(n = 0; TempDataForHttpToLink.length > n; n++){
			if(TempDataForHttpToLink[n].slice(0,7) == "http://"){
				TempDataForHttpToLink[n] = '<a href="' + TempDataForHttpToLink[n] + '">' + TempDataForHttpToLink[n] + '</a>';
			}
		}
		
		HiwihiiObject[i].text = TempDataForHttpToLink.join(" ");
		
		TempForPrint += HiwihiiObject[i].text + '</span><span class="hiwitime">' + dateStr + '</span></p>';
		
		//TempForPrint += '<a href="http://twitter.com/n_sumire/statuses/' + HiwihiiObject[i].id + '">';
		
		count ++;
	}
	
	//TempForPrint += '</div></div>';
	TempForPrint += '<div id="Twitry"><a href="javascript:ShowAllHiwihii()" id="TwitryOn">+ show all</a><a href="javascript:CloseHiwihii()" id="TwitryOff">- close</a></div>';
	
	if(document.getElementById('Hiwihii')){
		document.getElementById('Hiwihii').innerHTML = TempForPrint;
	}
	
	//MCMSrefreshSizeById('TwitBox', 'TwitBoxInner', 'height');
	//SetMCMSparentById('TwitBox', 'height');
}
function ShowAllHiwihii(){
	document.getElementById('Hiwihii').className = 'showingtwitry';
	//MCMSrefreshSizeById('TwitBox', 'TwitBoxInner', 'height');
}
function CloseHiwihii(){
	document.getElementById('Hiwihii').className = 'closingtwitry';
	//MCMSrefreshSizeById('TwitBox', 'TwitBoxInner', 'height');
}



// The Great Modules  -----------------------------------------------

function ConsoleLog(text){
	if(isAppleWebkit){
		console.log(text);
	}
}


// The Great Modules  -----------------------------------------------

function createXMLHttp(){
	if(window.XMLHttpRequest){
		return new XMLHttpRequest();
		ConsoleLog('XHRオブジェクトを作成');
	}else{
		return null;
		ConsoleLog('XHRオブジェクト作成に失敗');
	}
}

function ScrollToBottom(){
	ScrollNow = getScrollTop();
	
	if(document.all){
		window.scrollBy(0, 10000);
	}else{
		window.scrollBy(0, parseInt(document.body.offsetHeight * 1.2));
	}
	if(ScrollNow != getScrollTop()){
		setTimeout("ScrollToBottom()", 25);
	}
}

function getScrollTop(){
	if (document.all) {
		return document.body.scrollTop;
	} else if (window.pageYOffset) {
		return window.pageYOffset;
	} else {
		return 0;
	}
}


function SotaiTime(inputtime){
	NowTime = parseInt((new Date()).getTime() / 1000);
	tempUptime = NowTime - inputtime;
	UpDateYYYYMMDD = YYYYMMDD(inputtime);
	UpDateYYYYMM = YYYYMM(inputtime);
	
	tempKeisoku = NowTime;
	tempNdaysAgo = 0;
	while(YYYYMMDD(tempKeisoku) > UpDateYYYYMMDD){
		tempNdaysAgo ++;
		tempKeisoku -= 86400;
	}
	
	tempKeisoku = YYYYMM(NowTime);
	tempNmonthsAgo = 0;
	while(tempKeisoku > UpDateYYYYMM && tempNmonthsAgo < 16){
		tempNmonthsAgo ++;
		tempKeisoku --;
		if(tempKeisoku % 100 == 0){
			tempKeisoku -= 88;
		}
	}
	
	if(tempUptime <= 92){
		return '1 minute ago';
	}else if(tempUptime <= 60 * 50){
		return parseInt(tempUptime / (60) + 0.5) + ' minutes ago';
	}else if(tempUptime <= 60 * 60 * 1.5){
		return '1 hour ago';
	}else if(tempUptime <= 60 * 60 * 6){
		return parseInt(tempUptime / (60 * 60) + 0.5) + ' hours ago';
	}else if(tempUptime <= 60 * 60 * 24){
		return parseInt(tempUptime / (60 * 60) + 0.5) + ' hours ago';
	}else if(tempNdaysAgo == 0){
		return 'today';
	}else if(tempNdaysAgo == 1){
		return 'yesterday';
	}else if(tempNdaysAgo < 7){
		return tempNdaysAgo + ' days ago';
	}else if(tempUptime <= 60 * 60 * 24 * 7 * 1.5){
		return '1 week ago';
	}else if(tempUptime <= 60 * 60 * 24 * 7 * 2.5){
		return parseInt(tempUptime / (60 * 60 * 24 * 7) + 0.5) + ' weeks ago';
	}else if(tempUptime <= 60 * 60 * 24 * 7 * 4 && tempNmonthsAgo == 0){
		return parseInt(tempUptime / (60 * 60 * 24 * 7) + 0.5) + ' weeks ago';
	}else if(tempNmonthsAgo == 0){
		return 'Early this month';
	}else if(tempNmonthsAgo == 1){
		return 'Last month';
	}else if(tempNmonthsAgo < 10){
		return tempNmonthsAgo + ' months ago';
	}else if(tempNmonthsAgo < 14){
		return '1 year ago';
	}else{
		return 'long time ago';
	}
}

function YYYYMMDD(sec){
	thistime = new Date();
	thistime.setTime(sec * 1000);
	return (thistime.getFullYear()) * 10000 + (thistime.getMonth() + 1) * 100 + thistime.getDate();
}
function YYYYMM(sec){
	thistime = new Date();
	thistime.setTime(sec * 1000);
	return (thistime.getFullYear()) * 100 + (thistime.getMonth() + 1);
}


// Onload Events  -----------------------------------------------

function OnLoad(){
	DiaryFeeldObj = document.getElementById('DiaryFeeld');
	SearchResultsObj = document.getElementById('SearchResults');
	SearchIconObj = document.getElementById('SearchIcon');
	
	//SetMCMSparent(SearchResultsObj, SearchResultsObj, 'height');
	
	CurrentEntry = DefaultId;
	ReloadUI();
	
	SetSearchCategories();
	if(SearchBoxObj.value != ''){
		TrySearchWindowDisable();
	}
	if(Mode == 'id'){
		SnapBackObj = document.getElementById('SnapBack');
	}
	if(DefaultSearch){
		SearchIt(DefaultSearch);
	}
	
	ReadHiwihii();
}