//<![CDATA[

/***************************
 * JsFileLoader.js
 *
 * Created by Jennifer Bowen 2008-04-02
 * Last updated 2008-04-02
 * 
 * DHTML utility for loading javascript files.
 * Allows for easier separation of content while
 * maintaining file cacheability.
 *
 ****************************/

function JsFileLoader(jsroot) {
    this.jsroot=jsroot;
    this.jslist = new Array();
    this.head = document.getElementsByTagName("head")[0];
    this.timeout = 3 * 1000; // 3-second timeout to retrieve files

    var all_links = document.getElementsByTagName("script");
    for ( var i = 0; i < all_links.length; i++ ) {
        var ftype = all_links[i].getAttribute("rel");
        if ( ftype == "javascript" ) {
            var find = this.jslist.indexOf(all_links[i].getAttribute("src"));
            if ( find == -1 ) {
                this.jslist.push(all_links[i].getAttribute("src"));
            }
        }
    }
}

JsFileLoader.prototype.isFileIncluded = function(filename) {
    var find = this.jslist.indexOf(filename);
    return find != -1;
}

JsFileLoader.prototype.load = function (filename) {
    var idx = this.isFileIncluded(this.jsroot+filename);
    if ( idx !== false ) return this.jslist[idx];

    var fileref = document.createElement("script");
    fileref.setAttribute("rel","javascript");
    fileref.setAttribute("type","text/javascript");
    fileref.setAttribute("src",this.jsroot + filename);

    // IE won't automatically trigger a load event, so add it in
    var fired = false;
    GEvent.addDomListener(fileref,'readystatechange',function(e) {
      if ( ! fired && this.readyState == 'complete' || this.readyState == "loaded" ) {
        fired = true;
        GEvent.trigger(this,'ready',true);
      }
    });

    // Also add in a timeout, in case we can't actually load the file
    var tid = window.setTimeout(function (e) {
      GEvent.trigger(this,'ready',false);
    }, this.timeout);

    GEvent.addDomListener(fileref,'load',function(e) {
      window.clearTimeout(tid); 
      GEvent.trigger(this,'ready',true);
    });

    this.head.insertBefore(fileref,this.head.firstChild);
    return fileref;
}



//]]> 
