
var Fjson = function(process){

	var that = this;
	
	this.process = process || { get: {}, post: {} };
	this.data = {};
	
	this.parseDom = function(){
	
		var data = {}, fields = $('[data-fjson]'), keys;
		
		fields.each(function(i, el){
		
			el = $(el);
			keys = el.attr('data-fjson').split(',');
			
			that.setObjectValue(data, keys, el);
		});
		
		that.data = data; // TODO: rever esta propriedade. Está ruim. 
	};
	
	this.setObjectValue = function(obj, keys, el){
	
		var currentKey= keys.shift(),
				name = el.attr('name'), 
				value = el.val();
		
		obj[currentKey] = obj[currentKey] || {};
		
		if (keys.length === 0) {
			
			if (that.process.send && that.process.send[name]) {
				value = that.process.send[name](el);
			}
			 
			obj[currentKey][name] = value;
			return;
		}

		obj = that.setObjectValue(obj[currentKey], keys, el);
	};
	
	this.toDom = function(obj){
	
		var name, value, el;
		
		for (name in obj) {
			value = obj[name];
			(that.process.get[name]) ? value = process.get[name](value) : value = value; 
			
			if (typeof value === 'object') {
				that.toDom(value);
			}
			else {
				el = $("[name='" + name + "']");
				el.val(value);
			}
		}
	};

	return this;
};

