/**
 * LiveSearch (requires the dimensions plug-in)
 *
 * Applies "live search" to input-fields
 *
 * Usage: jQuery('#q').liveSearch({ajaxURL: '/ajax/search/?q='});
 *
 * @class liveSearch
 * @param {Object} conf, custom config-object
 *
 * Copyright (c) 2008 Andreas Lagerkvist (andreaslagerkvist.com)
 * Released under a GNU General Public License v3 (http://creativecommons.org/licenses/by/3.0/)
 */
 
// Hide all search-results if you click outside them
$(document.body).click(function(event) {
	if(!$(event.target).parents('div.search_container').length) {
		jQuery('div.search_container').hide();
        /* Show existing Content */
        jQuery('div.search_container:last').nextAll().show(); 
	}
});

jQuery.fn.liveSearch = function(conf) {
	var config = jQuery.extend({
		ajaxURL: 'http://www.starsforeurope.com/search.html?lang=eng&search_folder=content&raw='
	}, conf);

	return this.each(function() {
		var input		= jQuery(this);		
		var results = jQuery('<div class="search_container"></div>').insertAfter('#leftcolumn').hide().slideUp(0);

		input.keyup(function() {
			if(this.value != this.lastValue && this.value.length >= 3 ) {
				
				//		show Loading animation
				jQuery('#loading').addClass('ajax-loading');

				var q = this.value;
				
				if(this.timer) {
					clearTimeout(this.timer);
				}

				this.timer = setTimeout(function() {
						jQuery.get(config.ajaxURL +q, function(data) {
															   
							//		Hide existing Content 
							jQuery('div.search_container:last').next().hide();

								if(data.length) {
									results.html(data).show();
									results.nextAll().hide();
							// remove loading animation
							jQuery('#loading').removeClass('ajax-loading');
								} else {
										results.hide();
										jQuery('div.search_container:last').next().show();
							// remove loading animation
							jQuery('#loading').removeClass('ajax-loading');
								}
							});
				}, 1000);
				this.lastValue = this.value;
			}
					else {
				//			jQuery('#loading').removeClass('ajax-loading');
							results.hide();
					}
		});
	});
};