// Class for handling a message dialog interaction.
var Dialog = $.Class({
	initialize: function(parent_object, dialog_div, dialog_header, fields, callbacks) {
		this.parent_object = parent_object;
		this.dialog_div = dialog_div;
		this.fields = fields;
		this.dialog_header = dialog_header;
		this.callbacks = callbacks;
		this.mode = 'add';
		this.current_key = "";
		this.handle_enter_key = true;
		this.first_open = true;
		this.is_dirty = false;
		this.ignore_dirty = false;
		this.initialize = true;
		this.no_post = false;
		this.remote_option_request_count = 0;
	},
	
	// Returns the Name and ID given the field name.
	getFieldID: function(name)
	{
		var result = this.dialog_header.name + '_' + name;
		return result;
	},
	
	// Returns the unique dialog name.
	getDialogName: function()
	{
		return '#dialog_' + this.dialog_header.name;
	},
	
	getFieldValue: function(field_name)
	{
		var field_id  = this.getFieldID(field_name);
		return $('#' + field_id).val();
	},
	
	showBlock: function()
	{
		block();
	},

	unblock: function()
	{
		unblock();
	},
	
	// Render the dialog to the html div tag.
	render: function()
	{
		var html = '';
		
		this.ignore_dirty = false;
		
		html += '<div id="dialog_' +  this.dialog_header['name'] + '" title="New ' + this.dialog_header['title'] + '" class="jui-dialog">';
		html += '<fieldset>';
		html += '<table width="100%" cellpadding=5>';
		for (var c = 0; c < this.fields.length; c++)
		{
			if (c == 0) {
				html += '<tr>';
				html += '<td colspan="' + this.fields.length + '" valign="top">';
			}
			else {
				if (c == this.fields.length-1) {
					html += '<td valign="top">';
				}
				else {
					html += '<td valign="top" class="jui-dialog-field-width">';
				}
			}
			
			// Generate the field controls for the form.
			for (var i = 0; i < this.fields[c].length; i++)
			{
				var field = this.fields[c][i];
			
				
				if ((field['type'] != 'spacer') && (field['type'] != 'checkbox')) {
					html += '<div class="jui-dialog-label">';
					html += '<label for="' + this.getFieldID(field['field_name']) + '">' + field['title'] + ':</label>';
				}
				else {
					if ((field['type'] != 'checkbox')) {
						html += '<div class="jui-dialog-label-spacer">';
						html += '<label for="' + this.getFieldID(field['field_name']) + '">' + field['title'] + '</label>';
					}
				}
				html += '</div>';
			
				if (field['type'] == 'text_field') {
					html += '<div class="jui-field-large"><input class="jui-field-text-field" type="text" name="' + this.getFieldID(field['field_name']) + '" id="' + this.getFieldID(field['field_name']) + '" value="" maxlength="' + field.maximum + '" /></div>';
					
				}
				else if (field['type'] == 'small_text_field') {
					html += '<div class="jui-field-small"><input class="jui-field-text-field" type="text" name="' + this.getFieldID(field['field_name']) + '" id="' + this.getFieldID(field['field_name']) + '" value="" maxlength="' + field.maximum + '" /></div>';
					
				}
				else if (field['type'] == 'url') {
					html += '<div class="jui-field-large"><input class="jui-field-text-field" type="text" name="' + this.getFieldID(field['field_name']) + '" id="' + this.getFieldID(field['field_name']) + '" value="" maxlength="' + field.maximum + '" /></div>';
					
				}
				else if (field['type'] == 'password') {
					html += '<div class="jui-field-large"><input class="jui-field-text-field match_input" type="password" name="' + this.getFieldID(field['field_name']) + '" id="' + this.getFieldID(field['field_name']) + '" value="" maxlength="' + field.maximum + '" /></div>';
				}
				else if (field['type'] == 'text_area') {
					var rows = '';
					var cols = '';
					if (field['rows'] != null) {
						rows = field['rows'];
					}
					if (field['cols'] != null) {
						cols = field['cols'];
					}
					html += '<div class="jui-field-large"><textarea style="resize:none;" class="jui-field-text-area" cols="' + cols + '" rows="' + rows + '" name="' + this.getFieldID(field['field_name']) + '" id="' + this.getFieldID(field['field_name']) + '"></textarea></div>';
				}
				else if (field['type'] == 'rich_text_area') {
					var rows = '';
					var cols = '';
					if (field['rows'] != null) {
						rows = field['rows'];
					}
					if (field['cols'] != null) {
						cols = field['cols'];
					}
					html += '<div class="jui-field-large-rich"><textarea class="jui-field-text-area" cols="' + cols + '" rows="' + rows + '" name="' + this.getFieldID(field['field_name']) + '" id="' + this.getFieldID(field['field_name']) + '"></textarea></div>';
				}
				else if (field['type'] == 'spacer') {
					html += '<div class="jui-field"></div>';
				}
				else if (field['type'] == 'date') {
					html += '<div class="jui-field"><input class="jui-field-date" type="text" name="' + this.getFieldID(field['field_name']) + '" id="' + this.getFieldID(field['field_name']) + '" value="" /></div>';
				}
				else if (field['type'] == 'color') {
					html += '<div class="jui-field"><div class="jui-field-color-sample" id="color_' + this.getFieldID(field['field_name']) + '">&nbsp;</div><input class="jui-field-color" type="text" name="' + this.getFieldID(field['field_name']) + '" id="' + this.getFieldID(field['field_name']) + '" value="" /></div>';
				}
				else if (field['type'] == 'autocomplete') {
					html += '<div class="jui-field-large"><input class="jui-field-autocomplete" type="text" name="' + this.getFieldID(field['field_name']) + '" id="' + this.getFieldID(field['field_name']) + '" value="" />';
					html += '<span class="jui-button-autocomplete-use"><input type="button" value="Use" id="useButton_' + this.getFieldID(field['field_name']) + '" /></span>';
					html += '</div>';
				}
				else if (field['type'] == 'number') {
					html += '<div class="jui-field"><input class="jui-field-float" type="text" name="' + this.getFieldID(field['field_name']) + '" id="' + this.getFieldID(field['field_name']) + '" value="" /></div>';
				}
				else if (field['type'] == 'email') {
					html += '<div class="jui-field-large"><input class="jui-field-text-field" type="text" name="' + this.getFieldID(field['field_name']) + '" id="' + this.getFieldID(field['field_name']) + '" value="" /></div>';
				}
				else if (field['type'] == 'integer') {
					html += '<div class="jui-field"><input class="jui-field-number" type="text" name="' + this.getFieldID(field['field_name']) + '" id="' + this.getFieldID(field['field_name']) + '" value="" /></div>';
				}
				else if (field['type'] == 'checkbox') {
					html += '<div class="jui-field-checkbox">' + '<input class="jui-field-float" type="checkbox" name="' + this.getFieldID(field['field_name']) + '" id="' + this.getFieldID(field['field_name']) + '" value="true" /> ' + field['title'] + '</div>';
				}
				else if (field['type'] == 'select') {
					html += '<div class="jui-field">';
				
					// if there is an onchange callback for this select option.
					html += '<select class="jui-field-select" name="' + this.getFieldID(field['field_name']) + '" id="' + this.getFieldID(field['field_name']) + '">';
				
					if (field['options'] != null) {
						for (var o = 0; o < field['options'].length; o++) {
							var option = field['options'][o];
							var style = '';
							if (option.style_class != null)
							{
								style = option.style_class;
							}
							html += '<option class="' + style + '" value="' + option.key + '">' + option.value + '</option>';
						}
					}
				
					html += '</select>';
				
					html += '<div id="' + this.getFieldID(field['field_name']) + '_data"></div>';
				
					html += '</div>';
				}
				else if (field['type'] == 'image') {
					html += '<div class="jui-field"><input class="jui-field-float" type="file" name="' + this.getFieldID(field['field_name']) + '" id="' + this.getFieldID(field['field_name']) + '" value="" /></div>';
					this.ignore_dirty = true;
				}
				if (field['notes'] != null) {
					html += '<div class="jui-field-notes">' + field['notes'] + '</div>';
				}
			}
			html += '</td>';
			
			if (c == 0) {
				html += '</tr>';
				html += '<tr>';
			}
			
		}
		html += '</tr></table>';
		html += '</fieldset>';
		html += '</div>';
		
		this.dialog_div.html(html);
		
		var ok_text = 'Ok';
		
		var width_dialog = 600;
		if (this.dialog_header['dialog_width'] != null) {
			width_dialog = this.dialog_header['dialog_width'];
		}
		
		$(this.getDialogName()).dialog({ 
			autoOpen: false, 
			modal: true, 
			width: width_dialog, 
			resizable: false, 
			autoResize:true, 
			buttons: 
				{ 	"Ok": this.oKButtonClicked, 
					"Cancel": this.cancelButtonClicked 
				} 
		});
			
		$(this.getDialogName()).dialog('option', 'dialog_class', this);
		$(this.getDialogName()).data("handle_key", true);
		
		var dialog_class = this;
		
		for (var c = 0; c < this.fields.length; c++)
		{
			// Setup jQuery UI controls.
			for (var i = 0; i < this.fields[c].length; i++)
			{
				var field = this.fields[c][i];
			
				$('#' + this.getFieldID(field['field_name'])).data("dialog_id", this.getDialogName());
				$('#' + this.getFieldID(field['field_name'])).focus(this.onFocused);
				$('#' + this.getFieldID(field['field_name'])).change(this.onChanged);
				$('#' + this.getFieldID(field['field_name'])).keyup(this.onChanged);
				$('#' + this.getFieldID(field['field_name'])).data("is_text_area", false);
				
				if (field['change_callback'] != null) {
					$('#' + this.getFieldID(field['field_name'])).change(field['change_callback']);
				}
			
				if (field['type'] == 'date') {
					$('#' + this.getFieldID(field['field_name'])).datepicker({
						numberOfMonths: 2,
						showButtonPanel: true
					});
								
					$("#ui-datepicker-div").addClass("promoteZ");
				}
				else if (field['type'] == 'color') {
					
					$('#' + this.getFieldID(field['field_name'])).ColorPicker({
						onSubmit: function(hsb, hex, rgb, el) {
							$(el).val(hex.toUpperCase());
							$(el).ColorPickerHide();
							
							var field_color_id = $('#color_' + dialog_class.getFieldID(field['field_name']));
							field_color_id.css("background-color", '#' + hex.toUpperCase());
							
							if ((dialog_class != null) && (!dialog_class.initialize)) {
								dialog_class.is_dirty = true;
							}
						},
						onBeforeShow: function () {
							$(this).ColorPickerSetColor(this.value);
						}
					})
					.bind('keyup', this.onChanged);
					$(".colorpicker").addClass("promoteZ");
				}
				else if (field['type'] == 'autocomplete') {
					var params = {};
					if (field['option_params'] != null) {
						params = field['option_params'];
					}
					
					$('#' + this.getFieldID(field['field_name'])).autocomplete(field['option_source'], params);
					$('#' + this.getFieldID(field['field_name'])).data("is_text_area", true);
					$('#useButton_' + this.getFieldID(field['field_name'])).click(this.dialogHandleAutoCompleteUse);
					$('#useButton_' + this.getFieldID(field['field_name'])).data("field_name", this.getFieldID(field['field_name']));
					$('#useButton_' + this.getFieldID(field['field_name'])).data("dialog_class", this);
				}
				else if (field['type'] == 'rich_text_area') {
					$('#' + this.getFieldID(field['field_name'])).data("is_text_area", true);
				}
				else if (field['type'] == 'select') {
					// Option source given, so get the options from the remote source.
					if ((field['option_source'] != null) && (field['option_key'] != null)) {
						var params = {};
						if (field['option_params'] != null) {
							params = field['option_params'];
						}
						this.getRemoteOptions(this.getFieldID(field['field_name']), field['option_source'], field['option_key'], field['allow_none'], params);
					}
				}
				else if (field['type'] == 'text_area') {
					$('#' + this.getFieldID(field['field_name'])).data("is_text_area", true);
				}
			}
		}
		
		var dialog = this;
		
		$(this.getDialogName()).validity();
		
		$(this.getDialogName()).keyup(this.keyUp);
		
	},
	
	onFocused: function()
	{
		var dialog_id = $('#' + this.id).data("dialog_id");
		var handle_key = $(dialog_id).data('handle_key');
		var is_text_area = $('#' + this.id).data("is_text_area");
		
		if (is_text_area == true) {
			$(dialog_id).data('handle_key', false);
		}
		else {
			$(dialog_id).data('handle_key', true);
		}
	},
	
	onChanged: function(id)
	{
		var control_id = '';
		if (id != null)
		{
			control_id = id.currentTarget.name;
		}
		else
		{
			control_id = this.id;
		}
		
		var dialog_id = $('#' + control_id).data("dialog_id");
		var handle_key = $(dialog_id).data('handle_key');
		var is_text_area = $('#' + control_id).data("is_text_area");
		
		var dialog_class = $(dialog_id).dialog('option', 'dialog_class');
		if ((dialog_class != null) && (!dialog_class.initialize)) {
			dialog_class.is_dirty = true;
		}
	},
	
	keyUp: function(e)
	{
		if (e.keyCode == 13) {
			var dialog_class = $('#' + this.id).dialog('option', 'dialog_class');
			var handle_key = $('#' + this.id).data('handle_key');
			if (handle_key == true) {
				dialog_class.handleOkClick(dialog_class);
			}
	    }
	},
	
	getDialogField: function(field_name)
	{
		for (var c = 0; c < this.fields.length; c++)
		{
			for (var i = 0; i < this.fields[c].length; i++)
			{
				var field = this.fields[c][i];
				if (this.getFieldID(field.field_name) == field_name)
				{
					return field;
				}
			}
		}
		
		return null;
	},
	
	// Handles auto complete "Use" button clicks.
	dialogHandleAutoCompleteUse: function()
	{
		var field_name = $('#' + this.id).data("field_name");
		var dialog_class = $('#' + this.id).data("dialog_class");
		var field_value = $('#' + field_name).val();
		
		var field = dialog_class.getDialogField(field_name);
		var fill_field = field['option_fill_field'];
		var current_value = $('#' + dialog_class.getFieldID(fill_field)).val();
		current_value = $.trim(current_value);
		var sep = "";
		if (current_value.length > 0) {
			if (current_value[current_value.length-1] != ',') {
				sep = ",";
			}
		}
		field_value = $.trim(field_value);
		if (field_value[field_value.length-1] == ',') {
			field_value = field_value.substring(0, field_value.length-1);
		}
		$('#' + dialog_class.getFieldID(fill_field)).val(current_value + sep + field_value);
		$('#' + field_name).val('');
	},
	
	setDefaultValue: function(field_name, value)
	{
		for (var c = 0; c < this.fields.length; c++)
		{
			for (var i = 0; i < this.fields[c].length; i++)
			{
				var field = this.fields[c][i];
				if (field.field_name == field_name)
				{
					field.default_value = value;
					
					break;
				}
			}
		}
		
		
	},
	
	setOptionKey: function(field_name, key, callback, callback_params)
	{
		for (var c = 0; c < this.fields.length; c++)
		{
			for (var i = 0; i < this.fields[c].length; i++)
			{
				var field = this.fields[c][i];
				if (field.field_name == field_name)
				{
					field.option_key = key;
					if ((field['option_source'] != null) && (field['option_key'] != null)) {
						var params = {};
						if (field['option_params'] != null) {
							params = field['option_params'];
						}
						this.getRemoteOptions(this.getFieldID(field['field_name']), field['option_source'], field['option_key'], field['allow_none'], params, callback, callback_params);
					}
					break;
				}
			}
		}
	},
	
	todayStr: function() 
	{
		var today = new Date();
		var month = today.getMonth() + 1;
		if (month < 10)
		{
			month = '0' + month;
		}
		
		return month + "/" + today.getDate() + "/" + (today.getFullYear());
	},
	
	triggerEvent: function( elem, type, event ) {
		if ( $.browser.mozilla || $.browser.opera || $.browser.safari || $.browser.chrome ) {
			event = document.createEvent("MouseEvents");
			event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
					0, 0, 0, 0, 0, false, false, false, false, 0, null);
			elem.dispatchEvent( event );
		} 
		else if ( $.browser.msie ) {
			elem.fireEvent("on"+type);
		}
	},
	
	clearFields: function()
	{
		var browser = $.browser
		
		var field;
		var field_name = '';
		var i;
		var default_value = '';
		
		for (var c = 0; c < this.fields.length; c++)
		{
			for (i = 0; i < this.fields[c].length; i++)
			{
				field = this.fields[c][i];
				field_name = this.getFieldID(field['field_name']);
			
				default_value = '';
				if (field.default_value != null) {
					default_value = field.default_value;
				}
				
				if (field['type'] == 'date')
				{
					if ((field.default_value == null) || (field.default_value.length <= 0))
					{
						default_value = this.todayStr();
					}
					else
					{
						default_value = field.default_value;
					}
				}
				else if (field['type'] == 'color') {
					var field_color_id = $('#color_' + this.getFieldID(field['field_name']));
					field_color_id.css("background-color", '#' + field.default_value);
				}
			
				$('#' + field_name).val(default_value);
				
			}
		}
		// Trigger the onchange for selects in case we have any
		// updates in the UI we want to make.
		for (var c = 0; c < this.fields.length; c++)
		{
			for (var i = 0; i < this.fields[c].length; i++)
			{
				field = this.fields[c][i];
				field_name = this.getFieldID(field['field_name']);
			
				default_value = '';
				if (field.default_value != null) {
					default_value = field.default_value;
				}
			
				if ((field['type'] == 'select') && (default_value.length > 0)) {
					var event;
					this.triggerEvent($('#' + field_name)[0], "change", event);
				}
			}
		}
	},
	
	getRemoteOptions: function(field_name, source, key, allow_none, params, callback, callback_parameters)
	{ 
		var callback_function = callback;
		var field_name = field_name;
		var callback_parameters = callback_parameters;
		var self = this;
		
		block();
		
		self.remote_option_request_count++;
		
		$.get(source + '/' + key, params,
			function(data)
			{
				var html = "";
				var data_html = "";
				var selected = "";
				
				if (allow_none != null) {
					if (allow_none == true) {
						html += '<option value="">None</option>';
					}
				}
				for (var i = 0; i < data.values.length; i++)
				{
					if (data.values[i].selected == true) {
						html += '<option selected="selected" value="' + data.values[i].key + '">' + data.values[i].value + '</option>';
						selected = data.values[i].value;
					}
					else {
						html += '<option value="' + data.values[i].key + '">' + data.values[i].value + '</option>';
					}
					
					if (typeof data.values[i].data != 'undefined') {
						if (data.values[i].data != null) {
							data_html += '<input type="hidden" value="' + data.values[i].data + '" id="' + field_name + '_' + data.values[i].key + '" />';
						}
					}
				}

				$('#' + field_name).html(html);
				$('#' + field_name + '_data').html(data_html);
				
				var field_id = $('#' + field_name);
				field_id.val(selected);
				
				self.remote_option_request_count--;
				if (self.mode == 'add') {
					self.clearFields();
				}
				
				if (callback_function != null) {
					callback_function(field_name, callback_parameters);
				}
				unblock();
				
			}, "json");
	},
	
	handleOkClick: function(dialog_class)
	{
		if ((dialog_class.is_dirty == false) && (dialog_class.ignore_dirty == false)) {
			$(dialog_class.getDialogName()).dialog('close');
			return;
		}
		
		if (dialog_class.dialog_header.update_path || dialog_class.dialog_header.insert_path || dialog_class.dialog_header.file_only)
		{
			if (dialog_class.mode == 'add')
			{
				dialog_class.insert(dialog_class);
			}
			else
			{
				dialog_class.update(dialog_class);
			}
		}
		else
		{
			if ((dialog_class.callbacks != null) && (dialog_class.callbacks['ok_clicked'] != null))
			{
				dialog_class.callbacks['ok_clicked'](dialog_class);
			}

			$(dialog_class.getDialogName()).dialog('close');
		}
	},
	
	// When OK is clicked.
	oKButtonClicked: function(button)
	{
		var dialog_class = $('#' + this.id).dialog('option', 'dialog_class');
		
		if ((dialog_class.is_dirty == false) && (dialog_class.ignore_dirty == false)) {
			$(dialog_class.getDialogName()).dialog('close');
			return;
		}
		
		if (dialog_class.dialog_header.update_path || dialog_class.dialog_header.insert_path || dialog_class.dialog_header.file_only)
		{
			if (dialog_class.mode == 'add')
			{
				dialog_class.insert(dialog_class);
			}
			else
			{
				dialog_class.update(dialog_class);
			}
		}
		else
		{
			if ((dialog_class.callbacks != null) && (dialog_class.callbacks['ok_clicked'] != null))
			{
				dialog_class.callbacks['ok_clicked'](dialog_class);
			}

			$(dialog_class.getDialogName()).dialog('close');
		}
	},
	
	// When Cancel is clicked.
	cancelButtonClicked: function(button)
	{
		var dialog_class = $('#' + this.id).dialog('option', 'dialog_class');
		
		if ((dialog_class.callbacks != null) && (dialog_class.callbacks['cancel_clicked'] != null))
		{
			dialog_class.callbacks['cancel_clicked'](dialog_class);
		}
		$(dialog_class.getDialogName()).dialog('close');
		dialog_class.unblock();
	},
	
	validate: function(dialog_class)
	{
		$.validity.clear();
		
		var result = true;
		var validation_result;
		
		for (var c = 0; c < dialog_class.fields.length; c++)
		{
			for (var i = 0; i < dialog_class.fields[c].length; i++)
			{
				var field = dialog_class.fields[c][i];
				var field_id = $('#' + dialog_class.getFieldID(field.field_name));
			
				if ((field.required == true) || ((field['type'] != 'checkbox') && (field['type'] != 'text_field') && (field['type'] != 'small_text_field') && (field['type'] != 'text_area') && (field['type'] != 'image') && (field['type'] != 'spacer') && (field['type'] != 'autocomplete')))
				{
					if (field['allow_none'] == null || field['allow_none'] != true || field['type'] != 'select') {
						validation_result = field_id.require();
						if ((validation_result.reduction.length == 0))
						{
							result = false;
							break;
						}
					}
				
					if (field['type'] == 'number')
					{
						validation_result = field_id.match('number', null);
						if (validation_result.reduction.length == 0)
						{
							result = false;
							break;
						}
					}
					else if (field['type'] == 'integer')
					{
						validation_result = field_id.match('integer', null);
						if (validation_result.reduction.length == 0)
						{
							result = false;
							break;
						}
					}
					else if (field['type'] == 'date')
					{
						validation_result = field_id.match('date', null);
						if (validation_result.reduction.length == 0)
						{
							result = false;
							break;
						}
					}
					else if (field['type'] == 'email')
					{
						validation_result = field_id.match('email', null);
						if (validation_result.reduction.length == 0)
						{
							result = false;
							break;
						}
					}
					else if (field['type'] == 'url')
					{
						validation_result = field_id.match('url', null);
						if (validation_result.reduction.length == 0)
						{
							result = false;
							break;
						}
					}
					else if (field['type'] == 'password')
					{
						$(".match_input").equal("Passwords do not match.", null);
					}
				}
			}
		}
		
		return result;
	},
	
	// Insert the data to given the insert path RESTful URL.
	insert: function(dialog_class)
	{
		var file_only = dialog_class.dialog_header.file_only;
		
		if ((dialog_class.dialog_header.insert_path) || (file_only == true)) {
			if (dialog_class.validate(dialog_class) == true)
			{
				
				$(dialog_class.getDialogName()).dialog('close');
				
				var params = {};
				
				if (file_only) {
					// Now upload any images to the record after successful
					// insert of the record.
					for (var c = 0; c < dialog_class.fields.length; c++)
					{
						for (i = 0; i < dialog_class.fields[c].length; i++)
						{
							params = {};
							field = dialog_class.fields[c][i];
							if (field['type'] == 'image')
							{
								var update_url = field['update_path'];

								var element_id = dialog_class.getFieldID(field.field_name);
								field_id = $('#' + element_id);
								if (field_id.val().length > 0)
								{
									var key = dialog_class.dialog_header['key']
									
									var hidden_key = '';
									if (dialog_class.dialog_header['hidden_key'] != null) {
										hidden_key = dialog_class.dialog_header['hidden_key'];
									}
								
									dialog_class.showBlock();
									$.ajaxFileUpload (
											{
											url:update_url, 
											secureuri:false,
											fileElementId : element_id,
											params: [key, hidden_key],
											dataType: 'json',
											success: function (data, status)
											{
												if (field.image_updated != null) {
													field.image_updated(data);
												}

												if (file_only == true) {

													if ((dialog_class.callbacks != null) && (dialog_class.callbacks['ok_clicked'] != null))
													{
														dialog_class.callbacks['ok_clicked'](dialog_class, data, status);
													}
												}
												dialog_class.unblock();
											},
											error: function (data_result, status, e)
											{
												dialog_class.unblock();

												if (file_only == true) {
													$(dialog_class.getDialogName()).dialog('close');

													if ((dialog_class.callbacks != null) && (dialog_class.callbacks['ok_clicked'] != null))
													{
														dialog_class.callbacks['ok_clicked'](dialog_class, data_result, status);
													}
												}
											}

										}
									);
								}
							}
						}
					}
				}
				
				// Get the parameters for the next call.
				for (var c = 0; c < dialog_class.fields.length; c++)
				{
					for (var i = 0; i < dialog_class.fields[c].length; i++)
					{
						var field = dialog_class.fields[c][i];
						if (field['type'] != 'spacer' && field['type'] != 'image') {
							var field_id = $('#' + dialog_class.getFieldID(field.field_name));

							if (field['type'] != 'checkbox') {
								params[field.field_name] = field_id.val();
							}
							else {
								var checked = field_id.attr('checked');
								params[field.field_name] = checked;
							}
						}
					}
				}
				
				if (dialog_class.dialog_header.insert_path && !dialog_class.no_post) {
					var final_url = dialog_class.dialog_header['insert_path'] + '/';
					if (dialog_class.dialog_header['key'] != null) {
						final_url += dialog_class.dialog_header['key'];
					}
					
					var hidden_key = '';
					if (dialog_class.dialog_header['hidden_key'] != null) {
						hidden_key = dialog_class.dialog_header['hidden_key'];
						params['hidden_key'] = hidden_key;
					}
					
					dialog_class.showBlock();
					var bodyContent = $.ajax({
						url: final_url,
						global: false,
						type: "POST",
						data: (params),
						dataType: "json",
						success: function(msg) {
							if (msg.status == 'OK')
							{
								if (!file_only) {
									// Now upload any images to the record after successful
									// insert of the record.
									for (var c = 0; c < dialog_class.fields.length; c++)
									{
										for (i = 0; i < dialog_class.fields[c].length; i++)
										{
											params = {};
											field = dialog_class.fields[c][i];
											if (field['type'] == 'image')
											{
												var update_url = field['update_path'];

												var element_id = dialog_class.getFieldID(field.field_name);
												field_id = $('#' + element_id);
												if (field_id.val().length > 0)
												{
													var key = ''
													if (msg.key != null) {
														key = msg.key;
													}
													else {
														key = dialog_class.dialog_header['key'];
													}
													
													var hidden_key = '';
													if (dialog_class.dialog_header['hidden_key'] != null) {
														hidden_key = dialog_class.dialog_header['hidden_key'];
													}
												
													file_only = true;

													dialog_class.showBlock();
													$.ajaxFileUpload (
															{
															url:update_url, 
															secureuri:false,
															fileElementId : element_id,
															params: [key, hidden_key],
															dataType: 'json',
															success: function (data, status)
															{
																if (field.image_updated != null) {
																	field.image_updated(data);
																}

																if (file_only == true) {

																	if ((dialog_class.callbacks != null) && (dialog_class.callbacks['ok_clicked'] != null))
																	{
																		dialog_class.callbacks['ok_clicked'](dialog_class, data, status);
																	}
																}
																dialog_class.unblock();
															},
															error: function (data_result, status, e)
															{
																dialog_class.unblock();

																if (file_only == true) {
																	$(dialog_class.getDialogName()).dialog('close');

																	if ((dialog_class.callbacks != null) && (dialog_class.callbacks['ok_clicked'] != null))
																	{
																		dialog_class.callbacks['ok_clicked'](dialog_class, data_result, status);
																	}
																}
															}

														}
													);
												}
											}
										}
									}
								}
								
								if (!file_only) {
									if ((dialog_class.callbacks != null) && (dialog_class.callbacks['ok_clicked'] != null))
									{
										dialog_class.callbacks['ok_clicked'](dialog_class, msg);
									}
								}
							}
							else
							{
								if ((dialog_class.callbacks != null) && (dialog_class.callbacks['error_insert'] != null))
								{
									dialog_class.callbacks['error_insert'](msg);
								}
							}
							dialog_class.unblock();
						},
						error: function(XMLHttpRequest, textStatus, errorThrown) {
							if ((dialog_class.callbacks != null) && (dialog_class.callbacks['error_insert'] != null))
							{
								dialog_class.callbacks['error_insert'](textStatus, errorThrown, dialog_class);
							}
							dialog_class.unblock();
						}
					});
				}
				else {
					if ((dialog_class.callbacks != null) && (dialog_class.callbacks['ok_clicked'] != null))
					{
						dialog_class.callbacks['ok_clicked'](dialog_class);
					}
				}
			}
		}
	},
	
	update: function(dialog_class)
	{
		var file_only = dialog_class.dialog_header.file_only;
		
		if (dialog_class.dialog_header.update_path) {
			if (dialog_class.validate(dialog_class) == true)
			{
				$(dialog_class.getDialogName()).dialog('close');
				
				var i = 0;
				var field_id;
				var field;
				var params = {};
				// Submit images first.
				
				if (file_only) {
					for (var c = 0; c < dialog_class.fields.length; c++)
					{
						for (i = 0; i < dialog_class.fields[c].length; i++)
						{
							params = {};
							field = dialog_class.fields[c][i];
							if (field['type'] == 'image')
							{
								var update_url = field['update_path'];

								var element_id = dialog_class.getFieldID(field.field_name);
								field_id = $('#' + element_id);
								if (field_id.val().length > 0)
								{
									var key = ''
									if (this.current_key != null) {
										key = this.current_key;
									}
									else {
										key = dialog_class.dialog_header['key']
									}
									dialog_class.showBlock();
									$.ajaxFileUpload (
											{
											url:update_url, 
											secureuri:false,
											fileElementId : element_id,
											params: [key],
											dataType: 'json',
											success: function (data, status)
											{
												if (field.image_updated != null) {
													field.image_updated(data);
												}

												dialog_class.unblock();
											},
											error: function (data, status)
											{
												if (data.responseText == 'OK') {
													if (field.image_updated != null) {
														field.image_updated(data);
													}
												}
												dialog_class.unblock();
											}

										}
									);
								}
							}
						}
					}
				}
				
				// Deal with normal fields now.
				params = {};
				for (var c = 0; c < dialog_class.fields.length; c++)
				{
					for (i = 0; i < dialog_class.fields[c].length; i++)
					{
						field = dialog_class.fields[c][i];
						if ((field['type'] != 'image') && (field['type'] != 'spacer'))
						{
							field_id = $('#' + dialog_class.getFieldID(field.field_name));
							
							if (field['type'] != 'checkbox') {
								params[field.field_name] = field_id.val();
							}
							else {
								var checked = field_id.attr('checked');
								params[field.field_name] = checked;
							}
						}
					}
				}
				
				var key = ''
				if (this.current_key != null) {
					key = this.current_key;
				}
				else {
					key = dialog_class.dialog_header['key']
				}
				 
				dialog_class.showBlock();
				// Submit text fields next.
				var bodyContent = $.ajax({
					url: dialog_class.dialog_header['update_path'] + '/' + this.current_key,
					global: false,
					type: "POST",
					data: (params),
					dataType: "json",
					success: function(msg) {
						if (msg.status == 'OK')
						{
							if (!file_only) {
								for (var c = 0; c < dialog_class.fields.length; c++)
								{
									for (i = 0; i < dialog_class.fields[c].length; i++)
									{
										params = {};
										field = dialog_class.fields[c][i];
										if (field['type'] == 'image')
										{
											var update_url = field['update_path'];

											var element_id = dialog_class.getFieldID(field.field_name);
											field_id = $('#' + element_id);
											if (field_id.val().length > 0)
											{
												
												dialog_class.showBlock();
												$.ajaxFileUpload (
														{
														url:update_url, 
														secureuri:false,
														fileElementId : element_id,
														params: [key],
														dataType: 'json',
														success: function (data, status)
														{
															if (field.image_updated != null) {
																field.image_updated(data);
															}
															
															dialog_class.unblock();
														},
														error: function (data, status)
														{
															if (data.responseText == 'OK') {
																if (field.image_updated != null) {
																	field.image_updated(data);
																}
															}
															dialog_class.unblock();
														}

													}
												);
											}
										}
									}
								}
							}
							
							if ((dialog_class.callbacks != null) && (dialog_class.callbacks['ok_clicked'] != null))
							{
								dialog_class.callbacks['ok_clicked'](dialog_class, msg);
							}
						}
						else
						{
							if ((dialog_class.callbacks != null) && (dialog_class.callbacks['error_insert'] != null))
							{
								dialog_class.callbacks['error_insert'](msg);
							}
						}
						dialog_class.unblock();
						
					},
					error: function(XMLHttpRequest, textStatus, errorThrown) {
						if ((dialog_class.callbacks != null) && (dialog_class.callbacks['error_insert'] != null))
						{
							dialog_class.callbacks['error_insert'](textStatus, errorThrown, dialog_class);
						}
						dialog_class.unblock();
					}
				});
				
			}
		}
	},
	
	title: function(new_title)
	{
		var name = this.dialog_header['name'];
		$('#ui-dialog-title-dialog_' + name).html(new_title);
	},
	
	// Puts the dialog in Add mode and shows it.
	add: function(key, no_post, hidden_key, title)
	{
		this.mode = 'add';
		this.is_dirty = false;
		this.initialize = true;
		var name = this.dialog_header['name'];
		
		var onFocusedCallback = this.onFocused;
		var onChangedCallback = this.onChanged;
		
		if (key != null)
		{
			this.dialog_header['key'] = key;
		}
		
		if (hidden_key != null)
		{
			this.dialog_header['hidden_key'] = hidden_key;
		}
		else
		{
			this.dialog_header['hidden_key'] = null;
		}
		
		this.no_post = false;
		if (no_post != null) {
			this.no_post = no_post;
		}
		
		$.validity.clear();
		this.clearFields();
		$(this.getDialogName()).data('title.dialog', 'New ' + this.dialog_header['title'] );
		$('#ui-dialog-title-dialog_' + name).html('New ' + this.dialog_header['title']);
		
		if (title != null) {
			this.title(title);
		}
		
		$(this.getDialogName()).dialog('open');
		
		if (true) {
			
			$('.wysiwyg').remove();
			
			for (var c = 0; c < this.fields.length; c++)
			{
				for (i = 0; i < this.fields[c].length; i++)
				{
					var field = this.fields[c][i];
					var field_id = $('#' + name + '_' + field.field_name);
					
					if (field.select == true) {
						field_id.focus().select();
					}
					
					if (field['type'] == 'rich_text_area')
					{
						var rows = '';
						var cols = '';
						if (field['rows'] != null) {
							rows = field['rows'];
						}
						if (field['cols'] != null) {
							cols = field['cols'];
						}
					
						field_id.wysiwyg(
							{
								controls : {
									separator01 : { visible : true },
									separator03 : { visible : true },
									separator04 : { visible : true },
									separator00 : { visible : true },
									insertOrderedList : { visible : true },
									insertUnorderedList : { visible : true },
									undo: { visible : true },
									redo: { visible : true },
									justifyLeft: { visible : true },
									justifyCenter: { visible : true },
									justifyRight: { visible : true },
									justifyFull: { visible : true },
									subscript: { visible : true },
									superscript: { visible : true },
									underline: { visible : true },
									html:{visible : true}
								},
								callbacks : {
									changed : onChangedCallback
								}
							} );
					}
				}
			}
		}
		this.initialize = false;
	},
	
	// Puts the dialog in edit mode and shows it.
	edit: function(record_key)
	{
		this.mode = 'edit';
		this.is_dirty = false;
		this.initialize = true;
		
		$.validity.clear();
		this.current_key = record_key;
		
		this.clearFields();
		$(this.getDialogName()).data('title.dialog', 'Edit ' + this.dialog_header['title'] );
		
		//"ui-dialog-title-dialog_action"
		
		var dialog_control = $(this.getDialogName());
		var name = this.dialog_header['name'];
		var fields = this.fields;
		var first_open = this.first_open;
		var dialog = this
		
		$('#ui-dialog-title-dialog_' + name).html('Edit ' + this.dialog_header['title']);
		
		var onFocusedCallback = this.onFocused;
		var onChangedCallback = this.onChanged;
		
		block();
		
		if (this.dialog_header['get_path'] != null)
		{
			var bodyContent = $.ajax({
				url: this.dialog_header['get_path'] + '/' + record_key,
				global: false,
				type: "GET",
				dataType: "json",
				success: function(msg) {
					dialog_control.dialog('open');
					
					for (var c = 0; c < fields.length; c++)
					{
						for (var i = 0; i < fields[c].length; i++)
						{
							var field = fields[c][i];
							var field_id = $('#' + name + '_' + field.field_name);
							
							if ((field['type'] != 'spacer') && (field['type'] != 'checkbox')){
								
								field_id.val(msg.values[field.field_name]);
								
								if (field['type'] == 'color') {
									var field_color_id = $('#color_' + name + '_' + field.field_name);
									field_color_id.css("background-color", '#' + msg.values[field.field_name]);
								}
								
								if (field.select == true) {
									field_id.focus().select();
								}
							}
							else {
								if (field['type'] == 'checkbox') {
									if(msg.values[field.field_name] == true) {
										field_id.attr('checked', true);
									}
									else {
										field_id.attr('checked', false);
									}
								}
							}
						}
					}
				
					dialog.initialize = false;
					
					$('.wysiwyg').remove();
					
					if (true) {
						for (var c = 0; c < fields.length; c++)
						{
							for (i = 0; i < fields[c].length; i++)
							{
								field = fields[c][i];
								if (field['type'] == 'rich_text_area')
								{
									var field_id = $('#' + name + '_' + field.field_name);
									
									field_id.wysiwyg(
										{
											controls : {
												separator01 : { visible : true },
												separator03 : { visible : true },
												separator04 : { visible : true },
												separator00 : { visible : true },
												insertOrderedList : { visible : true },
												insertUnorderedList : { visible : true },
												undo: { visible : true },
												redo: { visible : true },
												justifyLeft: { visible : true },
												justifyCenter: { visible : true },
												justifyRight: { visible : true },
												justifyFull: { visible : true },
												subscript: { visible : true },
												superscript: { visible : true },
												underline: { visible : true },
												html:{visible : true}
											},
											callbacks : {
												changed : onChangedCallback
											}
										} );
										
								}
							}
						}
					}
					dialog.unblock();
					
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					dialog.initialize = false;
					dialog.unblock();
				}
			});
		}
		else
		{
			dialog_control.dialog('open');
			dialog.initialize = false;
			dialog.unblock();
		}
		this.first_open = false;
		
	}
});

