/*
 * Build forms using dform jQuery plugin
*/


(function($) {
	$.fn.iform = function(options) {
		
		var defaults = {
				formsPath : "forms/",
				scriptsPath : "",
				scriptsExtension : ".json"
		};
		var options = $.extend(defaults, options);
		
		return this.each(function() {
			var obj = $(this);
			iId = $(this).attr("id");
			iFormPath = options.formsPath + iId + options.scriptsExtension;
			$.getJSON(iFormPath, function(data) {
				obj.buildForm(data);
				setBackground();
				obj.bind("submit", function() {
					var object = $(this);
					if(object.valid()) {
						var action = options.scriptsPath + object.attr("action");
						var objData = object.serializeArray();
						$.ajax({
							url: action,
							data : objData,
							success : function(data) {
								
							    /*dataParsed = jQuery.parseJSON(data);
							    console.log(dataParsed);*/
						    	object.children().remove();
						    	object.append("<p class=\"message\">" + data.message + "</p>");
						    	$("html, body").animate({ scrollTop: 0 }, "slow");
						    	setBackground();
							}
						})
							.fail(function() {
								object.children().remove();
						    	object.append("<p class=\"message\">Your request could not be sent!. <br/> Try again later or contact us via <a href=\"mailto:contact@ezlegacy.com\">email</a></p>");
						    	$("html, body").animate({ scrollTop: 0 }, "slow");
						    	setBackground();
							});
						
					} else {
						setBackground();
					};
					return false;
				});

			});
		});
		function setBackground() {
			 if ($.browser.msie) {
				 if($("#content").height() < $(window).height()) {
					height = $(window).height();
				 } else {
					height = $("#content").height();
				 }
				 $("#back").height(height);
				 $("#content").height(height);
			 } else {
				 $("#back").height($("#content").height());
			 }
		};
	};

})(jQuery);

$(window).load(function(){
	$(".dform").iform(
		{
			formsPath : "forms/build/",
			scriptsPath : "forms/process/",
			scriptsExtension : ".php"			
		}
	);
});
