(function ( $ ) {
 
    $.fn.bootcomplete = function(options) {
        
        var defaults = {
            url : "",
            method : 'POST',
            wrapperClass : "bc-wrapper",
            menuClass : "bc-menu",
            idField : true,
            idFieldName : $(this).attr('name')+"_id",
            minLength : 3,
            dataParams : {},
            formParams : {},
            functionParams : null,
            clearIdFieldOnKeyUp: true
        }

        var settings = $.extend( {}, defaults, options );

        $(this).attr('autocomplete','off')
        $(this).wrap('<div class="'+settings.wrapperClass+'"></div>')
        
        if (settings.idField) {
            if ($(this).parent().parent().find('input[name="' + settings.idFieldName + '"]').length !== 0) {
                //use existing id field
            } else {
                //there is no existing id field so create one
                $('<input type="hidden" name="' + settings.idFieldName + '" value="">').insertBefore($(this))
            }
        }
        
        $('<div class="'+settings.menuClass+' list-group"></div>').insertAfter($(this))
        
        $(this).on("keyup", searchQuery);
        $(this).on("focusout", hideThat)

        var xhr;
        var that = $(this)

        function hideThat() {
            if ($('.list-group-item' + ':hover').length) {
                return;
            }

            var containerResult = $(that).next('.'+settings.menuClass);

            if(containerResult.length == 0){
                containerResult = $(that).next().next('.'+settings.menuClass);
            }

            containerResult.hide();
        }
        
        function searchQuery(){
            if (settings.idField && settings.clearIdFieldOnKeyUp) {
                if ($(that).parent().parent().find('input[name="' + settings.idFieldName + '"]').length !== 0) {
                    //use existed id field
                    $(that).parent().parent().find('input[name="' + settings.idFieldName + '"]').val("");

                    // by froilan
                    $(that).parent().parent().find('input[name="' + settings.idFieldName + '"]').trigger('change');
                }
                else {
                    //use created id field
                    $(that).prev('input[name="' + settings.idFieldName + '"]').val("");

                    //by froilan
                    $(that).prev('input[name="' + settings.idFieldName + '"]').trigger('change');
                }
            }
            
            var arr = [];
            $.each(settings.formParams,function(k,v){
                arr[k]=$(v).val();
            })
            var dyFormParams = $.extend({}, arr );

            var dyDynamicParams = {};
            if(settings.functionParams != undefined && settings.functionParams != null && $.isFunction(settings.functionParams)) {

               dyDynamicParams =  settings.functionParams();
            }

            //Build Data
            var Data = $.extend({search: $(this).val()}, settings.dataParams, dyFormParams, dyDynamicParams);

            if(!Data.search){
                $(this).next('.'+settings.menuClass).html('')    
                $(this).next('.'+settings.menuClass).hide()    
            }

            Data.search = Data.search.trim();
            if(Data.search.length >= settings.minLength){
                
                if(xhr && xhr.readyState != 4){
                    xhr.abort();
                }
                
                xhr = $.ajax({
                    type: settings.method,
                    url: settings.url,
                    data: JSON.stringify(Data),
                    dataType: "json",
                    contentType: 'application/json; charset=utf-8',
                    success: function( json ) {
                        var results = ''
                        $.each( json, function(i, j) {
                            results += '<a href="#" class="list-group-item" data-id="'+j.id+'" data-label="'+j.label+'">'+j.label+'</a>'
                        });


                        var containerResult = $(that).next('.'+settings.menuClass);

                        if(containerResult.length == 0){
                            containerResult = $(that).next().next('.'+settings.menuClass);
                        }


                        $(containerResult).html(results);
                        $(containerResult).children().on("click", selectResult);
                        $(containerResult).show();
                    }
                })
            }
        }
        
        function selectResult(){
            $(that).val($(this).data('label'));
            if (settings.idField) {
                if ($(that).parent().parent().find('input[name="' + settings.idFieldName + '"]').length !== 0) {
                    //use existed id field
                    $(that).parent().parent().find('input[name="' + settings.idFieldName + '"]').val($(this).data('id'));
					//ensure we trigger the onchange so we can do stuff
					$(that).parent().parent().find('input[name="' + settings.idFieldName + '"]').trigger('change');
                }
                else {
                    //use created id field
                    $(that).prev('input[name="' + settings.idFieldName + '"]').val($(this).data('id'));
					//ensure we trigger the onchange so we can do stuff
					$(that).prev('input[name="' + settings.idFieldName + '"]').trigger('change');
                }
            }

            var containerResult = $(that).next('.'+settings.menuClass);

            if(containerResult.length == 0){
                containerResult = $(that).next().next('.'+settings.menuClass);
            }

            containerResult.hide();

            return false;
        }

        return this;
    };
 
}( jQuery ));
