(function($){
var vendorLookupUrl = window.zinc.root+"/zinc/vendor-query.php";

jQuery.fn.supplierItemQuery = function (chunkSize) {
 
    if(this.length < 1) return;

    chunkSize = chunkSize || null;

    var query = {
        'vendors': [], 
        'codes':   [], 
        'targets': []
    };
    
    this.each(function () {
        var $this  = $(this)
        $this.removeClass('lookup').addClass('loading');

        query.vendors.push($this.parent().parent().parent().attr("class").split('-', 2)[1]);
        query.codes.push($this.text().trim());
        query.targets.push($this.attr('id'));

        $this.text(this.text + " (\u2026)");
        
    });

    var doLookup = function (params) {
        jQuery.getJSON(vendorLookupUrl, params, function (data) {
            jQuery.each(data, function(id, body) {
                $("#"+id).removeClass('loading').text(body);
            });
        });
    };
    
    if(chunkSize) {
        var chunks = query.length / chunkSize;
        var chunk = {
            'vendors': [], 
            'codes':   [], 
            'targets': []
        };
        for(var i = 0; i < query.targets.length; i++) {
            chunk.vendors.push(query.vendors[i]);
            chunk.codes.push(query.codes[i]);
            chunk.targets.push(query.targets[i]);
            if(i > 0 && i % chunkSize == 0) {
                doLookup(chunk);
                 var chunk = {
                     'vendors': [], 
                     'codes':   [], 
                     'targets': []
                 };
            }
        }
        if(chunk.targets.length > 0) {
            doLookup(chunk);
        }
    } else {
        doLookup(query);
    }
};

})(jQuery);

