/*
 * WGO Autocomplete - jQuery Plugin
 *
 * Example:
 *
 * HTML
 * <form methde="post" ... >
 *    <input type="text" id="search" value="" size="40">
 * </form>
 *
 * Javascript
 *
 * $('#search').wgo_autocomplete({
 *		datasource: 'http://www.d-living.de/search.php'
 *		limit : 10,
 *		width: 250
 * });
 *
 * @author Fstrauss <florian.strauss@wgo-online.com>
 * @version 0.1
 * @date 28.06.2010
 */
(function($){
    if(!$.wgo){
        $.wgo = new Object();
    };

    $.wgo.autocomplete = function(el, options){
        var base = this,
			timer, searchValue, resultContainer,
			template = '<ul id="wgo-autocomplete-search-result"></ul>';


        base.$el = $(el);
        base.el = el;

        base.$el.data("wgo.autocomplete", base);

        base.init = function(){
            base.options = $.extend({},$.wgo.autocomplete.defaultOptions, options);

			base.$el.parent('form').submit(function() {
				base.selectItem();
				base.$el.parent('form').get(0).submit();
				return false;
			})

			base.$el.attr('autocomplete', 'off');

			base.$el.keyup(function(event) {


				if(event.keyCode != 27 && event.keyCode != 38 && event.keyCode != 40 && event.keyCode != 13) {
					clearTimeout(timer);
					timer = setTimeout(function() {

						searchValue = base.$el.val();

						if(searchValue.length > 2) {
							base.getDataFromDatasource(base.$el.val(), base.render)
						}

					},300)
				}

			});

			$('body').click(function() {
				resultContainer.fadeOut('fast');
			})
			$(document).keyup(function(event) {
				if(resultContainer.is(':visible')) {
					event.preventDefault();
					switch(event.keyCode) {
						case 27:
							base.$el.blur();
							$.wgo.autocomplete.hide();
							break;
						case 38:
							base.prevItem();
							break;
						case 40:
							base.nextItem();
							break;
						case 13:
							base.selectItem();
							break;
						default:

					}
					return false;
				}
			})
			$(template)
				.css({
					position :	'absolute',
					width:		(base.options.width) ? base.options.width : base.$el.width()
				})
				.hide()
				.appendTo('body');

			resultContainer = $('#wgo-autocomplete-search-result');

        };
		base.nextItem = function() {

			var activeItem = resultContainer.find('li.active');

			if(activeItem.length == 0) {
				resultContainer.find('li:nth-child(2)').addClass('active');
			}
			activeItem.removeClass('active').next().addClass('active');

		}
		base.selectItem = function() {

			var activeItem = resultContainer.find('li.active');

			if(activeItem.length != 0) {
				base.$el.val(activeItem.find('a').attr('title'))
			}
			//base.$el.parent('form').get(0).submit();
			return false;


		}
		base.prevItem = function() {
			var activeItem = resultContainer.find('li.active');

			if(activeItem.length == 0) {
				resultContainer.find('li:last').addClass('active');
			}
			activeItem.removeClass('active').prev().addClass('active');
		}

		base.render = function(products) {

			resultContainer.empty();

			var notice = $('<li>')
							.addClass('notice')
							.html('Vorschläge zu Ihrer Suche...')
							.appendTo(resultContainer),
				list, link, regexp, replacedString;

			if(products) {
				$(products).each(function(i, item) {
					if(i < base.options.limit) {

						if(item.product_name) {

							
							$(searchValue.split(" ")).each(function(j, part){

								regexp	= new RegExp("("+part+")","gi");
								replacedString = item.product_name.replace(regexp,'<span>$1</span>')
							})

							list	= $('<li>'),
							link	= $('<a href="#">name</a>');

							link
								.attr('title', item.product_name)
								.html(replacedString)

								.click(function(){
									list.addClass('active');
									base.selectItem();
									base.$el.parent('form').get(0).submit();
									return false;
								})



							list
								.append(link)
								.hover(function(){
									$(this).addClass('active');
								}, function() {
									$(this).removeClass('active');
								})
								.appendTo(resultContainer)
						}


					}



				});
				resultContainer
					.css({
						top:	base.$el.offset().top + base.$el.height(),
						left:	base.$el.offset().left
					})
					.slideDown();
			}

		}


		base.getDataFromDatasource = function(searchString,callback) {
			$.ajax({
				url: base.options.datasource,
				dataType: 'jsonp',
				data: {search_string : searchString},
				success: callback
			});

		}

        base.init();
    };

    $.wgo.autocomplete.defaultOptions = {
        datasource: "",
		width: 250,
		limit: 10
    };

	$.wgo.autocomplete.hide = function() {
		$('#wgo-autocomplete-search-result').slideUp();
	}
    $.fn.wgo_autocomplete = function(options){
        return this.each(function(){
            (new $.wgo.autocomplete(this, options));
        });
    };

	$.wgo.clone = function(obj){
		if(obj == null || typeof(obj) != 'object') {
			return obj;
		}
		var temp = new obj.constructor();
		for(var key in obj) {
			temp[key] = clone(obj[key]);
		}
		return temp;
	}


	$(document).ready(function() {
		$('#search_query_keyword').wgo_autocomplete({
			datasource: 'http://www.myfamila.de/search_result_ajax.php'
		});
	});

})(jQuery);

