
// Hide all search-results if you click outside them
$(document.body).click(function(event) {
	if(!$(event.target).parents('#quick-search-results').length) {
		jQuery('#quick-search-results').fadeOut(300);
	}
});

jQuery.fn.liveSearch = function(conf) {
	var config = jQuery.extend({
		ajaxURL: '/quicksearch/'
	}, conf);

	return this.each(function() {
		var input	= jQuery(this);
		var results	= jQuery('<div id="quick-search-results"></div>').appendTo('#quick-search');
		
		input.keyup(function() {
			if(this.value != this.lastValue) {
				input.addClass('ajax-loading');

				var q = this.value;

				//validate the postcode
				if (!checkPostCode (q)) {
					$(this).removeClass('valid');
					$(this).addClass('not-valid');
					return false;
				}else{
					$(this).removeClass('not-valid');
					$(this).addClass('valid');
				}
				
				if(this.timer) {
					clearTimeout(this.timer);
				}

				this.timer = setTimeout(function() {
					jQuery.get(config.ajaxURL + q, function(data) {
						input.removeClass('ajax-loading');

						if(data.length) {
							results.html(data).fadeIn(300);
						}
						else {
							results.slideUp(300);
						}
					});
				}, 200);

				this.lastValue = this.value;
			}
		});
	});
};

jQuery.fn.SportliveSearch = function(conf) {

	return this.each(function() {
		var input	= jQuery(this);
		
		function setupNextLink(sport, type, q, page){
			$('#local-search-container .load').remove();
			/* Local results */
			$('#local-search-container').append('<div id="next-resutls-' + page + '"></div>');
			$('#local-search-container').append('<p id="next-five" class="read-more-link"><a href="#">Load next 5 clubs</a></p>');
			$('#next-five a').click(function(){
				$('#next-resutls-' + page).load("/clubs/clubsearch/", { 
					'sport' : sport,
					'type'	: type,
					'postcode' : q,
					'page' : page
					},
					function(){
						$('#next-five').remove();
						setupNextLink(sport, type, q, page + 1);
					}
				);
				return false;
			});
		}
		
		input.keyup(function() {
			if(this.value != this.lastValue) {
				input.addClass('ajax-loading');

				var q = this.value;

				//validate the postcode
				if (!checkPostCode (q)) {
					$(this).removeClass('valid');
					$(this).addClass('not-valid');
					return false;
				}else{
					$(this).removeClass('not-valid');
					$(this).addClass('valid');
					$('#local-search').css('background-image', 'none');
					$('#local-search-container').append('<div class="load"><p>LOADING...</p></div>');
	
					var page = 0;
					var sport = $('body').attr('id');
					var type = 1
					
					/* Local results */
					$('#local-search-container').load("/clubs/clubsearch/", { 
						'sport' 	: sport,
						'type'		: type,
						'postcode' 	: q,
						'page' 		: page
						},
						function(){
							setupNextLink(sport, type, q, page + 1);
						}
					);
					
					
				}
				this.lastValue = this.value;
			}
		});
	});
};
















