var text = {
	guest:   "гостевая книга",
	gallery: "галлерея (сожрет кучу трафика)",
	about:   "о сайте",
	back:    "вернуться на главную",
	write:   "написать комментарий",
	count:   ""
}

var func = {
	guest:   new Function("this._helper.remove(); this.style.opacity = this._minOpacity; document.location.href = './guest.html'"),
	gallery: new Function("this._helper.remove(); this.style.opacity = this._minOpacity; document.location.href = './gallery.html'"),
	about:   new Function("this._helper.remove(); this.style.opacity = this._minOpacity; document.location.href = './about.html'"),
	back:    new Function("this._helper.remove(); this.style.opacity = this._minOpacity; document.location.href = './index.html'"),
	write:   new Function("var wrtr = document.getElementById('wrtr'); if(wrtr.style.visibility == 'visible'){wrtr.style.visibility='hidden'}else{wrtr.style.visibility='visible'}"),
	count:   new Function("")
}

function addMainBar(){
	ajaxRequest('./cgi/counter.cgi', counter, "get", null);
}

function addBackBar(s){
	var bar = new BackBar(null, s);
}

function MainBar(parent, s){
	if(!parent)
		parent = document.body;

	var bar = document.createElement('div');
	bar.className = "mainBar";
	parent.appendChild(bar);

	for(i in s){
		var b = document.createElement('div');
		b.className = "mainBarButton";
		b.style.background = "url('./icons/" + s[i] + "-main.png')";
		b.style.opacity = b._minOpacity = 0.3;
// 		b.addEventListener("mouseover", fadeIn, false);
// 		b.addEventListener("mouseout", fadeOut, false);
// 		b.addEventListener("click", func[s[i]], false);

		b.onmouseover = fadeIn;
		b.onmouseout = fadeOut;
		b.onclick = func[s[i]];
		
		b._str = text[s[i]];
		bar.appendChild(b);
	}
}

function BackBar(parent, s){
	if(!parent)
		parent = document.body;
	
	var bar = document.createElement('div');
	bar.className = "backBar";
	var w = 168 + 84*s.length + "px";
	bar.style.width = w;
	bar.style.marginLeft = '-' + w;
	parent.appendChild(bar);

	for(i in s){
		var w = document.createElement('div');
		w.className = "backBarWrapper";
		bar.appendChild(w);

		var b = document.createElement('div');
		b.className = "backBarButton";
		b.style.background = "url('./icons/" + s[i] + "-back.png')";
		b.style.opacity = b._minOpacity = 0.5;
// 		b.addEventListener("mouseover", fadeIn, false);
// 		b.addEventListener("mouseout", fadeOut, false);
// 		b.addEventListener("click", func[s[i]], false);

		b.onmouseover = fadeIn;
		b.onmouseout = fadeOut;
		b.onclick = func[s[i]];
		
		b._str = text[s[i]];
		w.appendChild(b);
	}

	var b = document.createElement('div');
	b.className = "mainBarButton";
	b.style.background = "url('./icons/back.png')";
	b.style.opacity = b._minOpacity = 0.5;
// 	b.addEventListener("mouseover", fadeIn, false);
// 	b.addEventListener("mouseout", fadeOut, false);
// 	b.addEventListener("click", func['back'], false);

		b.onmouseover = fadeIn;
		b.onmouseout = fadeOut;
		b.onclick = func['back'];
	b._str = text['back'];
	bar.appendChild(b);
}

function counter(req){
	if(req.readyState == 4 && req.status == 200 && req.responseXML){
		text.count = "Уникальных посещений: " + req.responseText;
		var s = ["guest", "gallery", "about", "count"];
		var bar = new MainBar(null, s);
	}
}

function dp(event) {
	var x = y = 0;
	if (document.attachEvent) {
		x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
		y = window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
	}
	else{
		x = event.clientX + window.scrollX;
		y = event.clientY + window.scrollY;
	}
	return {x:x, y:y};
}

function fadeIn(e){
	this.style.opacity = 1;
	this._helper = new Helper(dp(e), this._str);
}

function fadeOut(){
	this.style.opacity = this._minOpacity;
	if(this._helper){
		this._helper.remove();
	}
}

function Helper(e, str){
	var d = document.createElement('div');
	d.className = "helper";
	d.style.top = e.y - 120 + "px";
	d.style.left = e.x - 100 + "px";
	d.innerHTML = str;
	document.body.appendChild(d);

	this.remove = function(){
		document.body.removeChild(d);
	}
}

function ajaxRequest(url, backend, method, data){
	var req;// = new XMLHttpRequest();
	if(XMLHttpRequest){
		req = new XMLHttpRequest();
	}
	else{
		req = new ActiveXObject("Msxml2.XMLHTTP"); // блядский осёл!
	}
// 	req.addEventListener("readystatechange", function(){backend(req)}, false);

	req.onreadystatechange = function(){backend(req)};
	req.open(method, url, true);
	req.send(data);
}

function backendFunc(){
	backend(req);
}

function initGuest(){
	ajaxRequest("./cgi/commentsrequest.cgi", commentsRequest, "get", null);
	var c = new Commenter(
		document.getElementById("wrtr"),
		function(){
			ajaxRequest("./cgi/addcomment.cgi?" + c.getParams(), function(){}, "get", null);
// 			location.reload(true);
			}
		);
}

function commentsRequest(req){
	if(req.readyState == 4 && req.status == 200 && req.responseXML){
		var cmnts = req.responseXML.getElementsByTagName('comment');
		var book = document.getElementById("book");
		for(var i=0; i<cmnts.length; ++i){
			var cmnt = escapeEntities(cmnts[i].getAttribute('text'));
			var author = escapeEntities(cmnts[i].getAttribute('author'));
			var time = cmnts[i].getAttribute('time');
			var ip = cmnts[i].getAttribute('ip');
			var d = document.createElement('div');
			d.innerHTML = '<div style="width:100%;">'+
							'<p style="width:500px; height: 20px; text-align: left; background: #555555; float: left; display: inline"> Автор: '+author+'</p>' +
							'<p style="width:280px; height: 20px; text-align: right; background: #555555; float: left;  display: inline">'+time+'</p>'+
							'<p style="width: 100%; float: left">'+cmnt+'</p>';
							'</div>';
			book.insertBefore(d, book.firstChild);
		}
	}
}

function escapeEntities(str){
	str = str.replace(/&/g, "&amp;");
	str = str.replace(/</g, "&lt;");
	str = str.replace(/>/g, "&gt;");
	str = str.replace(/"/g, "&quot;");
	str = str.replace(/'/g, "&apos;");
// 	str = str.replace(/ /g, "&nbsp");
	str = str.replace(/\\n/g, "<br>");
	return str;
}

function commentTime(){
	var d = new Date;
	var days   = [ 'воскресенье', 'понедельник', 'вторник', 'среда', 'четверг', 'пятница', 'суббота'];
	var months = ['января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря'];
	var h = d.getHours();
	var m = d.getMinutes();
	return days[d.getDay()] + ", " + d.getDate() + " " + months[d.getMonth()] + ", " + (h>9?h:'0'+h) + ":" + (m>9?m:'0'+m);
}

function Commenter(parent, func){
	if(!parent)
		parent = document.body;
	
	var wrtr = document.createElement('div');
	wrtr.style.position = "absolute";
	wrtr.style.top = "-100px";
	wrtr.style.width = "500px";
	wrtr.style.height = "250px";
	wrtr.style.background = "black";
	wrtr.style.color = "white";
	parent.appendChild(wrtr);

	var lbl1 = document.createElement('span');
	lbl1.style.position = "absolute";
	lbl1.style.top = "5px";
	lbl1.style.left = "5px";
	lbl1.style.width = "95px";
	lbl1.style.height = "20px";
	lbl1.innerHTML = "Ваше имя:";
	wrtr.appendChild(lbl1);

	var auth = document.createElement('input');
	auth.name = "author";
	auth.style.position = "absolute";
	auth.style.top = "5px";
	auth.style.left = "110px";
	auth.style.width = "280px";
	auth.style.height = "20px";
// 	auth.style.background = "grey";
	auth.style.background = "#888888";
	auth.style.color = "white";
	auth.style.border = "0px";
	wrtr.appendChild(auth);

	var sbm = document.createElement('input');
	sbm.type = 'submit';
	sbm.style.position = "absolute";
	sbm.style.top = "5px";
	sbm.style.left = "398px";
	sbm.style.width = "100px";
	sbm.style.height = "20px";
	sbm.value = "отправить";
	sbm.style.background = "black";
	sbm.style.color = "white";
// 	sbm.style.border = "1px solid grey";
	sbm.style.border = "1px solid #888888"
	sbm.onclick = func;
	wrtr.appendChild(sbm);

	var txt = document.createElement('textarea');
	txt.name = "text";
	txt.style.position = "absolute";
	txt.style.top = "50px";
	txt.style.left = "0px";
	txt.style.width = "500px";
	txt.style.height = "200px";
// 	txt.style.background = "grey";
	txt.style.background = "#888888";
	txt.style.color = "white";
	txt.style.border = "1px solid black";
	wrtr.appendChild(txt);

// 	new EditPanel(wrtr, 28, 0, txt);

	this.getParams = function(){
		return ("author=" + auth.value + "&text=" + txt.value + "&time=" + commentTime()).replace(/;/g, "%3B");
	}

}

function EditPanel(parent, x, y, txt){
	if(!parent)
		parent = document.body;

	var panel = document.createElement('div');
	panel.style.position = "absolute";
	panel.style.top = x + "px";
	panel.style.left = y + "px";
	panel.style.width = "500px";
	panel.style.height = "22px";
	panel.style.background = "gray";
	parent.appendChild(panel);

	var b0 = document.createElement('div');
	b0.style.width = b0.style.height = "22px";
	b0.style.background = "url('./icons/text-bold.png')";
	b0.style.cssFloat = "left";
	b0.onclick = function(){
		var start = txt.selectionStart;
		txt.value = txt.value.substr(0, start) + "[bb][/bb]" + txt.value.substr(start);
		txt.setSelectionRange(start+4, start+4);
		txt.focus();
	}
	panel.appendChild(b0);

	var b1 = document.createElement('div');
	b1.style.width = b1.style.height = "22px";
	b1.style.background = "url('./icons/text-italic.png')";
	b1.style.cssFloat = "left";
	b1.onclick = function(){
		var start = txt.selectionStart;
		txt.value = txt.value.substr(0, start) + "[ii][/ii]" + txt.value.substr(start);
		txt.setSelectionRange(start+4, start+4);
		txt.focus();
	}
	panel.appendChild(b1);
}
