$(function() {
	var pageId = 1;
	var page = jQuery('#cr_ajax_searchbox_page').attr('value');
	if(page) {
		pageId = page;
	}
	
	var sectionPid = 0;
	var section = jQuery('#cr_ajax_searchbox_sections').attr('value');
	if(section) {
		sectionPid = section;
	}
	
	var languageId = 0;
	var language = jQuery('#cr_ajax_searchbox_lang').attr('value');
	if(language) {
		languageId = language;
	}
	
	var mediaId = -1;
	var media = jQuery('#cr_ajax_searchbox_media').attr('value');
	if(media) {
		mediaId = media;
	}
	
	jQuery('#cr_ajax_searchbox_sword').autocomplete({ 
		source: function(request, response) {
			jQuery.ajax({
				url: 'index.php?eID=cr_ajax_searchbox',
				dataType: 'json',
				type: 'POST',
				data: {
					id: pageId,
					sId: sectionPid,
					lId: languageId,
					mId: mediaId,
					sw: 3,
					ml: 3,
					mc: 10,
					wc: 1,
					term: request.term
				},
				beforeSend: function(result) {
					jQuery('#cr_ajax_searchbox_submit').addClass('ajax_loading');
				},
				success: function(result) {
					jQuery('#cr_ajax_searchbox_submit').removeClass('ajax_loading');
					
					response(jQuery.map(result.data, function(item) {
						return {
							label: item.name + ' (' + item.count + ' Treffer)',
							value: item.name
						}
					})
				)}
			})
		},
		minLength: 3,
		delay: 600,
		select: function(event, ui) {
			jQuery('#cr_ajax_searchbox_sword').val(ui.item.value);
			jQuery('#cr_ajax_searchbox').submit();
		}
	});
});