(function($) {
    
    $.lookahead = {
        'url': '',
        'onReceive': null,
        'onClick': null,
        'target_id': 'lookahead_results'
    };
    
    $.fn.lookahead = function(settings) {

        var config = $.extend({}, $.lookahead, settings);
        
        if(config['url'] == '')
        {
            alert('Lookahead "url" is required');
            return false;
        }
        
        if(typeof config['onReceive'] == 'string') {
            alert("Use \n'onReceive' : "+config['onReceive']+ "\n instead of\n'onReceive' : '"+config['onReceive']+"'");
            return false;
        }
        
        if(typeof config['onClick'] == 'string') {
            alert("Use \n'onClick' : "+config['onClick']+ "\n instead of\n'onClick' : '"+config['onClick']+"'");
            return false;
        }
        
        if($('#'+config['target_id']).length == 0)
        {
            $('<div></div>').attr('id', config['target_id'])
                            .addClass('lookahead_results')
                            .css({'position': 'absolute', 'zIndex': 1000})
                            .appendTo('body');
        }

        //Add functionality to all applicable inputs
        this.each(function() {
            $elem = $(this);
            $elem.attr('autocomplete', 'off')
                 .data('last_value', $elem.val())
                 .data('config', config)        
                 .keyup(data_lookup);
        });
        return this;
    }
    
    function data_lookup()
    {
        var $source = $(this);
        if($source.data('last_value') == $source.val())
            return false;

        $source.data('last_value', $source.val());
        var config = $source.data('config');
        
        $.ajax({
              type : 'GET',
              url : '/member/lookup/term/' + $source.val(),
              dataType : 'json',
              success: function(data) { populate_results(data, $source); },
              error: function(req, status, errorThrown) {
                  alert('error status: ' + errorThrown);
              }
        });
    }
    
    function populate_results(data, $source)
    {
        var config = $source.data('config');
        var $output_box = $('#' + config['target_id']);
        
        if(config['onReceive'])
        {
            var func = config['onReceive'];
            return func(this, $source);
        }
        
        if(data == null || data.length == 0)
        {
            $output_box.empty();
            $output_box.hide();
            return;
        }
        
        var position = $source.offset();
        position.top += $source.height() + 5;
        
        $output_box.html('<ul></ul>')
                   .css({'left': position.left, 'top': position.top})
                   .show();
        for(i = 0; i < data.length; i++)
        {
            $('<li></li>').appendTo($output_box)
                          .html(data[i]['value'])
                          .data('item_data', data[i])
                          .click( function() { itemChoose(this, $source); });
        }
    }
    
    function itemChoose(item, $source)
    {
        var config = $source.data('config');

        if(config['onClick'])
        {
            var func = config['onClick'];
            var return_val = func(item, $source);
            if(return_val == false)
                return false;
        }    
        
        $source.val($(item).text());
        $('#'+config['target_id']).empty();
        $('#'+config['target_id']).hide();
    }
})(jQuery);

