g_stbCurrentCellSource = [];
(function ($, app) {
	$(document).ready(function () {
		var editor = app.Editor.Hot,
			toolbar = app.Editor.Tb;

		// Selectable Fields Dialog
		g_stbSetSelectableFieldDataDialog = $('#setSelectableFieldDataDialog').dialog({
			autoOpen: false,
			width:    600,
			height:   'auto',
			modal:    true,
			open: function() {
				var range = toolbar.getValidRange(editor.getSelectedRange());

				if (range === undefined) {
					return;
				}
				var row = range.highlight.row,
					col = range.highlight.col,
					cellMeta = editor.getCellMeta(row, col),
					source = cellMeta.source || [];

				g_stbCurrentCellSource = source.length ? source : [ editor.getDataAtCell(row, col) ];

				for(var i = 0; i < g_stbCurrentCellSource.length; i++) {
					toolbar._addSelectableListOpt(g_stbCurrentCellSource[i]);
				}
			},
			close: function() {
				toolbar._clearSelectableListOpt();
			},
			buttons:  {
				Apply: function (event) {
					toolbar.call('applySelectableField');
					$(this).dialog('close');
				},
				Remove: function () {
					toolbar.call('removeSelectableField');
					$(this).dialog('close');
				},
				Cancel: function () {
					$(this).dialog('close');
				}
			}
		});

		// Selectable Fields Options
		$('#listOptsShell').sortable({
			items: '.listOpt',
			axis: 'y'
		});
		$('.listOptAddBtn').on('click', function(e) {
			toolbar._addSelectableListOpt();
			return false;
		});
		$('.listOptClearBtn').on('click', function(e) {
			toolbar._clearSelectableListOpt();
			return false;
		});

		// Table History Options
		$('select[name="history[user]"]').on('change ifChanged', function() {
			var select = $(this),
				option = select.find('option:selected'),
				userId = parseInt(select.val()),
				period = option.data('created'),
				index = option.data('index');

			if(userId) {
				var updatedShell = $('.table-history-updated');
				updatedShell.hide();
				updatedShell.filter('[data-index="' + index + '"]').show();
				app.Models.Tables.getPreviewHistoryTable(userId, $('#table-history-preview'), period);
			}
		});

		$('form#history-settings').find('input, select, textarea').on('change ifChanged', function(e) {
			g_stbIsDataEdited['history'] = true;
		});

		function divSettingsShow(className, isShow) {
			if(isShow) {
				$(className).fadeIn();
			} else {
				$(className).fadeOut();
			}
		}

		// Table Source Options
		function divEditableShow(isShow) {
			divSettingsShow('.source-database-editable', isShow);
			divSettingsShow('.source-database-editloggedin', isShow && $('#source-db-editloggedin').is(':checked'));
		}

		$('#table-source-database').on('change ifChanged', function() {
			var isChecked = $(this).is(':checked');
			divSettingsShow('.setting-source-database', isChecked);
			if(isChecked) {
				var db = $('#source-db-name'),
					table = $('#source-db-table'),
					isSpecialTable = table.val() == table.data('special-table-val');

				divSettingsShow('.setting-source-database-external', db.val() == db.data('special-db-val'));
				divSettingsShow('.setting-source-database-sql', isSpecialTable);
				divSettingsShow('.setting-source-database-fields,.source-database-allow-edit', !isSpecialTable);
				divEditableShow(!isSpecialTable && $('#source-db-editable').is(':checked'));
			} else {
				divSettingsShow('.setting-source-database-external,.setting-source-database-sql,.setting-source-database-fields,.source-database-allow-edit,.source-database-editable,.source-database-editloggedin', false);
			}
		});
		$('#source-db-editable').on('change ifChanged', function() {
			var table = $('#source-db-table');
			divEditableShow($(this).is(':checked') && table.val() != table.data('special-table-val') && $('#table-source-database').is(':checked'));
		}).trigger('change');

		$('#source-database-connect').on('click', function() {
			$('#source-db-name').trigger('change');
			return false;
		});

		// Load database tables
		$('#source-db-name').on('change ifChanged', function() {
			var dbTables = $('#source-db-table'),
				dbFields = $('#source-db-fields'),
				dbEditFields = $('#source-db-editfields'),
				selectedValue = $(this).val(),
				isSpecialValue = selectedValue == $(this).data('special-db-val'),
				buttonIcon = $('#source-database-connect').find('.fa');
			
			divSettingsShow('.setting-source-database-external', isSpecialValue);

			dbTables.empty();
			dbTables.append('<option class="specialOption" value="' + dbTables.data('special-table-val') + '">' + dbTables.data('special-table') + '</option>');
			dbTables.trigger('chosen:updated');
			dbTables.trigger('change');

			if(isSpecialValue) {
				var dbExternal = $('#source-db-external').val();
				if(dbExternal == '') {
					buttonIcon.attr('class', 'fa fa-exclamation-circle');
					return;
				}
			}
			buttonIcon.attr('class', 'fa fa-spinner fa-spin');

			app.request({
				module: 'tables',
				action: 'getDBTables'}, {
					dbName: selectedValue,
					dbExternal: isSpecialValue ? dbExternal : '',
					dbLogin: isSpecialValue ? $('#source-db-login').val() : '',
					dbPassword: isSpecialValue ? $('#source-db-password').val() : ''					
			}).done(function(data) {
				if (data.success) {
					buttonIcon.attr('class', 'fa fa-check');
					var tables = data.tables;
					for(var i = 0; i < tables.length; i++) {
						dbTables.append('<option value="' + tables[i] + '">' + tables[i] + '</option>');
					}
					dbTables.trigger('chosen:updated');
				}
			}).fail(function (error) {
				buttonIcon.attr('class', 'fa fa-exclamation-circle');
                alert('Error: ' + error);
            });
		});

		// Load fields for database table
		$('#source-db-table').on('change ifChanged', function() {
			var dbFields = $('#source-db-fields'),
				dbEditFields = $('#source-db-editfields'),
				editable = $('#source-db-editable'),
				selectedValue = $(this).val(),
				isSpecialValue = selectedValue == $(this).data('special-table-val');

			dbFields.empty();
			dbEditFields.empty();
			dbFields.trigger('chosen:updated');
			dbEditFields.trigger('chosen:updated');

			divSettingsShow('.setting-source-database-sql', isSpecialValue);
			divSettingsShow('.setting-source-database-fields,.source-database-allow-edit', !isSpecialValue);
			divEditableShow(!isSpecialValue && $('#source-db-editable').is(':checked'));

			if(isSpecialValue) return;

			var buttonIcon = $('#source-database-connect').find('.fa');
			buttonIcon.attr('class', 'fa fa-spinner fa-spin');
			
			app.request({
				module: 'tables',
				action: 'getDBTableFields'}, {
					dbName: $('#source-db-name').val(),
					dbTable: selectedValue,
					dbExternal: $('#source-db-external').val(),
					dbLogin: $('#source-db-login').val(),
					dbPassword: $('#source-db-password').val()
			}).done(function(data) {
				if (data.success) {
					buttonIcon.attr('class', 'fa fa-check');
					var fields = data.fields;
					for(var i = 0; i < fields.length; i++) {
						dbFields.append('<option value="' + fields[i] + '">' + fields[i] + '</option>');
						dbEditFields.append('<option value="' + fields[i] + '">' + fields[i] + '</option>');
					}
				dbFields.trigger('chosen:updated');
				dbEditFields.trigger('chosen:updated');
				}
			}).fail(function (error) {
				buttonIcon.attr('class', 'fa fa-exclamation-circle');
                alert('Error: ' + error);
            });
		});

		$('form#source-settings').find('input, select, textarea').on('change ifChanged', function(e) {
			g_stbIsDataEdited['source'] = true;
		});

	});
}(window.jQuery, window.supsystic.Tables));