var EnvelopeClass = {
	init: function(p, suppressMsg) {
		$.extend(this, EnvelopeClass);

		var response = false, ptype = typeof p;
		
		// optional contructor parameter to prevent the default 
		// message handling logic from displaying the ui message.
		// Primarily a work around for forms in thickboxes.
		this.suppressMsg = suppressMsg;

		if(ptype == "object") {
			if(p.responseText) {
				// XML redirect response
				if(p.responseXML && p.responseXML.baseURI) {
					response = {redirectUrl: p.responseXML.baseURI};
//				ptype = "object"
				}
				// Use the responseText (in the next if block)
				else {
					p = p.responseText;
					ptype = "string";
				}
			}
			else {
				response = p; // object
			}
		}
		if(ptype == "string") {
			p = $.trim(p);
			if(!p) return;

			// Typical (json)
			if(p.charAt(0) == "{" && p.slice(-1) == "}") {
				response = this.toObj(p);
			}
			// Error (display)
			else {
				var parts = p.replace(/[^ -~]+/g, " ").match(/^(.*?)({"redirectUrl".*})\s?(.*)$/);
				if(parts) {
					// remove payload 
					p = $.trim(parts[1] || "") + $.trim(parts[3] || "");

					// production (hide errors...)
					try {
						response = this.toObj(parts[2]);
					}
					catch(e) {
						response = false;
					}
				}
				else {
					// pre for print_r
					p = "<pre>" + p + "</pre>"; 
				}

				// debug messages
				//  NB: true === true is converted to false in minimized code
				if(true === true) {
					// shorten if too long
					if(p.length > 1024) {
						p = p.substring(0,1024) + "<b>...</b>";
					}

					// build error message
					p = [
						'<div class="message errorMessage">',
						'<span class="delete-icon js-delete-uimessage"></span>',
						'<div class="messageIcon errorMessageIcon"></div>',
						'<div class="messageBody">',
						'<h4>AJAX Error</h4>', p,
						'<br/></div></div>'
					].join("");

					// show and exit
					this.showMessage(p);
				}
			}
		}

		if(!response) {
			// build error message
			p = [
				'<div class="message errorMessage">',
				'<span class="delete-icon js-delete-uimessage"></span>',
				'<div class="messageIcon errorMessageIcon"></div>',
				'<div class="messageBody">',
				'<h4>Error</h4>An unexpected error occurred with your request. Please try again later or contact customer care.',
				'<br/></div></div>'
			].join("");

			// show and exit
			this.showMessage(p);
			return;
		}
		
		// allow caller to access the full response
		this.fullResponse = response;

		if(response.redirectUrl) {
			// commenting out on release night 07-22-2010 - breaking searchmls in CRM
			//window.location.href.indexOf(response.redirectUrl) == -1 
			//	? window.location = response.redirectUrl
			//	: window.location.reload();
			
			window.location = response.redirectUrl;
		}
		else {
			this.payload = response.payload ? response.payload : {};
				
			if(response.message) {
				this.showMessage(response.message);
			}
			else if(response.messagesUrl) {
				$(window.parent.document.body).find("#messageWrapper").load(response.messagesUrl + " #messageWrapper > div", this.showMessage);
			}
//		else {
//			this.hideMessage();
//		}
				
			if(window.profilerOn && window.profilerInit && response.profilerContent) {
				$(window.parent.document.body).find("#profilerAjaxWrapper").append(response.profilerContent);
				profilerInit();
			}
		}
		
		
	},
	toObj: function(json) {
		// borrowed from jQuery-1.4
		if (window.JSON && window.JSON.parse) {
			return window.JSON.parse(json);
		}
		else {
			return (new Function("return " + json))();
		}
	},
	showMessage: function(html) {
		if (this.suppressMsg) {
			return;
		}
		
		var msgDiv = $("#messageWrapper");
		var parentWin = false;

		// not found here locally (check parent)
		if(msgDiv.length === 0) {
			msgDiv = $(window.parent.document.body).find("#messageWrapper");
			parentWin = true;
		}
		// nothing to do!
		if(msgDiv.length === 0) return;

		if(html) {
			msgDiv.append(html).show().data("complete", false);
		}
		else {
			msgDiv.show().data("complete", false);
		}

		if(parentWin) {
			window.parent.scroll(0,0);
		}
		else {
			window.scroll(0,0);
		}

		this.message = true;
		// show for at least 5 sec
		setTimeout(function() {msgDiv.data("complete", true); msgDiv = null}, 5000); 
	},
	hideMessage: function() {
		var msgDiv = $("#messageWrapper", window.parent.document.body);

		if(msgDiv.html() && msgDiv.data("complete") === true) {
			msgDiv.html("").data("complete", false);
		}

		msgDiv = null;
	},
	payload: {},
	fullResponse: false,
	message: false,
	suppressMsg: false
};
var Envelope = EnvelopeClass.init;

