jQuery.noConflict();

jQuery.expr[':'].icontains = function(obj, index, meta, stack){
	var regex = new RegExp(jQuery.trim(meta[3]).replace(/\s+/g,'[\\s\\wäöüß.,;/()]+\\b'), 'i'),
			text = jQuery.trim(obj.textContent || obj.innerText || jQuery(obj).text() || '').replace(/[®]/g,'').replace(/^\s+|\s{2,}/g,' ');
	return regex.test(text);
};
jQuery.fn.ajaxSubmit = function(dataType, callback, extend) {
	var form = jQuery(this).is('form') ? jQuery(this) : jQuery(this).closest('form'),
			params = {
		  	url: form.attr('action'),
		  	type: form.attr('method'),
		  	data: form.serializeArray(),
				beforeSend: function(){if (!(jQuery.browser.msie && (7 >= parseInt(jQuery.browser.version)))){form.closest('table').addClass('loading');}},
				complete: function(){form.closest('table').removeClass('loading');}
		  };
	if ('undefined' !== typeof(dataType)) {
		params.dataType = dataType;
	}
	if ('function' === typeof(callback)) {
		params.success = callback;
	}
	if ('function' === typeof(extend)) {
		extend = extend();
	}
	if ('object' === typeof(extend)) {
		jQuery.extend(params.data, extend);
	}
	jQuery.ajax(params);
};

function formatTitle(title, currentArray, currentIndex, currentOpts) { return title; };
function fancyRearrangeElements() {
	var wrapper = jQuery('#fancybox-inner'),
			title = wrapper.find('.title'),
			links = wrapper.find('.links'),
			w_title = (jQuery('#fancybox-top-title').length ? jQuery('#fancybox-top-title') : jQuery('<div id="fancybox-top-title" class="fancybox-title-top"></div>')).html(title.html()),
			w_links = jQuery('#fancybox-title');
	wrapper.before(w_title);
	w_links.addClass('links').css('width', function(i,v){return parseInt(v)-20;}).html(links.html());
	var h = parseInt(w_title.outerHeight()+w_links.outerHeight());
	wrapper.css({'height': function(i, v){return parseInt(v) - h;}, 'top': function(i, v){return parseInt(v)+w_title.outerHeight()+10;}});
	title.remove();links.remove();
}
function fancyParseData(data) {
	var wrapper = jQuery('#fancybox-inner'),
			title = wrapper.find('.title'),
			links = wrapper.find('.links'),
			w_title = (jQuery('#fancybox-top-title').length ? jQuery('#fancybox-top-title') : jQuery('<div id="fancybox-top-title" class="fancybox-title-top"></div>')).html(title.html()),
			w_links = jQuery('#fancybox-title');
	wrapper.before(w_title);
	w_links.addClass('links').css('width', function(i,v){return parseInt(v)-20;}).html(links.html());
	var h = parseInt(w_title.outerHeight()+w_links.outerHeight());
	wrapper.css({'height': function(i, v){return parseInt(v) - h;}, 'top': function(i, v){return parseInt(v)+w_title.outerHeight()+10;}});
	title.remove();links.remove();
}

jQuery.fn.pagination = function(options){
	var table = jQuery(this);

	if ( table.length ) {
		var rows = table.find('tbody tr'),
				pagination = table.find('tfoot .pagination').empty(),
				eventScrollId = "scroll." + Math.random().toString().substring(10),
				eventKeyId = "keydown." + Math.random().toString().substring(10);

		var options = jQuery.extend({
			per_page_values: [5, 10, 25],
			show_per_page: 10,
			current_page: 0,
			mode: 'init',
			num_items: rows.size(),
			num_pages: 1,
			num_links: 5,
			scroll_active: false,
			key_codes: [37, 39]
		} || {}),
		ajax = false;

		function initPagination() {
			initAjax();
			initScroll();
			initFilter();
			if (false === ajax) {
		  	rebuildData();
		  }
			table.bind('rebuild', rebuildData);
			table.bind('reset', function(){setPage(0)})
		};

		function initAjax() {
			var form = table.find('.ajax-helper form'),
					tab = table.parent('div'),
					id = table.attr('id'),
					hash = window.location.hash.replace(/#/, ''), current_tab = hash.replace(/,.*$/, ''), current_page = (!tab.hasClass('hidden') && (m = hash.match(/,(\d+)/))) ? m[1] : 1;
			if (!form || (!table.is('.ajax') && 50 > parseInt(form.find('data[rows]').val()))) {
		  	return;
		  }
			table.addClass('ajax');
			if(null === form.data('init')) {
				if (window.location.hash.length && 1 < current_page) {
					options.current_page = parseInt(current_page)-1;
				}
				options.num_items = form.find('data[rows]').val();
				form
					.append(jQuery('<input />').attr({'id': id+'-ajax-per-page', 'name': 'data[per-page]', 'type': 'hidden', 'value': options.show_per_page}))
					.append(jQuery('<input />').attr({'id': id+'-ajax-current-page', 'name': 'data[current-page]', 'type': 'hidden', 'value': options.current_page}))
					.attr('action', form.find('[name=data[uri]]').val())
					.ajaxSubmit(null, replacePerAjax, getFilterData);
				initSortPerAjax();
				form.data('init', true);
			}
			ajax = {'init': true, 'form': form, 'sort': form.find('[name=data[sort_type]]').val()};
		};

		function initSortPerAjax() {
			var sorter = table.find('thead .sort a');
			if('function' === typeof(jQuery(table).tablesorter)) {
				jQuery(table).tablesorter = null;
			}
			sorter.unbind('click').click(function(evt){
				var form = jQuery(ajax.form),
						c_sort = jQuery(ajax.form).find('[name=data[sort_type]]').val(),
						sort = jQuery(this).attr('rel'),
						p = jQuery(this).parent(),
						dir = (p.hasClass('desc') || c_sort !== sort) ? '' : 'desc';				
				('desc' === dir) ? p.addClass('desc') : p.removeClass('desc');
				form.find('[name=data[sort_type]]').val(sort);
				form.find('[name=data[sort_dir]]').val(dir.toUpperCase());
				form.ajaxSubmit(null, replacePerAjax, getFilterData);
				return evt.preventDefault();
			});
		};

		function replacePerAjax(respond) {
			var html = ('object' === typeof(respond)) ? respond.html : respond,
					scores = ('object' === typeof(respond)) ? respond.rows : false;
			if (undefined != html) {
		  	table.find('tbody').html(html);
				if ('hide' === scores) {
					var current = $('ul.tabs li.active a'), hash = window.location.hash.replace(/#/, ''), current_tab = hash.replace(/,.*$/, ''), current_page = (m = hash.match(/,(\d+)/)) ? m[1] : 1,
							div = table.parent('div.tab'), tab = jQuery('ul.tabs li a[rel="'+div.attr('id')+'"]').parent('li'), qu = 'li'+(hash.length?' a[href="#'+current_tab+'"]':':first-child a'), next = tab.parent('ul').find(qu);
					if (!next.length) { next = tab.parent('ul').find('li:first-child a'); }
					if (next.attr('rel') == tab.find('a').attr('rel')) { var nn = next.parent('li').next('li').find('a'); if (nn.length) { next = nn; } }
					tab.remove();
					div.remove();
					if (next.length) { next.click(); }
					return false;
				}
				else if (false!==scores) {
					setCounter(scores);
				}
		  	if (jQuery.fn.fancybox) {
		  		table.find('tbody a[rel="quickInfo"]').each(function(){
						var more = jQuery('<a class="more-info" href="'+jQuery(this).attr('href')+'">?</a>')
								.attr('title', "Schnell-Info zum Kurs")
								.data({
				  				'ajax-data': { 'id': jQuery(this).attr('href') },
				  				'ajax-uri': 'ajax/get-course-data.php'
				  			})
								.click(function(){if(pageTracker){pageTracker._trackPageview(jQuery(this).attr('href'));/*pageTracker._trackEvent('Courses', 'quickInfo', jQuery(this).attr('href'));*/}});
						more.fancybox({
		  				'ajax': {
		  					type: 'post',
		  					data: jQuery(more).data('ajax-data')
		  				},
		  				'href': jQuery(more).data('ajax-uri'),
							'centerOnScroll': true,
							'titlePosition': 'inside',
							'onAjaxComplete': fancyParseData,
							'onStart': function(){jQuery('body').addClass('fancybox-showing');},
							'onClosed': function(){jQuery('body').removeClass('fancybox-showing');}
		  			});
		  			jQuery(this).removeAttr('rel').after(more).remove();
		  		});
		  	}
		  }
			jQuery(ajax.form).find('[name=data[init]]').remove();
			if (jQuery('select.filter-locations').length) jQuery(ajax.form).find('.options-loc_id').remove();
			table.removeClass('loading');
		};

		function rebuildData() {
			options.num_items = !ajax ? getRows().size() : jQuery(ajax.form).find('[name=data[rows]]').val();
			options.num_pages = numPages();
			if (ajax) {
				options.current_page = jQuery(ajax.form).find('[name=data[current-page]]').val();
			}
			setPage(options.current_page);
		};

		function getRows() {
			return ( rows = jQuery('tbody tr', jQuery(table)) );
		};

		function getMatchedRows() {
			return rows.filter(":not('.filtered')");
		};

		function numPages() {
			return Math.ceil((!ajax?getMatchedRows().size():options.num_items)/options.show_per_page);
		};

		function initFilter() {
			var filter = false;
			if (filter = table.find('thead .filter-text input')) {
				//filter.data('init_value', filter.val());
				filter.data('init_value', 'Schnellsuche');
				filter
					.click(function(evt){if(jQuery(this).val() == jQuery(this).data('init_value')){jQuery(this).val('');}})
					.focusout(function(evt){if('' == jQuery.trim(jQuery(this).val())){jQuery(this).val(jQuery(this).data('init_value'));}})
					.bind('keyup', {element: jQuery('thead .filter-locations select', table), method: 'append'}, filterRows);
			}
			if (filter = table.find('thead .filter-locations select')) {
				filter.bind('change', {element: jQuery('thead .filter-text input', table), method: 'prepend'}, filterRows);
			}
			if (filter_reset = table.find('thead .filter-reset')) {
				filter_reset.append(jQuery('<a href="javascript:void(0)" title="Filter zurücksetzen">x</a>').click(resetFilter));
			}
		};
		
		function resetFilter() {
			table.find('tr.filter-set input, tr.filter-set select').val('').change().keyup();
			return false;
		};

		function resetPage() {
			options.current_page = 0;
			jQuery(ajax.form).find('[name=data[current-page]]').val(0);
		}

		function filterRows(evt) {
			if ('object' === typeof(ajax) && ajax.init) {
				if ('undefined'!==typeof(search_timeout)) {
					clearTimeout(search_timeout);
        }
        var $this = this;
        search_timeout = setTimeout(function(){
					search_timeout = undefined;
					resetPage();
          jQuery(ajax.form).find('[name=data[filter]]').val(term);
					jQuery(ajax.form).ajaxSubmit(null, replacePerAjax, getFilterData);
					table.trigger('rebuild');
					return;
        }, 500);	  		
	  	}

			var value = jQuery(this).val().replace(new RegExp('undefined' !== typeof(jQuery(this).data('init_value')) ? jQuery(this).data('init_value')+'\s?' : '', 'i'), ''),
					term = jQuery.trim(value),
					scores = 0;

			if (evt.data && jQuery(evt.data.element).length) {
				var plus_value = jQuery(evt.data.element).val().replace(new RegExp(value+'$','ig'),'').replace(new RegExp('undefined' !== typeof(jQuery(evt.data.element).data('init_value')) ? jQuery(evt.data.element).data('init_value')+'\s?' : '', 'i'), '');
				term = jQuery.trim('prepend' == evt.data.method ? plus_value+' '+value : value+' '+plus_value);
			}

			if ( !term || 3 > term.length ) {
				scores = rows.removeClass('filtered').size();
			}
			else {
				scores = rows.addClass('filtered').filter(":icontains('"+term+"')").removeClass('filtered').size();
				setCounter(scores);
			}
			options.current_page = 0;
			table.trigger('rebuild');
		};

		function getFilterData() {
			return table.find('thead .filter-set').find('input,select').serializeArray();
		};

		function setCounter(count) {
			if ('object' === typeof(ajax) && ajax.init) {
				jQuery(ajax.form).find('[name=data[rows]]').val(parseInt(count));
			}
			if (counter = jQuery(table).find('tfoot .count em')) {
				counter.html(count);
				counter.find('a[rel="reset-filter"]').click(resetFilter);
			}
			table.trigger('rebuild');
		};

		function initScroll() {
			if (options.scroll_active) { table.bind('mousewheel', function(e, delta){ return (0 > delta) ? previous(e) : next(e); }); }
			jQuery(document).unbind(eventKeyId).bind(eventKeyId, function(e) {
				if (e.altKey || e.ctrlKey || 'input' == e.target.nodeName.toLowerCase() ) { return; }

				if (table.parent('div').hasClass('hidden')) { return; }

				if (37 == e.keyCode || 39 == e.keyCode) {
					return (37 == e.keyCode) ? previous(e) : next(e);
				}
				/* else if (38 == e.keyCode || 40 == e.keyCode) {
					return (38 == e.keyCode) ? previous(e) : next(e);
				} */
			});
		}

		function previous(e) {
			var next_page = 0 < options.current_page ? options.current_page -1 : 0;
			setPage(next_page);
			return e.preventDefault();
		};

		function next(e) {
			var next_page = (numPages()-1) > options.current_page ? options.current_page +1 : numPages()-1;
			setPage(next_page);
			return e.preventDefault();
		};

		function setPage(page_id) {
			if ('object' == typeof(page_id)) {
	  		evt = page_id;
	  		page_id = parseInt(evt.data.page_id);
	  	}

	  	var offset = parseInt(page_id) * options.show_per_page,
					old_page = options.current_page;

			if (false !== ajax && ajax.init) {
				if (old_page != parseInt(page_id)) {
					jQuery(ajax.form).find('[name=data[current-page]]').val(parseInt(page_id));
					jQuery(ajax.form).ajaxSubmit(null, replacePerAjax, getFilterData);
				}
				//options.num_items = jQuery(ajax.form).find('[name=data[rows]]').val();
		  }
			else {
		  	getRows().css('display', 'none').filter(":not('.filtered')").slice(offset, offset + options.show_per_page).show();
		  }

			if ('init' == options.mode || old_page != options.current_page) {
				options.current_page = page_id;
				buildLinks();
				window.location.hash = window.location.hash.replace(/,.*$/, '')+(0<options.current_page?','+(parseInt(options.current_page)+1):'');
			}

			if ('object' == typeof(evt)) {
		  	return evt.preventDefault();
		  }
		};

		function setPerPage(per_page) {
			if ('object' == typeof(per_page)) {
				evt = per_page;
	  		per_page = parseInt(evt.data.per_page);
	  	};

			if ( 3 > per_page )
				per_page = 3;
			if ( options.show_per_page == per_page )
				return;

			var new_page = Math.floor((options.show_per_page *options.current_page) /per_page);

			if (false !== ajax && ajax.init) {
				resetPage();
		  	jQuery(ajax.form).find('[name=data[per-page]]').val(parseInt(per_page));
		  	jQuery(ajax.form).ajaxSubmit(null, replacePerAjax, getFilterData);
		  }
			options.show_per_page = per_page;

			initPagination();
			//setPage(new_page);

			if ('object' == typeof(evt)) {
		  	return evt.preventDefault();
		  };
		};

		function buildPerPage() {
			var links = jQuery('<span/>').html('Kurse/Seite: ').addClass('per-page'),
					matchedRows = getMatchedRows().size(), rows = options.num_items;

			jQuery.each(options.per_page_values, function(index, value) {
				if (value > matchedRows && options.per_page_values[index-1] >= rows) {
					return false;
				};
				var link = jQuery('<a/>').addClass('page').html(value).bind('click', {per_page: parseInt(value)}, setPerPage);
				if (options.show_per_page == value) link.addClass('current');
				links.append(link);
			});
			return links;
		};

		function buildPages() {
			var pageNum = numPages(),
					pages = jQuery('<span/>').addClass('pages'),
					offset = Math.floor(options.num_links/2),
					i = 0;
			i = options.current_page - offset;
			if ( pageNum < (i + options.num_links) )
				i -= (i + options.num_links) - pageNum;
			i = (0 > i) ? 0 : i;

			for(j=0;i<pageNum&&j<options.num_links;i++,j++) {
				var link = jQuery('<a/>').addClass('page').html(i+1).bind('click', {page_id: i}, setPage);
				if ( (options.current_page) == i ) link.addClass('current');
				pages.append(link); 
			};
			return pages;
		};
	
		function buildLinks() {
			pagination.empty();

			if ( options.num_items > options.show_per_page ) {
				if ( 0 < options.current_page ) {
					pagination
						.append(jQuery('<a/>').addClass('page-control')
							.html('&laquo;').bind('click', {page_id: 0}, setPage))
						.append(jQuery('<a/>').addClass('page-control')
							.html('&lsaquo;').click(previous));
				};
				pagination
						.append(buildPages());
				if ( options.current_page < numPages() -1 ) {
					pagination
						.append(jQuery('<a/>').addClass('page-control')
							.html('&rsaquo').click(next))
						.append(jQuery('<a/>').addClass('page-control')
							.html('&raquo').bind('click', {page_id: numPages() -1}, setPage));
				};
			};

			pagination.append(buildPerPage());
		};

		('rebuild' === options.mode) ? rebuildData() : initPagination();
	};
};
jQuery(document).ready(function($){$('table.paginate').each(function(){$(this).pagination();});});