﻿
// Script : Represents one script file

Script = createClass();
Script.prototype.init = function(args) {
    /*
        id          : Unique script identifier (will be used in script callbacks)
        url         : Script url
        defer       : Delay execution of script or not
        mandatory   : Whether this script is mandatory for Script-batch callback
        callback    : Function to be called on script load, or timeout expiry
        timeoutSec	: Wait timeout for script
    */
	if(!isDefined(args))
		args = {};
	defaults = { id: null, url: null, defer: false, mandatory: true, callback: null, timeoutSec: 60 };
	for(var pr in defaults)
		this[pr] = isDefined(args[pr]) ?args[pr] :defaults[pr];
    
	// Script request/response status
    this.sentRequest = false;
	this.gotResponse = false;
    this.errorCode = -1;

	// Timeout-id returned by setTimeout function
	this.timeoutId = null;
	this.parentBatch = null;
	
	// Load script file from server
    this.load = function() {
	    if(!isEmpty(this.id)) {
		    if(isString(this.url)) {
			    var scriptTag = document.createElement("script");
			    scriptTag.type = "text/javascript";
			    scriptTag.src = this.url;
			    if(this.defer)
				    scriptTag.defer = "defer";
			    document.getElementsByTagName("head")[0].appendChild(scriptTag);
		    }
    		
		    this.sentRequest = true;
		    var script = this;
		    this.timeoutId = window.setTimeout(function() { script.onTimeout(); }, this.timeoutSec*1000 );
	    }
	    else
		    throw new Error("Script-id compulsary for load");
    };

    // Script onLoad handler
    this.onLoad = function(errorCode) {
	    window.clearTimeout(this.timeoutId);
    	
	    if(isDefined(errorCode))
		    this.errorCode = errorCode;
	    // If no error occured
	    if(this.errorCode == -1) {
		    this.gotResponse = true;
		    if(this.callback)
			    this.callback();
		    if(this.parentBatch)
			    this.parentBatch.onScriptLoad(this.id);
	    }
	    else
		    this.onError();
    };

    // Script onTimeout handler
    this.onTimeout = function() {
	    throw new Error("Timeout expired for: " + this.id);
    };

    // Script onError handler
    this.onError = function() {
	    if(this.parentBatch)
		    this.parentBatch.onScriptLoad(this.id);
	    else
		    throw new Error("Error occured for: " + this.id);
    };
};