/*
 * 'whenLoaded' jQuery plugin
 *
 * @author James Padolsey
 * @description Runs a callback function (specified as argument) when all selected elements have loaded.
 *              Works only with certain elements, i.e. those which have an onload event (e.g. iframe,img etc.)
 * @namespace jQuery.whenLoaded
 * @namespace jQuery.fn.whenLoaded
 * @version 1.0
 * 
 */

(function(JQ){
    JQ.fn.whenLoaded = function(fn){
        var JQelements = this,
            total = this.length;
        JQelements.each(function(){
            JQ(this).load(function(){
                JQ(this).data('isLoaded',true);
            });
        });
        function check() {
            var loaded = 0;
            JQelements.each(function(){
                if(JQ(this).data('isLoaded')) {
                    loaded++;
                }
            });
            if(loaded===total) {
                fn.call(JQelements);
            } else {
                setTimeout(check,300);
            }
        }
        check();
    }
})(jQuery);


