var http_request = false;
function makePOSTRequest(url, parameters) {
	http_request = false;
	if (window.XMLHttpRequest) {
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/html');
		}
	}
	else if (window.ActiveXObject) {
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e)
			{}
		}
	}
	if (!http_request) {
		alert('Cannot create XMLHTTP instance');
		return false;
	}
	
	http_request.onreadystatechange = alertContents;
	http_request.open('POST', url, true);
	http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http_request.setRequestHeader("Content-length", parameters.length);
	http_request.setRequestHeader("Connection", "close");
	http_request.send(parameters);
}

function alertContents() {
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			fadeIn('komentarze');
			result = http_request.responseText;
			document.getElementById('komentarze').innerHTML=result;
		}
		else {
			alert("Wystąpił nieoczekiwany błąd.");
		}
	}
}

function getKom(cmd,page) {
	document.getElementById('komentarze').innerHTML="<h3>Wczytuję listę komentarzy, proszę czekać...</h3>";
	poststr =	"cmd=" + cmd + "&page=" + page;
	makePOSTRequest("_komentarze.php", poststr);
}

function checkKom() {
	var loc = document.location.href;
	if (inStr(loc, "#") != -1) {
		var parsed = parseURLKom();
		var cmd = parsed[0];
		var page = parsed[1];
		
		komentarz(cmd, page);
	} else {
		document.location.href="#lista,1";
		komentarz("lista", "1");
	}
}

function parseURLKom() {
	var location = document.location.href;
	for (var a=0; a < location.length; a++) {
		var hash = location.substring(a, a+1);
		if (hash == "#") {
			var anch = location.substring(a+1, location, length);
		}
	}
	
	for(var c=0; c<anch.length; c++) {
      var coma = anch.substring(c, c+1);
      if(coma == ",") {
        var coma_position = c;
      }
    }
	
	var cmd = anch.substring(0, coma_position);
	var page = anch.substring(coma_position+1, anch.length);
	
	return [cmd, page];
}

function komentarz(cmd, page) {
	setOpacity("komentarze", 100);
	getKom(cmd, page);
}

function showKomentarze(data) {
	$("#komentarze").html(data)
	                .fadeIn("slow");
}

function addComment() {
	$("#komentarze").fadeOut("slow");
	$.post("_komentarze.php", $("#addComment").serialize(), function (data) {showKomentarze(data);}, 'html');
}

function showCommentPage(n) {
	$("#komentarze").fadeOut("fast");
	$.post('_komentarze.php', {cmd: 'lista', page: n}, function (data) {showKomentarze(data);}, 'html');
}

$(document).ready(function() {
	$("#komentarze").fadeOut("fast");
	$.post('_komentarze.php', {cmd: 'lista', page: '1'}, function (data) {showKomentarze(data);}, 'html');
});

