var VignettePortal = new Object();
VignettePortal.portalContext = "/portal"; //set portal context url

if (typeof this['vuit_defined'] == 'undefined')
{
    // loads only vuit "base"
    vuitConfig = {
        baseUrl: VignettePortal.portalContext + '/jslib/vuit/',     // this is where all module paths will be relative to
        modulePaths: {
            'vapui': VignettePortal.portalContext + '/jslib/vapui'
        },
        isDebug: false,                     // no debug output by default
        parseOnLoad: false                  // dont parse pages for widgets/connects by default
    };

	try {
		if (typeof vuit !== 'undefined') {
			delete vuit;
		}
	} catch (ex) {
		vuit = undefined;
	}

     //document.write("<script type='text/javascript' src='" + VignettePortal.portalContext + "/jslib/vuit/vuit.js.uncompressed.js'><" + "/script>")
    document.write("<script type='text/javascript' src='" + VignettePortal.portalContext + "/jslib/vuit/vuit.js'><" + "/script>");

    vuit_defined = 1.0; // defines vuit_defined to avoid re-loading the same lib.
}

VignettePortal.AJAXClient = function() {}

VignettePortal.AJAXClient.prototype = {
    _getHandlerType: function(data, props) {
       // summary: private method to return one of "load", "error", "timeout" to describe the response
        var type = "load";
        if(typeof props.vuitType != "undefined") {
            type = vuitType.toString()
        }
        return type;
    },
// sends the data to the URL in AJAX style and invokes the callback method
    sendURL :  function(url, callbackMethod) {
        var requestArgs = {
            url: url,
            load: vuit.hitch(this, function(data, ioArgs) {
                this.processResponse("load", data, ioArgs.xhr, callbackMethod);

            }),
            error: vuit.hitch(this, function(data, err) {
                var type = this._getHandlerType(data, ioArgs);
                this.processResponse(type, data, ioArgs.xhr, callbackMethod);
            })
        };
        vuit.xhrGet(requestArgs);
        return false;
    },


// sends the form data to the Action URL of the Form in AJAX style and
//invokes the callback method
    sendForm : function(formNodeValue, callbackMethod) {
        // get the method in Propercase
        var xhrMethod = (typeof formNodeValue.method != "undefined") ? formNodeValue.method.toLowerCase() : "get";
        xhrMethod = "xhr" + xhrMethod.charAt(0).toUpperCase() + xhrMethod.substring(1);
        // call the appropriate vuit method (e.g. vuit.xhrGet)
        var requestArgs = {
            form: formNodeValue,
            load: vuit.hitch(this, function(data, ioArgs) {
                this.processResponse("load", data, ioArgs.xhr, callbackMethod);

            }),
            error: vuit.hitch(this, function(data, err) {
                var type = this._getHandlerType(data, ioArgs);
                this.processResponse(type, data, ioArgs.xhr, callbackMethod);
            })
        };
        vuit.xhrPost(requestArgs);
        return false;
    },

// posts the multipart form data to the Action URL of the Form in AJAX style and
//invokes the callback method

    sendMultiPartForm : function(formNodeValue, callbackMethod, responseMimeType) {
        if (responseMimeType == null)
            responseMimeType = "text/plain";

            var url = formNodeValue.action;
            if(url.indexOf("#") > -1) {
                url = url.split("#")[0];
            }
            vuit.io.iframe.send({
                url: url,
                method: "POST",
                form: formNodeValue,
                handleAs: "html",
                //timeoutSeconds: 10,
                preventCache: true,
                load: vuit.hitch(this, function(data, ioArgs) {
					if(typeof data.nodeType !== "undefined" && data.nodeType == 9) {
						var bodyElm = "";
						if (data.body.innerHTML) {
							bodyElm = data.body.innerHTML;
						} else if (data.getElementsByTagName("body")[0].innerHTML) {
							bodyElm = data.getElementsByTagName("body")[0].innerHTML
						}
						//bodyElm = data.body || data.getElementsByTagName("body")[0];
						data = bodyElm;
					}
                    this.processMultiPartResponse("load", data, ioArgs, callbackMethod);
                }),
                error: vuit.hitch(this, function(data, err) {

                    var type = this._getHandlerType(data, err);
                    this.processMultiPartResponse(type, data, err, callbackMethod);
                })
            });
        return false;
    },

    // handles AJAX response by doing some preliminary error handling
    processResponse : function (type, data, evt, callback) {
        var isValidResponse = evt.getResponseHeader("X-Vignette-RespondedWith");
        if (isValidResponse != "AJAX") {
            // If the response is not valid (i.e., timeout, error), display it in the cuurent window
            // FIXME: this leaks!
            window.document.body.innerHTML = evt.responseText;
            return;
        }
        else {
            callback(evt);
        }
    },

    // handles Multipart response
    processMultiPartResponse : function (type, data, evt, callback) {
        callback(data);
    },

	// finds javascript in a text fragment and adds to the document
	addScripts : function (frag) {
		var pattern = /<script[^>]*?language="javascript"[^>]*?>([\s\S]*?)<\/script>/gi;
		var rePattern = new RegExp(pattern);
		var result
		while((result = rePattern.exec(frag)) != null) {
			this.evalInGlobal(result[1]);
		}

		pattern = /<script[^>]*?id=[^>]*>([\s\S]*?)<\/script>/gi;
		rePattern = new RegExp(pattern);
		while((result = rePattern.exec(frag)) != null) {
			this.evalInGlobal(result[1]);
		}

		// This second check looks for script tags that have a src attribute
		// <script type="text/javascript" src="/portal/jslib/epi-utils.js"></script>
		pattern = /<script[^>]*?type="text\/javascript"[^>]*?src=\"([^"]*?)\"/gi;
		rePattern = new RegExp(pattern);
		while((result = rePattern.exec(frag)) != null) {
			this.evalInGlobalSrc(result[1]);
		}
	},

	evalInGlobal : function (code) {
		appendNode = document.body;
		var n = appendNode.ownerDocument.createElement('script');
		n.type = "text/javascript";
		appendNode.appendChild(n);
		n.text = code;
	},

	evalInGlobalSrc : function (code) {
		appendNode = document.body;
		var n = appendNode.ownerDocument.createElement('script');
		n.type = "text/javascript";
		appendNode.appendChild(n);
		n.src = code;
	}
};
