function log(msg){ try{ console.log(msg) }catch(e){	window.console = {	log:function(){} };	} }

// TODO: 
//		Focus on the input
//		Smoother opening of the resultcontainer & adjust height nicely

$(function(){
	QuickSearch.init();
	
	// Initialize sliders if needed
	if (jQuery().easySlider){
		initCardSliders();
	}

});


function initCardSliders(){
	
	// Add slider functionality 
	$("div.slider").easySlider({
		prevText: 'Vorige',
		nextText: 'Volgende',
		speed : 500
	})
	// Then make each list item clickable and flipable
	.find('li').click(function(){
		$this = $(this);
		// Get the image
		$img = $this.find('img');
	
		// Set image and direction
		var newImage =  $img.attr('src').replace('front', 'back');
		var direction = 'rl';
		
		if($img.attr('src').indexOf('back') > -1){
			// Switching back to front
			newImage =  $img.attr('src').replace('back', 'front');
			direction = 'lr';
		}
		
		$img.attr('src', newImage);
		
		$this.flip({
			direction: direction,
			color: '#FFFFFF',
			content: $img,
			speed: 500
		});
		
	});

}


var QuickSearch = function(){

	// Static config variables
	var CONTAINER_ID = 'quicksearch';
	var API_URL = '/api/entities/search/';
	
	// Elements
	var opener = null;
	var container = null;
	var input = null;
	var resultContainer = null;

	var selectedResult = null;
	
	// Possible states of the QuickSearch
	var active = false;
	var requestCounter = 0;
	
	
	function init(){
		
		// Initialize opening by clicking
		opener = $('#quicksearch-opener').click( open );

		// Also by pressing 'shift + ?'
		$(document).keydown(  function(e){
			if (e.shiftKey && e.keyCode == 191 ){
				open();
			}
		});
		
		// Close by pressing escape: note keyup is used here -> escape key doesn't trigger keydown event) 
		$(document).keyup(  function(e){
			if(e.keyCode == 27 && active ){
				close();
			}
		});
	
	}	
	
	function open(){
		if( !container ){
			container = $('#' + CONTAINER_ID );
			input = $('#query').bind('keydown', handleInputKeyUp );
			$(document).click( handleDocumentClick );
			$('#quicksearch-form').submit( function(){ return false;} );
		}

		setTimeout( function(){
			input.focus();
		}, 400);
		
		container.show();
		active = true;
		
		return false;
	}
	
	function close(){
		container.hide();
		active = false;
	}

	
	// Close the Quicksearch when clicked outside it
	function handleDocumentClick(e){

		// If the event target isn't a child of our container, click happened outside the container
		if ( active && !$(e.target).parents('#' + CONTAINER_ID ).length){
			close();
		}

	}
	
	function handleInputKeyUp(e){
		
		if( e.keyCode > 8 && e.keyCode < 48){

			// Not backspace or character, so no need to update
			return true;
		}
		
		update();
	}
	
	
	function update(){
		requestCounter++;
		var query = input.val();
		$.getJSON( API_URL, {c:requestCounter,q:query}, handleUpdate );

	}
	
	function handleUpdate(resp){
		
		if (!resultContainer){
			setupResultDisplay();
		}
		
		if (resp.requestCount != requestCounter ){
			// If this wasn't the last request, ignore it
			return false;
		}
		if ( !resp.data.resultCount){
			resultContainer.hide()
			container.removeClass('listing-results');
			return false;
		}else{
			resultContainer.show()
			container.addClass('listing-results');
		}

		resultContainer.html(resp.data.html);
		selectedResult = null; // Previous list is gone		

	}

	function setupResultDisplay(){
		
		if (resultContainer){
			return true;
		}
		
		resultContainer = $('#quicksearch-results');
		
		// Enable closing
		$('#quicksearch-close').click(close);
		
		// Enable clicking on list items
		$('#quicksearch-results li').live( 'click', function(){
			followLink( $(this) );

		});
		// Enable hovering list items
		$('#quicksearch-results li').live( 'mouseover', function(){	select($(this));  });
		$('#quicksearch-results li').live( 'mouseout', function(){	deselect($(this)); });
		
		// Enable keyboard navigation
		$(document).keyup( handleDocumentKeyUp );
		
		return true;
	}
	
	
	function handleDocumentKeyUp(e){

		if( e.keyCode == 40 || e.keyCode == 38 ){
			
			var toSelect;

			if( e.keyCode == 40 ){	// Pressed down arrow
				
				if( !selectedResult ){
					// No selected list item yet, select the first one
					select( $('li:first', resultContainer) );
				}else{
					var next = selectedResult.next('li');
					if( next.length ){
						toSelect = next;
					}
				}
				
			}else if(e.keyCode == 38){	// Pressed up arrow
			
				var prev = selectedResult.prev('li');
				if( prev.length ){
					toSelect = prev;
				}

			}
			
			if (toSelect){
				deselect( selectedResult );
				select( toSelect );	
			}

		}else if( e.keyCode == 13 ){
			// Enter key pressed
			if(selectedResult){
				followLink(selectedResult);
			}
		}
	}
	
	function select( $li ){
		selectedResult = $li.addClass('hover');
	}
	
	function deselect( $li ){
		$li.removeClass('hover');
		selectedResult = null;
	}
	function followLink( li ){
		window.location.href = $(li).find('a:first').attr('href');
		return false;
		
	}
	
	return {
		init: init
	};
	
}();
