/**
 * KAKART: Live Search
 *
 * (c) Jon E, Dom A, Kaweb Ltd.
*/
(function($) {
	
	var opts;
	
	$.fn.kakartLiveSearch = function(options) {
		
		// Store options
		var opts = $.extend({}, $.fn.kakartLiveSearch.default_options, options);
		
		// Bind it.
		this.each(function() {
			
			var $this = $(this);
			var $results = $this.parents(opts.overallContainer).find(opts.resultsContainer);
			var pos = -1;
			var lastsearch = '';
			var max_results = opts.maxResults;
			var timer = null;
			
			$this.attr('autocomplete', 'off');
			
			// Slide up when clicking off livesearch
			$(document).click(function(e) {

				if(!$(e.target).parents(opts.resultsContainer).length && $(e.target).get(0) != $this.get(0)) {
					
					if($results.is(':visible')) {
						
						$results.hide('slide', { easing: 'easeOutQuint', direction: 'up' }, 250);
						// Neil hack
						$('.round-14, .rotate, ul.search-results li, #search-tools').css('z-index', '');
						
						lastsearch = '';
					}
				}
			});
			
			$this.live('click', function() {
				if ($results.is(':visible')) return;
				if ($this.val().length >= opts.minLength && $this.val() != $this.attr('title')) {
					$results.show('slide', { easing: 'easeOutQuint', direction: 'up' }, 1000);
					// Neil hack
					$('.round-14, .rotate, ul.search-results li, #search-tools').css('z-index', -1);
				}
				
			});
			
			$this.keyup(function(e) {
				var key = e.charCode || e.keyCode || 0;
				
				switch (key) {
					// Escape.
					case 27:
						// Clear the box and remove the results panel
						$(this).val('');
						
						if ($results.is(':visible')) {
							$results.hide('slide', { easing: 'easeOutQuint', direction: 'up' }, 250, function() {
								// Remove all results in the panel
								$results.find('ul li').remove();
							});
							// Neil hack
							$('.round-14, .rotate, ul.search-results li, #search-tools').css('z-index', '');
						}
						
						pos = -1;
						lastsearch = '';
						
						break;
						
					// Up & Down
					case 38:
					case 40:
						index_length = $results.find('ul li').length - 1;
						
						if ($results.is(':hidden') && $results.find('ul li').length > 0) {
							$results.show('slide', { easing: 'easeOutQuint', direction: 'up' }, 1000);
							// Neil hack
							$('.round-14, .rotate, ul.search-results li, #search-tools').css('z-index', -1);
						}
						
						if (key == 38) {
							// Up - wrap around if we hit top.
							pos = (pos == 0) ? index_length : pos - 1;
						}
						else {
							// Down - wrap around if we hit bottom
							pos = (pos < 0 || pos >= index_length) ? 0 : pos + 1;
						}
						
						$results.find('ul li').removeClass('hovering').eq(pos).addClass('hovering');
						
						return false;
					
					default:
						break;
				}
				
				if(timer) {
					clearTimeout(timer);
				}
				
				timer = setTimeout(function() {
					
					var val = $this.val();
					
					if (val.length >= opts.minLength) {
						
						// Earmark.
						$this.addClass('searching');
						
						if (val == lastsearch) 
							return;
					
						lastsearch = val;
					
						$.getJSON(opts.source, { search: val }, function(data) {
							
							$this.removeClass('searching');
							
							var json_results = data.results.length;
							var json_results_text = data.message;
							var ul_content = '';
							
							$results.find('ul li').remove();
							$(opts.elemNumberResults).html(json_results_text);
							
							var count = 0;
							
							$.each(data.results, function(index, item) {
								if(index < max_results || max_results == 0) {
									ul_content += opts.itemTemplate(index, item);
								}
							});
							
							$results.find('ul').html(ul_content);
						
							$results.find('ul li a img').load(function() {
								$(this).removeClass('loading').fadeIn();
							});
							
							if($results.is(':hidden')) {
								
								if(json_results > 0 || json_results == 0 && opts.triggerOnEmpty) {
									$results.show('slide', { easing: 'easeInQuint', direction: 'up' });
								}
								// Neil hack
								$('.round-14, .rotate, ul.search-results li, #search-tools').css('z-index', -1);
								
							}

							pos = -1;
							
							$(opts.elemViewAll).attr('href', '/products/search/' + escape(val));
							
						});
					}
					else {
						if ($results.is(':visible')) {
							$results.hide('slide', { easing: 'easeOutQuint', direction: 'up' }, 250);
							// Neil hack
							$('.round-14, .rotate, ul.search-results li, #search-tools').css('z-index', '');
						}
					}
				}, 200);
			});
			
			$this.parents('form').submit(function() {
				if (pos < 0) {
					window.location = '/products/search/' + escape($this.val());
					return false;
				}
				pos = (pos < 0) ? 0 : pos;
				var new_location = $results.find('ul li').eq(pos).find('a');
				
				$this.val(new_location.find('span.title').text());
				window.location = new_location.attr('href');
					
				return false;
			});

		});
		
		return this;		
	}
	
	$.fn.kakartLiveSearch.default_options = {
		overallContainer: '',
		resultsContainer: '#ajax_results',
		source: '/livesearch/',
		itemTemplate: function(index, item) { return '<li>' + item.toString() + '</li>'; },
		triggerOnEmpty: true,
		maxResults: 3,
		minLength: 3,
		elemNumberResults: '#search-numberResults',
		elemViewAll: '#search-view a'
    };
	
})(jQuery);