/**
 * @namespace This contains generic methods to create a uniform style for modals.
 * @author Tom McCourt / Oliver Bishop
 * @version 0.0.2
 * @changeLog Add an ajax load page function.
 * @changeLog Added a check to make sure only same id containers are visible toggled. New id modals are created from scratch.
 * @changeLog Created.
 */

UKISA.namespace("UKISA.widget.Modal");

/**
 * Global dialog templates that use YUI Container widgets to allow a consistent look of the site.
 */
UKISA.widget.Container = null;

/**
 * Create a modal instance.
 *
 * @returns YAHOO.widget.Panel Returns a YAHOO.widget.Panel instance.
 * @example 
 * var modal = new UKISA.widget.Modal("my-id", "Some content");
 * modal.show();
 */
UKISA.widget.Modal = function(id, content, options) {
	var panel, hd, bd, ft, container, loader, body, ajax, container;

	panel = document.getElementById(id);

	container = UKISA.widget.Container;

	// This is a default content placeholder - simply has a "loading" message.
	loader = function() {
		var a = document.createElement("p");
		a.id = id + "-loading";
		a.className = "loading";
		a.innerHTML = "Please wait...";

		return a;
	};

	body = content || loader();

	if (panel && container && (id === container.id)) {
		container.setBody(body);

		return container;
	} else {
		// If the id's do not match then we may be dealing with a different style, so reset it.
		if (container && id !== container.id) {
			container.hide();
			container.destroy();
		}

		// This creates the custom shadow around the Panel box.
		panel = document.createElement("div");

		hd = panel.cloneNode(false);
		bd = panel.cloneNode(false);
		ft = panel.cloneNode(false);

		panel.id = id;
		panel.className = "yui-panel-container yui-dialog shadow";
		hd.className = "hd";
		bd.className = "bd";
		ft.className = "ft";

		panel.appendChild(hd);
		panel.appendChild(bd);
		panel.appendChild(ft);

		document.body.appendChild(panel);

		UKISA.widget.Container = new YAHOO.widget.Panel(id, { 
			fixedcenter: true,
			modal: true,
			visible : false,	
			close: true,
			underlay: "shadow",
			constraintoviewport: true,
			zIndex: 500,
			autofillheight: "body"
		});
		
		container = UKISA.widget.Container;

		container.setBody(body);

		container.render(document.body);

		container.hideAndDestroy = function() {
			container.hide();

			YAHOO.lang.later(100, container, function() {
				this.destroy();
			}, null, false);
		};

		// Add some extra functionality.
		container.load = function(type, url, callback, qs) {
			callback = callback || {
				success: function(o) {
					container.setBody(o.responseText);
				}, 
				failure: function(o) {
					container.setBody([
						'<p class="error">',
							'Sorry, there was a problem when trying to fetch something. Please close this down and try again.',
						'</p>'
					].join(""));
				}, 
				timeout: 5000
			};

			this.ajax = YAHOO.util.Connect.asyncRequest(type, url, callback, qs);
		};

		return container;
	}
};