/*******************************************************************************************
 * jquery.wh.typeahead.js
 * Plugin ersetzt Inputfelder durch Typeahead Ajax
 * @autor   Cornelius Rittner
 * @date    09.12.2010
 * @version 1.0
 * @lastmodified 09.11.2011, DK (Ausblenden wenn keine Ergebnisse)
 *
 * Beispiel für Typeahead XML Code:
	<ajax_response>
		<success>true</success>
		<message></message>
		<results>xmlFormat(Ihre Suche ergab eine Million Ergebnisse!<br /><a href="http://www.google.de">zu Google</a>)#</results>
	</ajax_response>
 *
 * Um beim Laden der Webseite gewünschten Inputs durch die Ajax-Versionen zu ersetzen,
 * muss die Funktion in die allgemeine Javascript-Datei der Seite eingesetzt werden.
 * Beispiel wie das aussehen kann:
 *
	$(document).ready(function() {
		$("#schnellsuche input[name='suche']").typeahead({ ajaxurl: "/ajax_suche.html" });
	});
 *
 *******************************************************************************************/
jQuery.fn.typeahead = function(set_options) {
	/***************************************************************************************
	 * Default Options
	 ***************************************************************************************/
	if (set_options == null) set_options = {};
	var options = {
		ajaxurl:				set_options.ajaxurl					|| "/ajax/typeahead"
		,searchparameter:		set_options.searchparameter		|| "s"
		,defaultstring:		set_options.defaultstring			|| "Suchen"
		,width:					set_options.width						|| 0
		,left:					set_options.left						|| 0
		,top:						set_options.top						|| 0
	};
	/***************************************************************************************
	 * Initialisierung
	 ***************************************************************************************/
	$(this).each(function(){
		var $input = $(this);
		var timeouts = new Object();
		var ajax_link = -1;
		var hide_results_focus = false;	// Wenn Focus auf dem Eingabefeld liegt, Ergebnis anzeigen
		var hide_results_hover = true;	// Wenn Focus auf der Ergebnisliste liegt, Ergebnis anzeigen

		$input.attr({ autocomplete:"off", value: options.defaultstring });

		// Focus Input
		$input.focus(function(){
			if ($(this).attr("value") == options.defaultstring) {
				$(this).attr("value","");
			}
			hide_results_focus = false
		});

		// Blur Input
		$input.blur(function(){
			if ($(this).attr("value") == "") {
				$(this).attr("value",options.defaultstring);
			}
			hide_results_focus = true;
			timeouts["ajax_result"] = window.setTimeout(function(){
				if ($('#ajax_results') && hide_results_focus && hide_results_hover) {
					$('#ajax_results').fadeOut();
				}
			},300);
		});

		// KeyUp on Input (when key is released)
		$input.keyup(function(e){
			var key = e.charCode || e.keyCode || 0;
			if (key != 37 && key != 38 && key != 39 && key != 40 && key != 13) {
				// do nothing when arrowkeys (37-40) or enter, else clear Timeout and run Ajax
				window.clearTimeout(timeouts["ajax_search"]);
				timeouts["ajax_search"] = window.setTimeout(function(){
						if ($input.val().length >=2) {
							var timestamp = new Date();
							$.ajax({
								type: 'GET',
								url: options.ajaxurl,
								data: options.searchparameter + '=' + encodeURIComponent($input.val()) + '&timestamp=' + encodeURIComponent(timestamp*1),
								success: function(xml,textStatus) {
									ajax_link = -1;
									if ($('#ajax_results').length == 0) {
										window.clearTimeout(timeouts["ajax_result"]);
										$('body').append('<div id="ajax_results"></div>');
										$('#ajax_results').css({ 'background-color': 'white', position: 'absolute', left: ((options.left > 0) ? options.left : $input.offset().left) + 'px', top: ((options.top > 0) ? options.top : ($input.offset().top + $input.height() + 2)) + 'px', width: ((options.width > 0) ? options.width : $input.width()) + 'px', 'z-index': 30, display: 'none'});
									}
									if ($('success', xml).text() == 'true') {
										// Suche erfolgreich
										$('#ajax_results').html($('results', xml).text());
									} else if ($('success', xml).text() == 'false') {
										//$('#ajax_results').html($('message', xml).text());
										$('#ajax_results').fadeOut();
									}
									if ($('#ajax_results').css("display") == "none") {
										$('#ajax_results').slideDown();
									}
									$('#ajax_results').hover(function(){
										hide_results_hover = false;
									},function(){
										hide_results_hover = true;
										timeouts["ajax_result"] = window.setTimeout(function(){
											if ($('#ajax_results') && hide_results_focus && hide_results_hover) {
												$('#ajax_results').fadeOut();
											}
										},300);
									});
								},
								error: function (XMLHttpRequest, textStatus, errorThrown) {}
							});
						}
				},200);
			}
		});

		// KeyDown on Input (when keys are pressed, e.g. arrowkeys)
		$input.keydown(function(e){
			var key = e.charCode || e.keyCode || 0;
			if (key == 40 && $("#ajax_results").length != 0) {
				// arrowkey down
				if (ajax_link == -1) {
					ajax_link = 0;
				} else {
					// remove highlight from element
					$('#ajax_results a:eq('+ajax_link+')').removeClass("ajaxfocus");
					if (ajax_link == $('#ajax_results a').length-1) {
						ajax_link = 0;
					} else {
						ajax_link++;
					}
				}
				// highlight element
				$('#ajax_results a:eq('+ajax_link+')').addClass("ajaxfocus");
			} else if (key == 38) {
				// arrowkey up
				if (ajax_link == -1) {
					ajax_link = 0;
				} else {
					// remove highlight from element
					$('#ajax_results a:eq('+ajax_link+')').removeClass("ajaxfocus");
					if (ajax_link == 0) {
						ajax_link = $('#ajax_results a').length-1;
					} else {
						ajax_link--;
					}
				}
				// highlight element
				$('#ajax_results a:eq('+ajax_link+')').addClass("ajaxfocus");
			} else if (key == 13 && ajax_link != -1) {
				// enter key, sets Window-Location
				window.location.href = $('#ajax_results a:eq('+ajax_link+')').attr("href");
				return false;
			}
		});

	});

	return this;
}
