// JScript File
/*
 * Dillo Ad AMA jQuery interface
 * Copyright (c) 2009  Oliver Astrologo
 * Dual licensed under MIT and GPL.
 * @author  Oliver Astrologo
 * @version 1.1
 */



function showRequest(XMLHttpRequest) {
	//jQuery("#loading-indicator").show();
	jQuery('#form-submit-response').addClass("ac_loading");
	jQuery("#form-submit").attr("disabled", "true");
}

function showError(XMLHttpRequest, textStatus, errorThrown) {
	//console.log( textStatus);
	jQuery('#form-submit-response').removeClass("ac_loading");
	jQuery("#form-submit").removeAttr("disabled");	
	alert('Spiacenti ma al momento non è possibile inviare i dati.');
	jQuery.ajax({		
		type: "POST",
		dataType: 'json',   
		cache: false,
		beforeSend: null,   
		error: null,
		url: "/data-sources/error.php",
		data: {
			error_dump : errorThrown + ' ' + textStatus				
		},      
		success: null
	});
}

function processFormData(formAction){
	jQuery(".std-input").removeClass("error");	
	jQuery(".error-input-msg").fadeOut().html("");		
	jQuery("#form-submit").attr("disabled", "true");		
	var postData = jQuery("#form-dillo-ad-ama").serialize();
	
	jQuery.ajax({		
			type: "POST",
			dataType: 'json',   
			cache: false,
			beforeSend: showRequest,   
			error: showError,
			url: formAction+"?mode=ajax",
			data: postData,      
			success: function(data){searchResponse(data);}
		}); 
	
		
} 		

function searchResponse (data) {				 
	jQuery('#form-submit-response').removeClass("ac_loading");
	jQuery("#form-submit").removeAttr("disabled");	
	var responseStatus = data.responseStatus;
	if (responseStatus == 'OK'){
		jQuery("#form-area").animate({
			opacity: 0		
			}, 1000, function() {
				jQuery("#form-area").hide();
				jQuery('html, body').animate({
					scrollTop: jQuery("#form-area").offset().top
				}, 1000);
				jQuery("#form-message").fadeIn();
				
		});		
	}else{
		var errorsArray = data.errors;
		jQuery.each(errorsArray, function(index, value) { 		
			jQuery("#"+value.field).addClass("error");
			jQuery("#"+value.field+"-error").html(value.reason).fadeIn();
			
		
		});
		alert("Attenzione\nAlcuni campi non sono stati compilati correttamente, verifica e prova nuovamente.");
		jQuery('html, body').animate({
					scrollTop: jQuery("#form-area").offset().top
				}, 1000);
	}
}	

jQuery(function(){	
	jQuery("#form-dillo-ad-ama").submit(function () {processFormData(jQuery(this).attr('action'));return false;});	
	
});
