function sortable(table) {
	var $ = jQuery;
	if (!sortable.sortColumn) {
		sortable.sortColumn = {table : 0};
		sortable.sortAsc = {table: true};
	}
	var headerText = new Array();
	var headerRow = $(table).find('tr')[0];
	$(headerRow).find('th').each(function(i, el) {
		var link = document.createElement('a');
		headerText[i] = $(el).text();
		$(link).text(headerText[i]);
		$(link).click(function() {
			var rows = $(table).find('tr').get();
			rows.shift(); // remove header row which we don't want to sort
			//console.log(rows);
			if (sortable.sortColumn[table] == i) {
				if ((sortable.sortAsc[table] = !sortable.sortAsc[table])) {
					if ($(el).hasClass('date')) {
						rows.sort(makeDateSortAsc(i));
					} else {
						rows.sort(makeSortAsc(i));
					}
				} else {
					if ($(el).hasClass('date')) {
						rows.sort(makeDateSortDesc(i));
					} else {
						rows.sort(makeSortDesc(i));
					}
				}
			} else {
				
				sortable.sortColumn[table] = i;
				sortable.sortAsc[table] = true;
				if ($(el).hasClass('date')) {
					rows.sort(makeDateSortAsc(i));
				} else {
					rows.sort(makeSortAsc(i));
				}
			}
			$(table).append(headerRow);
			for(j=0; j < rows.length; j++) {
				$(table).append(rows[j]);
			}
			//console.log($(link));
			//console.log($(link).text());
			$(headerRow).find('th').each(function(k, elem) {
				$(elem).find('a').text(headerText[k]);
			});
			$(link).html(headerText[i] + (sortable.sortAsc[table] ? ' <strong style="color:black">&or;</strong>' : ' <strong style="color:black">&and;</strong>') );
		});
		$(link).css({'text-decoration': 'none'});
		$(el).text('').append(link);
		$(el).css({cursor: 'pointer'});
	});
	$($(headerRow).find('a')[0]).click();
}

function makeSortAsc(i) {
	return function sortAsc(row1, row2) {
		var $ = jQuery;
		return ($($(row1).find('td')[i]).text().toLowerCase() < $($(row2).find('td')[i]).text().toLowerCase()) ? -1 : 1;
	}
}

function makeDateSortAsc(i) {
	return function dateSortAsc(row1, row2) {
		var $ = jQuery;
		return (Date.parse($($(row1).find('td')[i]).text()) < Date.parse($($(row2).find('td')[i]).text())) ? -1 : 1;
	}
}

function makeDateSortDesc(i) {
	return function dateSortDesc(row1, row2) {
		var $ = jQuery;
		return (Date.parse($($(row1).find('td')[i]).text()) > Date.parse($($(row2).find('td')[i]).text())) ? -1 : 1;
	}
}

function makeSortDesc(i) {
	return function dsortDesc(row1, row2) {
		var $ = jQuery;
		return ($($(row1).find('td')[i]).text().toLowerCase() > $($(row2).find('td')[i]).text().toLowerCase()) ? -1 : 1;
	}
}

jQuery(document).ready(function($) {
	$('.itemList').each(function(i, el) {
		sortable(el);
	});	
});

