$(document).ready(function(){

	$('.form-ajax input:text').placeholder();
	
	$('.form-ajax').bind('submit',function() {
			
		val = serialize_form(this);	
		
		var invia = $.when(			
			$.post("catalog/view/theme/brend/form_framework/invia.php", val, '', "json")		
		);
		
		invia.then($.proxy(function(resp) {			
			clear_error();
			if (resp.report) show_response(resp.msg.send, this);
			else report_errori(resp.msg, this);		
		},this));
		
		return false;
	});

});

// ======================================================================
// Funzione serializza form

function serialize_form(form) {
	var array = $(form).serializeArray();
	return serialize_object(array);
}

// ======================================================================
// Funzione serializza array

function serialize_object(array) {
	var object = {};
	$.each(array, function() {
		if (object[this.name]) {
			if (!object[this.name].push) {
				object[this.name] = [object[this.name]];
			}
			object[this.name].push(this.value || '');
		} else {
			object[this.name] = this.value || '';
		}
	});
	return object;
}

// ======================================================================
// Funzione show_response

function show_response(resp, form) {
	
	// reset form
	$(form).find(':input').removeAttr('checked').removeAttr('selected');
	$(form).find('input:text, textarea').val('');
	$(form).find('input:text').placeholder();
	$(form).find('select').val('');
	$(form).find('input.disabled').attr('disabled','disabled');
	$(form).find('input.checked').attr('checked','checked');
	
	var message = '<span class="message_ok">' + resp + '</span>';
	$(form).prepend(message);	
	
}

// ======================================================================
// Funzione report errori

function report_errori(report, form) {

	for (var fields in report) { 
		var message = '<span class="message_error">' + report[fields] + '</span>';
		$(form).prepend(message).addClass('error');
		$("*[name='"+fields+"']").addClass('error');
	}
	
	$('.error input, .error textarea').bind('focus click',function() {
		$(this).removeClass('error');
	});
}

function clear_error() {
	$('.error').removeClass('error');
	$('.message_error, .info_error').remove();
}

// ======================================================================
// Gestione Placeholder

(function($){
	$.fn.placeholder = function(){												
		
		return this.each(function() {
			
			$(this).val($(this).attr('placeholder')).addClass('placeholder');
			
			$(this).bind('focus', function() {
				if ($(this).hasClass('placeholder')) $(this).val('').removeClass('placeholder');
			});
			
			$(this).bind('blur', function() {
				if (!$(this).val()) $(this).val($(this).attr('placeholder')).addClass('placeholder');
			});
			
		});
	};
})(jQuery);
