// funkcja poprawnie sortująca liczby; ukradziona z 
// http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:sort
function numerycznie(a,b) {
	if(a[0] > b[0])
		return 1;
	if(a[0] < b[0])
		return -1;
	return 0;
}

// zmodyfikowane powyższe dla alfabetu
function alfabetycznie(a,b) {
	if(a[3].toLowerCase() > b[3].toLowerCase())
		return 1;
	if(a[3].toLowerCase() < b[3].toLowerCase())
		return -1;
	return 0;
}


var lista = new Array();
var przycisk = document.getElementById('przycisk');

function wezListe(listaID) {
	var teksty = document.getElementById(listaID).getElementsByTagName('li');
	// tworzy wielowymiarową tablicę, której każdy element zawiera informacje o jednym z tekstów. Informacje to w kolejności:
	// — data w formacie przyjaznym do sortowania
	// — href
	// — title
	// — tresc wyswietlana na stronie
	for (i=0; i<teksty.length; i++) {
		// data
		var data = teksty[i].childNodes[0].firstChild.nodeValue;
		nowaData = data.replace(/\[(\d+)\.(\d+)\.(\d+)\]/gi, "$3$2$1");
		var wart = new Array();
		wart[0] = nowaData;
		// mówiące za siebie
		wart[1] = teksty[i].childNodes[1].getAttribute("href");
		wart[2] = teksty[i].childNodes[1].getAttribute("title");
		// treść linka
		wart[3] = teksty[i].childNodes[1].firstChild.nodeValue;

		lista[i] = Array(wart[0], wart[1], wart[2], wart[3]);
	}
return lista;
}

function podmienListe(listaID) {
	var teksty = document.getElementById(listaID).getElementsByTagName('li');
	for (i=0; i<lista.length; i++) {
		var data = lista[i][0].replace(/(\d\d)(\d\d)(\d\d)/gi, "[$3.$2.$1]");
		teksty[i].childNodes[0].firstChild.nodeValue = data;
		teksty[i].childNodes[1].setAttribute('href', lista[i][1]);
		teksty[i].childNodes[1].setAttribute('title', lista[i][2]);
		teksty[i].childNodes[1].firstChild.nodeValue = lista[i][3];
	}
}

function uporzadkuj(listaID,jak) {
	var przycisk = document.getElementById('przycisk');
	wezListe(listaID);
	if (jak == "data") {
		lista.sort(numerycznie);
		przycisk.firstChild.nodeValue = 'uporządkuj alfabetycznie';
		przycisk.onclick = function () {
			uporzadkuj('artykuly', 'alfabet');
		}
}
	if (jak == "alfabet") {
		lista.sort(alfabetycznie);
		przycisk.firstChild.nodeValue = 'uporządkuj wg daty';
		przycisk.onclick = function () {
			return uporzadkuj('artykuly', 'data');
		};
	}
	podmienListe(listaID);
}

window.onload = function()
{
	document.getElementById('przycisk').onclick = function() { 
		return uporzadkuj('artykuly', 'data'); 
	};
}
