$(function() {
	$('#search-from, #search-to').datepicker({
		showButtonPanel: true,
		firstDay: 1,
		dayNamesMin: ['S', 'M', 'T', 'W', 'T', 'F', 'S']
	});


	$('#searchbar-keywords')
		.data('val', $('#searchbar-keywords').val())
		.keyup(function() {
			$(".searchloader").show(); 
			if ($(this).data('val') != $(this).val()) {
				$(this).data('val', $(this).val());

				var timer = $(this).data('timer');

				if (timer) {
					clearTimeout(timer);
				}

				var query = $(this).val();
				if (query.length >= 3) {
					timer = setTimeout(function() {
						var formdata = $('#searchbox form').serializeArray();
						formdata[2].value = "search/ajax";
						var postdata = {};
			
						for (var i in formdata) {
							postdata[formdata[i].name] = formdata[i].value;
						}
			
						$.ajax({
							type: 'POST',
							url: '/',
							data: postdata,
							dataType: '',
							success: function(data, textStatus) {
								//alert(data);
								if (data.indexOf('<!-- AJAX RESULTS') != -1) {
									$('#searchbox .dropdown').html(data).show();
								}
								else {
									$('#searchbox .dropdown').html('').hide();
								}
							}
						});
					}, 500);
			
					//console.log(timer);
					$(this).data('timer', timer);
				}
			}
			else {				
				$(".searchloader").hide(); 
			}
		})
		.focus(function() {
			$(this).val("");
		})
		.blur(function() {
			if($(this).val()==''){
				$(this).val("SEARCH");
			}
			if (!$('#searchbox .dropdown').data('selected')) {
				$('#searchbox .dropdown').hide();
			}
		});
	$('#searchbox .dropdown').mouseenter(function() {
		$(".searchloader").hide(); 
		$('#searchbox .dropdown').data('selected', true);
	});

	$('#searchbox .dropdown').mouseleave(function() {
		$('#searchbox .dropdown').data('selected', false);
	});

	$('#searchbox .dropdown').click(function(e) {
		e.stopPropagation();
	});
	
	$('#btnSearchSubmit').click(function(e){
		if($('#searchbar-keywords').val()=='SEARCH'){
			return false;
		}
	});

	$('body').click(function() {
		$('#searchbox .dropdown').hide();
		$(".searchloader").hide(); 
	});
});

