/**
 * require is used for on demand loading of JavaScript
 *
 * require r1 // 2008.02.05 // jQuery 1.2.2
 *  // basic usage (just like .accordion) $.require("comp1.js");
 *
 *
 * @param jsFiles
 *            string array or string holding the js file names to load
 * @param params
 *            object holding parameter like browserType, callback, cache
 * @return The jQuery object
 * @author Manish Shanker
 * @author Ferenc Radius
 */
(function($) {

    /**
     * add files
     * @param {Object} dependency
     */
    function loadCss(file){
        var link = document.createElement('link');
        link.rel = "stylesheet";
        link.type = "text/css";
        link.href = $.cssPath + file;
        $(link).insertAfter("head > link[rel='stylesheet']");
    }

    $.require = function(jsFiles, params) {

        var executed = false;
        var params   = params || {};
        var browser  = params.browser === false ? false : true;
        var cache    = !!$.requireCache;
        var cBack    = params.callBack || function() {};

        $.require.loadedLib = $.require.loadedLib || {};
        jsFiles =(typeof jsFiles === "string") ? [jsFiles] : jsFiles;

        if (!browser) {
            return $;
        }

        if(typeof params.cache == "boolean") {
            cache = params.cache;
        }

        if (!$.scriptPath) {
            throw Error('$.scriptPath not set!');
        }

        for( var i = 0; i < jsFiles.length; i++) {
            var file = jsFiles[i];

            if (!$.require.loadedLib[file]) {

                if(file && file.match(/\.css$/) != null) {
                    loadCss(file);
                    cBack.call(this);
                } else {
                    $.ajax({
                        type : "GET",
                        url : $.scriptPath + file,
                        success: function() {
                            executed = true;
                            cBack.call(this);
                        },
                        dataType : "script",
                        cache : cache,
                        async : false
                    });
                }
                $.require.loadedLib[file] = true;
            }
        }

        if(!executed) {
            cBack.call(this, true);
        }
        return $;
    };
})(jQuery);
