/* 
 * Gaia Ajax Widgets, an Ajax Widget Library
 * Copyright (C) 2007  Frost Innovation AS
 * All rights reserved.
 * This program is distributed under either GPL version 2 
 * as published by the Free Software Foundation or the
 * Gaia Commercial License version 1 as published by
 * Frost Innovation AS
 * read the details at http://ajaxwidgets.com/
 */



/*
        Helper for including JavaScript files DYNAMICALLY...!!
 */
 
var javaScriptFilesToWaitFor = 0;

function _checkIfAllFilesAreLoaded(checkFunction){
  var finished = false;
  try {
    var splits = checkFunction.split('.');
    var idx;
    for( idx = 0; idx < splits.length; ++idx ){
      var tmpChecker = '';
      for( var idx2 = 0; idx2 <= idx; ++idx2){
        if( idx2 != 0 )
          tmpChecker += '.';
        tmpChecker += splits[idx2];
      }
      if( eval('typeof window.' + tmpChecker) == 'undefined' )
        break;
    }
    if( idx == splits.length ) {
      finished = true;
    }
  } catch(err) {
    ; // Silently passing ince this is probably a "namespaced" type where the earlier parts of the "namespace" is undefined too...!!
  }
  if( finished ){
    // Decrement the number of files to wait for...
    javaScriptFilesToWaitFor -= 1;
  } else {
    // Wait 1/10 of second and try again...!!
    setTimeout(function(){
      _checkIfAllFilesAreLoaded(checkFunction);
    }, 100);
  }
}

$incJs = function(script, typeToWaitFor){
  var exists = false;
  var els = document.getElementsByTagName('script');
  for( var x = 0; x < els.length; ++x ){
    if( els[x].src.indexOf(script) != -1 ){
      exists = true;
      break;
    }
  }
  if( !exists ){
    javaScriptFilesToWaitFor += 1;
    var xJFile = document.createElement('script');
    xJFile.type='text/javascript';
    xJFile.src=script;
    document.getElementsByTagName('head')[0].appendChild(xJFile);

    // Waiting for script to load...
    _checkIfAllFilesAreLoaded(typeToWaitFor);
  }
}




