/***************************************************************
matrix_input.js - form submit/sync via AJAX

Copyright 2010 - Simon Strandgaard <simon@bee3.com>

This file depends on:
  1. jQuery
  2. misc.js
  3. htmlentities.js
  4. get_html_translation_table.js
  5. typewatch.js

***************************************************************/


// our constructor
function MatrixInputController(options) {
	// console.log('MatrixInputController', options);

	this.m_content_uid = dictionary_fetch(
		options,
		'content_uid', 
		'0'
	);
	
	this.m_write_to_database_url = dictionary_fetch(
		options,
		'write_to_database_url', 
		'write_to_database.php'
	);
	
	this.m_id_form = dictionary_fetch(
		options,
		'id_form', 
		'#the_form'
	);
}

// prototype assignment
MatrixInputController.prototype = (function() {
	return {
		constructor: MatrixInputController,
		
		setup: function() {
			// console.log("setup");
			var thisObj = this;
			
			$(this.m_id_form + ' input').each(function() {
				var obj = $(this);
				obj.change(function() { thisObj.typewatchNotify(obj); });
			});
			$(this.m_id_form + ' input').each(function() {
				var obj = $(this);
				obj.typeWatch({ 
					callback: function() { thisObj.typewatchNotify(obj); } 
				});
			});
			return this;
		},
		
		toString: function() {
			return '<MatrixInputController>';
		},

		writeToDatabase: function(obj) {
			// console.log('writeToDatabase', this.m_content_uid, this.m_id_textfield);
			
			var value = obj.val();
			var name = obj.attr('name');
			// console.log('name', name, 'value', value);
			
			var data = {
				name: name,
				value: value
			};

			$.ajax({
				url: this.m_write_to_database_url,
				cache: false,
				context: this,
				data: data,
				success: function(text) { this.writeToDatabaseCallback(text); }
			});

		},

		writeToDatabaseCallback: function() {
			// console.log('callback', this.m_content_uid);
			
			// NICE: indicate that the textfield has been saved
		},

		typewatchNotify: function(obj) {
			// var name = obj.attr('name');
			// console.log('typewatchNotify', this.m_content_uid, name);
			this.writeToDatabase(obj);
		}

	};
})();

// factory method
MatrixInputController.setup = function(options) { return new MatrixInputController(options).setup(); };

