/***************************************************************
dropdown_input.js - AJAX dropdown list

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

This file depends on:
  1. jQuery
  2. misc.js

***************************************************************/
var DropDownFields = {};

// our constructor
function DropDownInputController(options) {
	// console.log('DropDownInputController', 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_dropdown = dictionary_fetch(
		options,
		'id_dropdown', 
		'#dropdown'
	);
}

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

			// this.readFromDatabase();
			
			return this;
		},
		
		toString: function() {
			return '<DropDownInputController>';
		},

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

		forceSync: function() {
			// console.log("forcesync");
			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
DropDownInputController.setup = function(options) { return new DropDownInputController(options).setup(); };

