
//-- Für die Buch-Auswahl nach Autor, Titel:
$('#booksearch_head span').click(function() {
	$(this).addClass('pressed').siblings().removeClass('pressed');
	var type = $('.type.pressed').data('type');
	var letter = $('.letter.pressed').text();
	if (type && letter) { window.location.href = 'books.php?type=' + type + '&letter=' + letter; }
});

//-- Für die Advanced Search:
if ($('#advanced').length) {
	$('#advanced span.connect').click(function() {
		$('#advanced span.connect').removeClass('pressed');
		$(this).addClass('pressed');
		$('input#connect').val( $(this).data('type') );
	});
	$('#advanced span.field').click(function() {
		$(this).toggleClass('pressed');
		$('input#' + $(this).data('type')).val($(this).hasClass('pressed') ? 1 : 0);
	});
	$("#advanced input#books").tokenInput('includes/autocomplete.php', {hintText: 'Type in a book name or leave empty to search in all publications.', queryParam : 'books'});;
	
	$('#advancedsearchform').submit(function() {
		if ($('#advancedsearchform input.inputtext').val() == '') {
			alert('Please enter a search term.');
			return false;
		} else if ($('#advanced span.field.pressed').length == 0) {
			alert('You must select at least one search option.');
			return false;
		}
	});
}

$('#searchform').submit(function() {
	if ($('#searchform input.inputtext').val() == '') {
		alert('Please enter a search term.');
		return false;
	}
});


//-- nachdem Seite geladen wurde
$(window).load(function() {

	//-- SoftScroll zur passenden Kategorie bei Laden der Seite
	if ($('#tree li#scrollhere').length) {
		var ziel = $('#tree li#scrollhere');
		$('html, body').animate({
			scrollTop: $(ziel).offset().top - 150
		}, 900);
		ziel.find('a:first').effect('highlight', {color : '#2cba3d'}, 3000);
	}

	//-- SoftScroll zu markiertem Eintrag bei Laden der Seite
	if ($('#entries tbody tr.content.highlight').length) {
		var ziel = $('#entries tbody tr.content.highlight:first');
		$('html, body').animate({
			scrollTop: $(ziel).offset().top - 100
		}, 900);
	}

	//-- Categories laden zum Ausklappen:
	if ($('table#entries').length) {
		entries = new Array();
		$('table#entries tr.content').each(function() {
			entries.push($(this).data('id'));
		});
		$.ajax({
			type: 'POST',
			url: 'includes/loadcategories.php',
			data: {'entries' : entries},
			dataType : 'json',
			success: function(data){
				$.each(data, function(index, value) {
					$('tr[data-id="' + index + '"]').find('.catContainer').html(value);
				});
			}
		});
	}
	
});

$('table#entries th.categories').click(function() {
	if ($('.catContainer:hidden').length) {
		$('.catContainer').show();
		$('.showcat').hide();
	} else {
		$('.catContainer').hide();
		$('.showcat').show();	
	}
});
$('div.showcat').click(function(e) {
	$(this).hide().siblings().show();
	$('html,body').scrollTop( $(this).siblings('div:first').offset().top - e.clientY );
});

//-- Tabellen(Container)breite fixieren wegen Filter-Stichwortsuche
$('#entries_filter input').live('focus', function() {
	$('#list').css({ 'width' :  $('#list').outerWidth() });
});
$(window).resize(function() {
	$('#list').css({ 'width' : '' });
});

//-- x-Button für Filter-Stichwortsuche
$('#entries_filter input').live('keyup', function() {
	if ($(this).val() && $('#entries_filter div#xButton').length == 0) {
		$(this).after('<div id="xButton" class="sprite icon_x"></div>');
	}
});
$('#entries_filter div#xButton').live('click', function() {
	$(this).remove();
	$('#entries_filter input').val('').keyup();
});


//-- Highlight-Funktion von Zeilen
$('#entries tbody td').not('.categories').click(function() {
    var this_tr = $(this).parent();
	var thisID = this_tr.data('id');
	if (this_tr.hasClass('highlight')) {
		this_tr.removeClass('highlight').effect('highlight', {color : '#2cba3d'}, 300);
		var reg = new RegExp('(,|&highlight=)' + thisID + '(,|$)');
		var replacement = (document.URL.search(new RegExp('&highlight=' + thisID + ',')) > 0) ? '$1' : '$2';
		history.pushState({ show: 'show'}, '', document.URL.replace(reg, replacement) );
	} else {
		this_tr.addClass('highlight').effect('highlight', {color : '#2cba3d'}, 1000);
		var url_add = (document.URL.search(/&highlight=/) > 0) ? ',' + thisID : '&highlight=' + thisID;
		history.pushState({ show: 'show'}, '', document.URL + url_add );
	}
});
//-- Highlighting soll nicht ausgelöst werden beim Klick auf Links:
$('#entries tbody td a').click(function(event) {
	event.stopPropagation();
});



$(document).ready(function(){	
	
	if ($('#advanced .inputtext').length) {
	   $('#advanced .inputtext').focus();
    } else if ($('#loginform #username').length) {
        $('#loginform #username').focus();
    } else {    
        $('#navi .inputtext').focus();
    }

	//-- Accordion auf der BookSeite
	$('.accordion').accordion({ active: false, autoHeight: false, collapsible: true });


	//-- AutoComplete bei Stichworksuche
	$('input.autocomplete').autocomplete({
		source: 'includes/autocomplete.php',
		minLength: 2
	});


	//-- Tree Ausklapp-Funktion
	if ($('div#tree').length) {
		$('#tree li > ul').each(function(i) {
			var parent_li = $(this).parent('li');
			var sub_ul = $(this).remove();
			parent_li.wrapInner('<a/>').find('a').click(function() {
				sub_ul.slideToggle();
			});
			parent_li.append(sub_ul);
		});
	}


	//-- enlarge Cover-Images of books
	$('.coverimg').click(function() {
    	var url = 'covers/' + $(this).attr('id');
    	if ($(this).attr('src') == url + 'a.jpg') {
        	$(this).attr({'src' : url + '.jpg', 'title' : 'Click to enlarge'})
        		   .animate({ width: $(this).data('original')}, 1000 );
    	} else {
        	$(this).attr({'src' : url + 'a.jpg', 'title' : 'Click to shrink'})
        		   .animate({ width: $(this).data('big')}, 1000 );
    	}
	});


	//-- Tabellen-Plugin
	if ($('table#entries').length) {
		$('#entries').dataTable({
			'bAutoWidth': false,
			'bInfo' : false,
			'bJQueryUI' : true,
			'bPaginate' : false,
			'bSortClasses' : false,
			'aaSorting': [],
			'aoColumnDefs': [ { 'bSortable': false, 'aTargets': ['carc', 'categories', 'comment'] },
							  { 'sType': 'data-sort-string', 'aTargets': [ 'creators', 'title', 'book'] },
							  { 'sType': 'numeric', 'aTargets': [ 'page' ] } ],
			'sDom': '<"H"f>t'
		});
		//-- dataTable plugin für die title-string-suche
		jQuery.fn.dataTableExt.oSort['data-sort-string-asc']  = function(a,b) {
			var x = a.match(/data-sort="(.*?)"/)[1].toLowerCase();
			var y = b.match(/data-sort="(.*?)"/)[1].toLowerCase();
			return ((x < y) ? -1 : ((x > y) ?  1 : 0));
		};
		jQuery.fn.dataTableExt.oSort['data-sort-string-desc'] = function(a,b) {
			var x = a.match(/data-sort="(.*?)"/)[1].toLowerCase();
			var y = b.match(/data-sort="(.*?)"/)[1].toLowerCase();
			return ((x < y) ?  1 : ((x > y) ? -1 : 0));
		};
	}
	
});


//////////////////////////////////////////////
//// Damit es auf dem iPhone funktioniert:////
//////////////////////////////////////////////

function touchHandler(event) {
    var touches = event.changedTouches,
    first = touches[0],
    type = "";
     switch(event.type) {
       case "touchstart": type = "mousedown"; break;
       case "touchmove":  type="mousemove"; break;        
       case "touchend":   type="mouseup"; break;
       default: return;
    }
	var simulatedEvent = document.createEvent("MouseEvent");
    simulatedEvent.initMouseEvent(type, true, true, window, 1, 
                          first.screenX, first.screenY, 
                          first.clientX, first.clientY, false, 
                          false, false, false, 0/*left*/, null);
	first.target.dispatchEvent(simulatedEvent);
	event.preventDefault();
}

function init() {
    document.addEventListener("touchstart", touchHandler, true);
    document.addEventListener("touchmove", touchHandler, true);
    document.addEventListener("touchend", touchHandler, true);
    document.addEventListener("touchcancel", touchHandler, true);    
}
//////////////////////////////////////////////
//////////////////////////////////////////////
//////////////////////////////////////////////
