/***************************************************************
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

***************************************************************/
var txsObj = {};

// our constructor
function MultilineTextInputController(options) {
	// console.log('MultilineTextInputController', 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_read_from_database_url = dictionary_fetch(
		options,
		'read_from_database_url', 
		'read_from_database.php'
	);
	
	this.m_id_textarea = dictionary_fetch(
		options,
		'id_textarea', 
		'#the_textarea'
	);
	
	this.m_id_button = dictionary_fetch(
		options,
		'id_button', 
		'#the_button'
	);
	
}

// prototype assignment
MultilineTextInputController.prototype = (function() {
	return {
		constructor: MultilineTextInputController,
		
		setup: function() {
			// console.log("setup");
			var thisObj = this;
			
			$(this.m_id_button).click(function() {     
				thisObj.forceSync();
			});

			$(this.m_id_textarea).typeWatch({ 
				callback: $.proxy(thisObj.typewatchNotify, thisObj) 
			});
			
			// this.readFromDatabase();
			
			return this;
		},
		
		toString: function() {
			return '<InputController>';
		},

		writeToDatabase: function() {
			// console.log('writeToDatabase', this.m_content_uid, this.m_id_textarea);
			
			var textarea_value = $(this.m_id_textarea).val();
			// console.log('textarea_value', textarea_value);
			
			var data = {
				textarea_value: textarea_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 textarea has been saved
		},

		forceSync: function() {
			this.writeToDatabase();
		},
			             
		typewatchNotify: function() {
			// console.log('typewatchNotify', this.m_content_uid);
			this.writeToDatabase();
		},
		
		readFromDatabase: function() {
			// console.log("reading from database");
			$.ajax({
				url: this.m_read_from_database_url,
				cache: false,
				context: this,
				// data: data,
				success: function(text) { this.readFromDatabaseCallback(text); }
			});
		},
		
		readFromDatabaseCallback: function(text) {
			// console.log('callback', this.m_content_uid, text);
			$(this.m_id_textarea).val(text);
		}

	};
})();

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

