document.write('<script type="text/javascript" src="/js/prototype.js"></script>');
document.write('<script type="text/javascript" src="/js/scriptaculous.js?load=effects"></script>');

var idmap = new Array();
var titlemap = new Array();
var historymap = new Array();
var lang;

window.onload = function() {
	var m = $('main'); 
	if (m) {
		m.hide();
		applyLinkAction($('top'));
		initContents();
		Event.observe(window, "scroll", scrollHistory, false);
	}
}

function page(url, title) {
	this.url = escape(url);
	this.title = escape(title);
}

function jump() {

	var pages = "";
	if (arguments && arguments.length > 0) {
		for (var i = 0; i < arguments.length; i++) {
			var p = arguments[i];
			if (i > 0) pages += ",";
			pages += p.url + ":" + p.title;
		}
	}
	document.cookie = "pages=" + pages + "; path=/;";
	document.cookie = "histories=; path=/;";
	location.href = "/";
	return false;
}

function welcome() {
	if (lang.match(/^ja/)) {
		ajaxReq('/welcome.jsp', 'アッズーリ', false, true);
		ajaxReq('/notice/index.jsp', 'ニュース', false, true);
	} else {
		ajaxReq('/en/welcome.jsp', 'Azzurri', false, true);
	}
}

function initContents() {
	if (document.cookie) {
		var values = document.cookie.split(";");
		var pages = '';
		for (var i = 0; i < values.length; i++) {
			if (values[i].match(/histories=/)) {
				restoreHistories(values[i].replace(/^\s+/, "").substring(11).split(","));
			}
			if (values[i].match(/pages=/)) {
				pages = values[i].replace(/^\s+/, "").substring(6).split(",");
				restorePages(pages);
			}
		}
		if (pages != null &&
				(pages.length == 0 || (pages.length == 1 && pages[0] == ""))) {
			welcome();
		}
	} else {
		welcome();
	}
	scrollHistory();
}

function tr(url) {
	var key = url;
	var host = window.location.protocol + "//" + window.location.host + "/";
	if (url.match("^" + host) == host) {
		key = key.substring(host.length);
	}
	if (key.match("^/") != '/') {
		key = '/' + key;
	}
	return key;
}

function link(event) {
	var e = Event.element(event);
	var title;
	if (e.title) {
		title = e.title;
	} else if (e.alt) {
		title = e.alt;
	} else {
		title = e.innerHTML;
	}
	Event.stop(event);
	ajaxReq(tr(this.href), title, true);
	return false;
}

function close(event) {
	var e = Event.element(event);
	var p = $(e.id.sub("close", "page"));
	new Effect.Fold(p, {duration: 0.3, afterFinish: function() {
		delete idmap[p.firstChild.url];
		delete titlemap[p.firstChild.url];
		Element.remove(p);
		if ($("main").select('[class="page"]').length == 0) {
			welcome();
		}
		scrollHistory();
		storePages();
	}});
	Event.stop(event);
	return false;
}

var semaphore = 0;

function ajaxReq(url, title, scroll, sync) {

	var syncNo = 0;
	if (sync) {
		syncNo = ++semaphore;
	}
	var key = tr(url);
	if (idmap[key]) {
		smoothScrollTo(idmap[key]);
		return false;
	}
	var msec = (new Date()).getTime();

	new Ajax.Request(url, {
		method : "get",
		parameters : "cache=" + msec,
		onCreate: function(){
			$('loader').show();
		},
		onSuccess : function(httpObj) {
			idmap[tr(url)] = 'page' + msec;
			titlemap[tr(url)] = title;
			if (sync) {
				if (syncNo != semaphore) {
					var timer = setInterval(function () {
						if (syncNo == semaphore) {
							clearInterval(timer);
							apply(httpObj, url, title, msec, true);
							--semaphore;
							if (semaphore == 0) {
								$('loader').hide();
								$('main').show();
							}
						}
					}, 30);
				} else {
					apply(httpObj, url, title, msec, true);
					--semaphore;
					if (semaphore == 0) {
						$('loader').hide();
						$('main').show();
					}
				}
			} else {
				apply(httpObj, url, title, msec);
				$('loader').hide();
				$('main').show();
			}
		},
		onFailure : function(httpObj) {
			$("console").innerHTML = "failed to read " + url + ".<br>";
			smoothScrollTo('top');
			if (sync) {
				--semaphore;
			}
			$('main').show();
		}
	});
	return false;
}

function applyLinkAction(element) {
	element.select('a').each(function(o) {
		if (o.target != '_blank') {
			Event.observe(o, "click", link, false);
		}
	});
}

function storePages() {
	var pages = '';
	var ps = $('main').select('[class="page"]');
	for (var i = 0; i < ps.length; i++) {
		var p = ps[i];
		if (i != 0) pages += ",";
		pages += escape(p.firstChild.url) + ":" + escape(titlemap[p.firstChild.url]);
	}
	document.cookie = 'pages=' + pages + '; path=/;';
}

function storeHistories() {
	var histories = '';
	var hs = $('histories').getElementsBySelector('a');
	for (var i = hs.length - 1; i >= 0 ; i--) {
		var h = hs[i];
		if (h) {
			var key = tr(h.href);
			histories += escape(key) + ":" + escape(h.title);
			if (i != 0) histories += ",";
		}
	}
	document.cookie = "histories=" + histories + "; path=/;";
}

function restorePages(pages) {
	for (var i = 0; i < pages.length; i++) {
		var page = pages[i].split(":");
		if (page[0]) {
			ajaxReq(unescape(page[0]), unescape(page[1]), false, true);
		}
	}
}

function restoreHistories(histories) {
	var hs = $('histories');
	for (var i = 0; i < histories.length; i++) {
		var history = histories[i].split(":");
		if (history[0]) {
			var url = unescape(history[0]);
			var title = unescape(history[1]);
			var linkTitle = title;
			var key = tr(url);
			if (title.length > 13) {
				title = title.substring(0, 13) + "...";
			}
			historymap[key] = key;
			new Insertion.Top(hs, '<a href="' + url + '" title="' + linkTitle + '">' + title + '</a><br />');
		}
	}
	applyLinkAction(hs);
}

function apply(httpObj, url, title, msec, notAddHistory) {
	var key = tr(url);
	var a = '<div class="page" style="display: none;" id="page' + msec + '"><div class="scrap">'
	+ '<h1><span class="close" id="close' + msec
	+ '">X</span>' + title + '</h1>'
	+ httpObj.responseText + '</div></div>';

	new Insertion.Top("main", a);

	var ex = $('page' + msec);
	ex.firstChild.url = key;

	var m = $("main");
	if (scroll) {
		if (m.firstChild == ex) {
			smoothScrollTo('top');
		} else {
			smoothScrollTo(ex.id);
		}
	}
	Event.observe($('close' + msec), "click", close, false);
	applyLinkAction(ex);
	
	var ps = m.select('[class="page"]');
	var pages = ps.length;
	if (pages >= 8) {
		var lp = ps[ps.length - 1];
		delete idmap[lp.firstChild.url];
		delete titlemap[lp.firstChild.url];
		Element.remove(lp);
	}
	$("console").innerHTML = "";

	new Effect.SlideDown(ex, {duration: 0.5, afterFinish: function() {
	ex.style.filter = "filter: progid:DXImageTransform.Microsoft.Blur(PixelRadius='5', MakeShadow='true', ShadowOpacity='0.30')";
	storePages();
	
	if (notAddHistory) return false;

	var linkTitle = title;
	if (title.length > 13) {
		title = title.substring(0, 13) + "...";
	}
	var hs = $("histories");
	if (historymap[key]) {
		hs.getElementsBySelector('a').each(function(o) {
			if (tr(o.href)==key) {
				delete historymap[key];
				Element.remove(o.next());
				Element.remove(o);
			}
		});
	}
	var historyLink = '<a href="' + url + '" title="' + linkTitle + '">' + title + '</a><br />';
	historymap[key] = key;
	new Insertion.Top(hs, historyLink);
	
	var histories = hs.getElementsBySelector('a');
	if (histories) {
		if (histories.length >= 15) {
			delete historymap[tr(histories[histories.length - 1].href)];
			Element.remove(histories[histories.length - 1]);
		}
		applyLinkAction(hs);
	}
	storeHistories();
	}});
}

var inScroll;

function smoothScrollTo(id) {
	if (!$(id)) return;
	
	if ($("main").firstChild == $(id)) {
		id = 'top';
	}

	inScroll = true;
	var f = document.viewport.getScrollOffsets();
	var t = $(id).cumulativeOffset()[1] - 5;
	var d = f.top < t ? 1 : -1;
	var i = setInterval(function() {
		var a = Math.abs(f.top - t) * 0.08 + 5;
		if ((d > 0 && t <= f.top) || (d <= 0 && t >= f.top)) {
			scrollTo(f.left, t);
			clearInterval(i);
			inScroll = false;
			scrollHistory();
		} else {
			scrollTo(f.left, f.top);
		}
		f.top += d * a;
	}, 10);
}

function scrollHistory(event) {
	if (inScroll) {
		return;
	}
	var p = $('hPanel');
	var ph = Element.getDimensions(p).height;
	var ft = Element.cumulativeOffset($('footer')).top;
	var init = p.offsetTop;
	var t = setInterval(function() {
		var cur = document.viewport.getScrollOffsets().top + 20;
		if (cur + ph > ft) {
			var lt = ft - ph - 20;
			if (lt > 0) cur = lt;
		}
		var myTop = p.cumulativeOffset()[1];
		var d = cur - myTop;
		if (Math.abs(d) > 1) {
			if (Math.abs(cur - init) > Math.abs(d) / 3) {
				var y = myTop + d / 3;
				p.style.top = y + "px";
			} else {
				p.style.top = init + "px";
				clearInterval(t);
			}
		} else {
			p.style.top = cur + "px";
			clearInterval(t);
		}
	}, 10);
	if (event) {
		var e = Event.element(event);
		Event.stop(event);
	}
	return false;
}

function reset() {
	var m = $('main');
	m.hide();
	var ps = m.select('[class="page"]');
	for (var i = 0; i < ps.length; i++) {
		var p = ps[i];
		delete idmap[p.firstChild.url];
		delete titlemap[p.firstChild.url];
		Element.remove(p);
	}
	welcome();
	m.show();
}

