// Gaia Ajax Copyright (C) 2008 - 2009 Gaiaware AS. details at http://gaiaware.net/

/* 
 * Gaia Ajax - Ajax Control Library for ASP.NET
 * Copyright (C) 2008 - 2009 Gaiaware AS
 * All rights reserved.
 * This program is distributed under either GPL version 3 
 * as published by the Free Software Foundation or the
 * Gaia Commercial License version 1 as published by
 * Gaiaware AS
 * read the details at http://gaiaware.net
 */

/* ---------------------------------------------------------------------------
   Helper for including JavaScript files DYNAMICALLY...!!
   --------------------------------------------------------------------------- */

// Main namespace for ENTIRE library (JS parts)
if( !window.Gaia  )
  Gaia = Class.create();

// This one is being used OUTSIDE of this file in the Control.js to ensure all JS files are
// finished loading before the execution engine moves on and potentially dereference types from
// the JS files. 
Gaia.javaScriptFilesToWaitFor = 0;

Gaia._checkIfAllFilesAreLoaded = function(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 since 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...
    Gaia.javaScriptFilesToWaitFor -= 1;
  } else {
    // Wait 1/10 of second and try again...!!
    // Trying to AVOID recursion due to Safari's small stack...
    setTimeout('Gaia._checkIfAllFilesAreLoaded(\''+checkFunction+'\');', 100);
  }
}

$incJs = function(script, typeToWaitFor){

  // First checking to see if script already exists on page from before
  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 ){
    // This file didn't exist therefore we have to include it onto the page
    Gaia.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...
    Gaia._checkIfAllFilesAreLoaded(typeToWaitFor);
  }
}

Gaia_ScriptHelper_browserFinishedLoading = true;
