
var sortable = {

	init: function(settings) {

		sortable.config = {
			$obj: $("table#sortable"),
		}
		
		$.extend( sortable.config, settings );	

		if(!sortable.config.$obj.length) return;

		sortable.tableRows = $('tbody tr',sortable.config.$obj);
		
		sortable.onReady();
	
	},
	
	replaceSpecials: function(str) {
		var specials = {"ö":"oe","ä":"ae","ü":"ue","ß":"ss"};
		for (var char in specials) {
			var regExp = new RegExp(char,"g");
			str = str.replace(regExp,specials[char]);
		}
		return str;
	},
	
	execute: function($this, index) {
		var elements = sortable.tableRows.get();
		var isNumeric = $this.hasClass("numeric");
		elements.sort(function(a, b) {
			var sortA = sortable.replaceSpecials($(a).children('td').eq(index).text().toLowerCase());
			var sortB = sortable.replaceSpecials($(b).children('td').eq(index).text().toLowerCase());
			var num;
			sortable.asc ? num = 1 :num = -1;
			if (isNumeric) return sortable.asc ? sortA - sortB : sortB - sortA;
			return (sortA == sortB) ? 0 : (sortA > sortB) ? num : num * -1;
		});
		for (var tr in elements) {
			$('tbody',sortable.config.$obj).append(elements[tr]);
		}
	},
	
	onReady: function() {
		sortable.config.$obj.each(function() {
			$('tbody tr:even', sortable.config.$obj).addClass("even");
			var th = $('th', sortable.config.$obj);
			th.each(function(index) {
				sortable.asc = false;
				$(this).click(function() {
					sortable.asc ? sortable.asc = false : sortable.asc = true;
					th.removeClass("desc asc");
					sortable.asc ? $(this).addClass("asc") : $(this).addClass("desc");
					sortable.execute( $(this), index );
					$('tbody tr', sortable.config.$obj).removeClass("even");
					$('tbody tr:even', sortable.config.$obj).addClass("even");
				});
			});
		});
	}
}

$(document).ready(sortable.init);
