$(document).ready(function(){
	$('form.ajax-submit').submit(function(){
		if(!$(this).hasClass('loading')){
			var form = $(this);
			
			form.addClass('loading');
		
			form.find('.loading_off').fadeOut('fast',function(){
				form.find('.loading_on').fadeIn('fast',function(){
					submitData = new Object();
					
					submitData['json'] = true;
					
					form.find('input, textarea, select').each(function(){
						if($(this).attr('name')){
							type = $(this).attr('type');
							if(type=='radio' || type=='checkbox'){
								if($(this).is(":checked")){
									submitData[$(this).attr('name')] = $(this).val();
								}
							}
							else {
								submitData[$(this).attr('name')] = $(this).val();
							}
						}
					});
										
					$.ajax({
						type: "POST",
						url: form.attr('action'),
						data:submitData,
						dataType:"json",
						error: function(){
							alert('An unexpected error occurred. Please try again');
							
							form.removeClass('loading');
							form.find('.loading_on').fadeOut('fast',function(){
								form.find('.loading_off').fadeIn('fast');
							});
						},
						success: function(response){
							alertMsg = "";
														
							if(response.errors){
								for(i in response.errors){
									alertMsg += " - " + response.errors[i] + "\n";		
								}
							}
							
							if(alertMsg){
								alert("The following errors occurred:\n" + alertMsg);	
							}
							else {
								if(response.form_replace_html){
									form.slideUp('fast',function(){
										form.html(response.form_replace_html);
										form.slideDown('fast');
									});
								}
								else {
									if(response.evaluate){
										eval(response.evaluate);	
									}
									else {
										alert('Thank you. Your details have been saved.');	
									}
								}
							}
							
							form.removeClass('loading');
							form.find('.loading_on').fadeOut('fast',function(){
								form.find('.loading_off').fadeIn('fast');
							});

						}
					});
				});
			});
		}
		
		return false;
	});
});
