(function($){
    $.fn.srmac = function(options) {
        var defaults = {autoSubmit: true,
                        ajaxUrl	: '/autocomplete.jquery.php',
			            wordLimit: 20,
			            topicLimit: 10,
			            resultContainer: 'autocomplete_container',
			            headerTag: 'h4',
			            wordlistTarget: 'wordlist_target',
			            wordlistHeader: 'Søkeforslag',
			            topcisTarget: 'topics_target',
			            topicsHeader: 'Emner',
			            offsetTop: 5,
			            offsetLeft: -9,
			            resultContainerWidth: 199,
			            noWordText: 'Ingen forslag tilgjengelig.',
			            noTopicText: 'Ingen relaterte emner.'
			            },
			settings = $.extend({}, defaults, options),	
            requests_sent = 0,
            autocomplete = function (t, $f) {
                    $.ajax({
                      url: settings.ajaxUrl,
                      dataType: 'json',
                      data: {term : t,
                             request : requests_sent,
                             wordlimit: settings.wordLimit,
                             topiclimit: settings.topicLimit},
                      success: function(data) {
                        if(parseInt(data.request) > parseInt($f.data('request'))) {
                            $('#' + settings.resultContainer)
                                .css({top: $f.offset().top + $f.outerHeight() + settings.offsetTop,
                                      left: $f.offset().left + settings.offsetLeft,
                                      width: settings.resultContainerWidth})
                                .children('div')
                                .html('')
                                .end()
                                .children(settings.headerTag)
                                .css({width: settings.resultContainerWidth - 9})
                                .end()
                                .slideDown('fast');
                            
                            $f.data('request', data.request);
                            if (data.wordcount > 0) {
                                $.each(data.wordlist, function(index, value) {
                                    $('<span />', {text: value}).appendTo('#' + settings.wordlistTarget);
                                    if(settings.noWordText.length == 0) {
                                        $('#' + settings.wordlistTarget).show().prev().show()
                                    }
                                });
                            } else {
                                if(settings.noWordText.length > 0) {
                                    $('#' + settings.wordlistTarget).html(settings.noWordText);
                                } else {
                                    $('#' + settings.wordlistTarget).hide().prev().hide();
                                }
                            }
                            if (data.topiccount > 0 ) {
                                $.each(data.topics, function(index, value) {
                                    txt = (value.parent)? value.title + ' ('+value.parent+')': value.title;
                                    $('<a />', {text: txt, href: value.url}).appendTo('#' + settings.topcisTarget);
                                    if(settings.noTopicText.length == 0) {
                                        $('#' + settings.topcisTarget).show().prev().show()
                                    }
                                });
                            } else {
                                if(settings.noTopicText.length > 0) {
                                    $('#' + settings.topcisTarget).html(settings.noTopicText);
                                } else {
                                    $('#' + settings.topcisTarget).hide().prev().hide();
                                }
                            }
                        }                 
                      }
                    });            
                    requests_sent++;       
                };
    
        $('<div />', {id: settings.resultContainer})
            .append($('<' + settings.headerTag +' />' , {text: settings.wordlistHeader}))
            .append('<div id="'+ settings.wordlistTarget +'"></div>')
            .append($('<' + settings.headerTag +' />' , {text: settings.topicsHeader}))
            .append('<div id="'+ settings.topcisTarget +'"></div>')
            .appendTo('body');
        
	    return this.each(function() {
	        var $acCont = $('#' + settings.resultContainer);
	        $(this)
	            .data('request', -1)
	            .keyup(function () {
	                var $this = $(this);
	                if($this.val().length >= 2) {
                	    autocomplete($this.val(), $this);
                	}
                	else if ($this.val().length == 0) {
                	    $acCont.slideUp('fast');
                	}
	            })
	            .blur(function () {
	                $acCont.data('hide', true);
	                setTimeout(function() {
	                    if($acCont.data('hide')) {
	                        $acCont.slideUp('fast');
	                    }
	                }, 250);
	            })
	            .focus(function() {
	                $acCont.data('hide', false);
	                $acCont.data('input', this);
	                var $this = $(this);
	                if ($this.val().length > 0) {
                        $this.keyup();
                    }
                });
                
            $('#' + settings.wordlistTarget + ' span').live('click', function() {
                var $target = $($acCont.data('input'));
                $target.val($(this).text());
                if(settings.autoSubmit) {
                    $target.closest('form').submit();
                }
            });
	    });
	}
})(jQuery);

