﻿// ajax forms
$(window).load(function() {
	// enable the forms
	
	$("form[ajax='true']").each(function() {
		var jthis = $(this);
		
		var target = jthis.attr("action");
		
		// surround with container to find the height
		jthis.wrap(document.createElement("div"));
		var container = jthis.parent();

		// get the size
		var h = jthis.height();
		var w = jthis.width();

		// make positioning fixed
		container.css("position","relative").css("width", w + "px").css("height", h + "px");

		// attach a div element
		var replacement = $(document.createElement("div"));
		replacement.css("position", "absolute").css("width", w + "px").css("height", h + "px").css("top", "0px");
		replacement.css("background-color", "white").css("opacity", ".8").css("display", "none");

		container.append(replacement);
		
		jthis.bind("submit", function() {
			var loadingAnimation = $(document.createElement("img"));
			loadingAnimation.attr("src", "/images/loadingAnimation.gif").css("position", "absolute").css("top", Math.round((h - 7)/2) + "px").css("left", Math.round((w - 104)/2) + "px");
			
			replacement.append(loadingAnimation).css("opacity", ".8").css("display", "block");
			
			// get the values
			var pData = {}
			jthis.find("input,textarea").each(function() {
				if(this.name.length > 0) pData[this.name] = this.value;
			});
			jthis.find("select").each(function() {
				if(this.name.length > 0) {
					pData[this.name] = this.options[this.selectedIndex].value;
				}
			});

			$.post(target, pData, function(data) {
				// show result
				replacement.css("opacity", "1").empty().html(data);
				replacement.one("click", function() {
					replacement.css("display","none");
				});
			});
			
			return false;
		});
		
	});
	
});
