g_stbCurrentCellSource = [];
(function ($, app) {
	$(document).ready(function () {
		var editor = app.Editor.Hot,
			toolbar = app.Editor.Tb,
            sort_items = [
                {
                    key: 0,
                    name: '---------'
                },
                {
                    key: 'sortingAsc',
                    name: function() {
                        return 'Sort A -> Z';
                    },
                    callback: function(name, selection, e) {
                        return app.Models.Tables.sortingTable(editor, selection, 'asc');
                    },
                    disabled: function() {
                        return false;
                    }
                },
                {
                    key: 'sortingDesc',
                    name: function() {
                        return 'Sort Z -> A';
                    },
                    callback: function(name, selection, e) {
                        return app.Models.Tables.sortingTable(editor, selection, 'desc');
                    },
                    disabled: function() {
                        return false;
                    }
                },
                {
                    key: 'sortingRand',
                    name: function() {
                        return 'Randomize Range';
                    },
                    callback: function(name, selection, e) {
                        return app.Models.Tables.sortingTable(editor, selection, '');
                    },
                    disabled: function() {
                        return false;
                    }
                },
                {
                    key: 'sortingClear',
                    name: function() {
                        return 'Clear all sorting';
                    },
                    callback: function(name, selection, e) {
                        return app.Models.Tables.clearSortingTable(editor);
                    },
                    disabled: function() {
                        return false;
                    }
                },
            ];

        // Editor Hooks
        editor.addHook('afterLoadData', function () {
            var settingsColHeaders = $('#settingsColHeaders').val().length ? JSON.parse($('#settingsColHeaders').val()) : false;
            var colHeaders = settingsColHeaders || true;
            editor.updateSettings({
                columnSorting: false,
                multiColumnSorting: true,
                colHeaders: colHeaders
            });
        });
        editor.addHook('afterContextMenuDefaultOptions', function(predefinedItems) {
            sort_items.forEach(function(item){
                predefinedItems.items.push(
                    item
                );
            });
        });
        editor.addHook('afterDropdownMenuDefaultOptions', function(predefinedItems) {
            sort_items.forEach(function(item){
                predefinedItems.items.push(
                    item
                );
            });
        });

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

				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;
		});

        // Edit Columns Header Dialog
        g_stbSetEditColumnsHeaderDataDialog = $('#setEditColumnsHeaderDataDialog').dialog({
            autoOpen: false,
            width:    600,
            height:   'auto',
            modal:    true,
            open: function() {
                var colHeaders = editor.getColHeader();
                for(var i = 0, n = colHeaders.length; i < n; i++) {
                    toolbar._addEditColumnsHeaderList(colHeaders[i]);
                }
            },
            close: function() {
                toolbar._clearEditColumnsHeaderList();
            },
            buttons:  {
                Apply: function (event) {
                    toolbar.call('applyEditColumnsHeader');
                    $(this).dialog('close');
                },
                'Clear Columns Headers': function (event) {
                    toolbar.call('removeEditColumnsHeader');
                    $(this).dialog('close');
                },
                Cancel: function () {
                    $(this).dialog('close');
                }
            }
        });

		// 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 : '',
					dbExternalHost: isSpecialValue ? $('#source-db-external-host').val() : '',
					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,
					dbExternalHost: $('#source-db-external-host').val(),
					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));
