﻿(function ($) {
	$.PanelLoader = {
		Defaults: {
			BackURL: "",
			FieldsetID: "",
			SectionClass: ".ProfileSection",
			FadeSpeed: "slow"
		},
		Create: function () { return new PanelLoader_component(); }
	};

	$.fn.PanelLoader = function (settings) {
		return this.each(function () {
			var config = $.extend({}, settings);
			if (config !== false) {
				new PanelLoader_component().Init(this, config);
			}
		});
	};

	function PanelLoader_component() {

		var backURL;
		var fadeSpeed;

		return {
			Settings: $.extend({}, $.PanelLoader.Defaults),

			Init: function (element, config) {
				this.Settings = $.extend(true, {}, this.Settings, config);

				backURL = this.Settings.BackURL;
				fadeSpeed = this.Settings.FadeSpeed;
				var parent = $(element).find(this.Settings.SectionClass);
				var legend = $(element).find("legend");

				$(element).find("a.SectionLink").click(function () {
					var linkText = $(this).text();
					var href = $(this).attr("href");

					// Load the linked seciton into the parent div
					parent.load(href, function () {
						if (parent.find("form").length == 1) {

							// Alter the legend in the parent
							savedLegendText = legend.text();
							legend.html("<a href=\"#\">" + savedLegendText + "</a> -> " + linkText);
							legend.find("a").unbind();

							legend.find("a").click(function () {
								parent.load(backURL).hide().fadeIn(fadeSpeed);
								legend.text(savedLegendText);
								return false;
							});

							// Hijack the post of the inside form to work via our JSON format
							parent.find("form").each(function () {
								var form = $(this);
								form.submit(function () {
									var formPostTo = $(this).attr("action");
									var formAction = $(this).attr("action");
									var formMethod = $(this).attr("method");
									var formdata = $(this).serialize();

									$.ajax({
										type: 'POST',
										url: formPostTo,
										data: formdata,
										success: function (data) {
											if (HandleMessages(data)) {
												// Success. Transition back to where we came from
												parent.load(backURL).hide().fadeIn(fadeSpeed);
												legend.text(savedLegendText);
											}
										},
										error: function () {
											alert("Mechanistic error submitting form.");
										},
										dataType: "json"
									});

									return false;
								});
							});
						}
						else {
							alert("You must use only one form inside a profile panel");
							return false;
						}
					});

					return false;
				});
			}
		};
	};
})(jQuery);
