puhuri.settings({
	swf: 'simple.swf',
	parentelement: 'li',
	highlight: true,
	highlightclass: 'puhuri-highlight',
	highlighttype: 'block',
	autoskip: 'span.source'
})

var selkohaku = (function($){
	function init() {
		
		$('#query').focus(input.onfocus).blur(input.onblur).keypress(input.keypress);
		
		input.emptycheck();
		
		$(document).keypress(input.autofocus);
		$(window).unload(function() { 
				var m = document.location.href.match(/^[^\?]+\?q\=([^\&]+)$/);
				$('#query.empty').val(m ? unescape(m[1]) : '');
			});
		$('#selkohaku').submit(function(evt) {
        if ($('#query').is('.empty')) evt.preventDefault();
      });
		
	}
	
	var input = {
		timeout: null,
		emptyNote: 'Hae tietoa selkosivustoista. Kirjoita hakusanat tähän.',
		
		emptycheck: function() {
			if ($('#query').val() == '')
				$('#query').addClass('empty').val(input.emptyNote);
			else
				$('#query').removeClass('empty');
		},
		
		onfocus: function(evt) {
			$(document).unbind('keypress', input.autofocus);
			$('#query.empty').removeClass('empty').val('');
		},
		
		onblur: function(evt) {
			$(document).unbind('keypress', input.autofocus);
			$(document).bind('keypress', input.autofocus);
			input.emptycheck();
		},
		
		autofocus: function(evt) {
			if (evt.charCode != null && evt.charCode != 0 && !evt.ctrlKey && !evt.altKey && !evt.metaKey) {
				var c = String.fromCharCode(evt.which || evt.keyCode); 
				//console.log(c+' '+evt.charCode);
				if (c.match(/[a-zA-Z0-9äöåÄÖÅ]+/)) {
					$('#query')[0].focus();
					$('#query').val(function() { return this.value + c; });
					input.keypress();
					evt.preventDefault();
				}
			}
		},
		
		keypress: function() {
			clearTimeout(this.timeout);
			this.timeout = setTimeout(input.spelling, 1000);
		},
		
		spelling: function() {
			var q = $('#query:not(.empty)').val(),
			    sp = $('#spelling');
			if (q && q.length > 2 && sp.length) {
				sp.slideUp('fast', function() { $(this).find('a').text('').attr('href', '#'); });
				$.get('/haku/spell/'+q, function(data) {
						if (data != '' && data != q && data.length > 2) {
							sp.slideDown('fast').find('a').text(data).attr('href', '?q='+data);
						}
					});
			}
		}
		
	};
	
	return {
		init: init
	};
	
}(jQuery));

$(selkohaku.init);
