
tj$         = window.tj$ || {};

//Input:  if async and following args are not supplied, then async injection is attempted.
//        callback is optional and happens after injection started. 
//        if delay is not set, then it will be 0 by default which forces to call injection immediately.
//        if delay is negative, then injection will start after window onload and after |delay| milliseconds
//        if delay is positive, than injection will start |delay| milliseconds after now.

tj$.inject = function (url, delay, async, callback) {
                  if( arguments.length < 3 ) async = true;
                  //TODO:
                  var cb = ( arguments.length > 3 && typeof arguments[3] === 'function' ) ? arguments[3] : null;

                  //Script loader and callback caller:
                  var fun = function () {
                     var x = document.createElement('script');
                     x.setAttribute('async', async);
                     x.setAttribute('type', 'text/javascript');
                     x.src = url;
                     document.documentElement.firstChild.appendChild(x);
                     if( cb ) cb();
                  };

                  var onload = window.onload;
                  var dl = delay || 0;
                  if( dl < 0 ) {
                      window.onload = function () {
                         if( onload ) onload();
                         if( dl < -1 ){
                            setTimeout( fun,  0 - dl );
                         }else{
                            fun();
                         }
                     };
                  }else if( dl > 0 ){
                     setTimeout( fun, dl );
                  }else{
                     fun();
                  };
};
 

