


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.initPagination();
		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 tableElements = sortable.tableRows.get();
		var isNumeric = $this.hasClass("numeric");
		tableElements.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 tableElements) {
			$('tbody',sortable.config.$obj).append(tableElements[tr]);
		}
	},

	initPagination: function() {
		sortable.current = 0;
		sortable.numMax = 3;
		sortable.pages = Math.ceil(sortable.tableRows.length / sortable.numMax);
		sortable.msg = $("#tools #msg");
		sortable.update();

		$("#up").click(function(e) {
			e.preventDefault();
			(sortable.current < sortable.pages -1) ? sortable.current += 1 : sortable.current = sortable.pages -1;
			sortable.update();
		})
	
		$("#down").click(function(e) {
			e.preventDefault();
			(sortable.current > 0) ? sortable.current -= 1 : sortable.current = 0;
			sortable.update();
		})
	},
		
	update: function() {
		var tableRows = $('tbody tr',sortable.config.$obj);
		sortable.msg.text("Seite: " + (sortable.current + 1));
		tableRows.hide().slice(sortable.current * sortable.numMax,(sortable.current + 1) * sortable.numMax).show();
	},
	
	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");
					sortable.update();
				});
			});
		});
	}
}

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