/*******************************************************************
*	Javascript loader
*	Author: Kasey McCurdy
*	Date: 11.13.06
*   Dependencies: prototype.lite (with dom-ready extension), moo.ajax, dombuilder
*	Description: ensures that javascript files are only called once (to avoid multiple calls of the same file)
*	Usage: first off, include this script...then, its just a matter of the following:
*		jl.include('/kc/js/one_a.js','/kc/js/one_b.js'd,'/kc/js/two_a.js');
*		jl.waitForLoad(loadme);
*
*		function loadme(){
*			//stuff to happen when scripts are loaded
*		};
********************************************************************/

function jsLoader(){
    var self = this;						/* fix the ol' loss o' scope */
	this.s_t_l = 0;				            /* SCRIPTS_TO_LOAD | the number of scripts requested */
	this.s_l = 0;				            /* SCRIPTS_LOADED | the number of scripts done loading (will be compared against the scripts_to_load) */
    this.i_f = new Array();		        /* INCLUDED_FILES | keep track of files requested */
    this.c_f = new Array();                /* CSS_FILES | css files to load */
	this.t_s = "";					        /* THE_SCRIPTS | string of all javascript to be parsed */
	this.l_f_r = false;		            /* LOADED_FILES_READY | boolean: lets us know when we're done and ready to send the callback */
    this.d_l =  false;                    /* DOM_LOADED | boolean: checks to make sure the dom is ready */
	this.scriptLoaded = function(s, a) { /* (script src, array) */
        alert('sl');
        for (var i = 0; i < a.length; i++) {
            if (a[i] == s) {
                return true;
            }
        }
        return false;
    };
	this.getFilename = function(s) { /* returns filename only, not the full path to file */
        return s.substr(s.lastIndexOf("/") + 1, s.length);
    };
	this.in_array = function(ndl, hs) { /* in_array(needle, haystack) */
        for (var i = 0; i < hs.length; i++) {
            if (hs[i] == ndl) {
                return true;
            }
        }
        return false;
    };
    this.isInScriptTags = function(s) { /*dont request the script if it's already hardcoded on the page */
        if (document.getElementsByTagName) {
            var scripts = document.getElementsByTagName('SCRIPT');
            for (var i = 0; i < scripts.length; i++) {
                if (scripts[i].getAttribute("SRC")) {
                    if (scripts[i].getAttribute("SRC").indexOf(s) >= 0) {
                        return true;
                    }
                    ;
                }
                ;
            }
        } else {
            return false;
        }
        ;
        return false;
    };
    this.isInCss = function(f) {
        for (var i = 0; i < self.c_f.length; i++) { /*make sure it's not alreayd in the array*/
            if (self.c_f[i].indexOf(f) > 0) {
                return true;
            }
        }
        if (document.getElementsByTagName) {
            var cfiles = document.getElementsByTagName('LINK');
            for (var i = 0; i < cfiles.length; i++) {
                if (cfiles[i].getAttribute("href").indexOf(f) >= 0) {
                    return true;
                }
            }
            return false;
        } else {
            return false;
        }
    };
    this.loadCss = function() {
        for (var i = 0; i < self.c_f.length; i++) {
            var css = document.createElement("link");
            css.rel = "stylesheet";
            css.href = self.c_f[i];
            css.type = "text/css";
            document.body.appendChild(css);
        }
    };
    this.waitForLoad=function(c){
            var r = 0;
            if(r < 10000){ /* lets make sure we dont blow up their machine !*/
                if (self.s_t_l == self.s_l && self.d_l){
                    clearTimeout(t);
                    var html = DomBuilder.apply();
                    var s = html.SCRIPT(self.t_s);
                    document.body.appendChild(s);
                    c();
                    self.loadCss();
                }else{
                    r++;
                    var t=setTimeout(function(){ self.waitForLoad(c); },300);
                }
            }else{
                clearTimeout(t);
            }
    };
	$(document).ready( function() {
        self.d_l = true;
    });
    var filesLoadedCheck;
	this.sl = function(request) { /*script loaded -- will increment counter */
        self.s_l++;
        self.t_s += request.responseText + "\n";
    }
    /*****************************************
     * include(args);
     * expects any number of elements...which
     * should be locations of the .js files
     * you want to load.
     *****************************************/;
	this.include = function() {
        var a = arguments;
        for (var i = 0; i < a.length; i++) {
            /* catch CSS files */
            if (a[i].substring(a[i].length - 4).indexOf(".css") >= 0) {
                if (!self.isInCss(self.getFilename(a[i]))) {
                    self.c_f.push(a[i]);
                }
            }
            else if (!self.in_array(a[i], self.i_f) && !self.isInScriptTags(a[i])) {
                self.i_f[self.i_f.length] = a[i];
                self.s_t_l++;
                new Ajax(a[i], {method:'get', onComplete:self.sl});
            } 
        }
    };
}

var jl = new jsLoader(); /*create singleton object of this*/

