var g_stbSetSelectableFieldDataDialog,
    g_stbSetEditColumnsHeaderDataDialog;
(function ($, app) {
	var Toolbar = app.Editor.Toolbar;

	// Add PRO version of subscribe method
	Toolbar.prototype.subscribePro = function () {
		var self = this;

		// Apply subscribe method from free version
		self.subscribe();

		// Change cells PRO params via its classes
		self.getEditor().addHook('afterSelection', function (startRow, startCol, endRow, endCol) {
			var cell = self.getEditor().getCell(startRow, startCol);

			if (!cell) {
				return;
			}
			var cellMeta = self.getEditor().getCellMeta(startRow, startCol),
				classes = app.getClassesRegexp(),
				familyData = classes.fontFamily.exec(cell.className),
				family = familyData ? familyData[1].replace(/_/g, ' ') : null;

			// Cell style params
			if (null !== family && g_stbAllFontsList && toeInArray(family, g_stbAllFontsList) != -1) {
				$('#fontFamily').val(family);
			} else {
				$('#fontFamily').val('default');
			}
		});
	};

	Toolbar.prototype._addSelectableListOpt = function(value) {
		value = value || '';

		var $optExample = $('#listOptExample');

		if($optExample.length) {
			var $newOpt = ($optExample).clone().removeAttr('id');

			$newOpt.appendTo($('#listOptsShell'));
			$newOpt.find('[name="source[]"]').val( value);
			$newOpt.find('input').removeAttr('disabled');
			$newOpt.find('.listOptRemoveBtn').click(function(){
				$(this).parents('.listOpt:first').fadeOut(300, function(){
					$(this).remove();
				});
				return false;
			});
			$newOpt.show();
		}
	};

	Toolbar.prototype._clearSelectableListOpt = function() {
		var $optShell = $('#listOptsShell');

		if($optShell.length) {
			$optShell.html('');
		}
	};

    Toolbar.prototype._clearEditColumnsHeaderList = function() {
        var $headColsShell = $('#listHeadColsShell');

        if($headColsShell.length) {
            $headColsShell.html('');
        }
    };

    Toolbar.prototype._addEditColumnsHeaderList = function(value) {
        value = value || '';

        var $optExample = $('#listHeadColsExample');

        if($optExample.length) {
            var $newOpt = ($optExample).clone().removeAttr('id');

            $newOpt.appendTo($('#listHeadColsShell'));
            $newOpt.find('[name="head_cols[]"]').val( value);
            $newOpt.find('input').removeAttr('disabled');
            $newOpt.show();
        }
    };

	// Add PRO methods
	$(document).ready(function () {
		// @see data-tables-generator-by-supsystic/src/SupsysticTables/Tables/assets/js/editor/tables.editor.toolbar.js
		var toolbar = app.Editor.Tb;

		var proMethods = {
			family: function(e) {
				var classes = app.getClassesRegexp(),
					family = $.trim($(e.target).val());

				if (!family || family == 'default') {
					this.removeClass(classes.fontFamily);
				} else {
					var $style = app.getAdminCellStylesElem(),
						familyClass = family.replace(/\s+/g, '_'),
						familyName = family.replace(/\s+/g, '+'),
						url = '';

					if($style.html().indexOf('.ffamily-'+familyClass) == -1) {
						if(g_stbStandartFontsList
							&& toeInArray(family, g_stbStandartFontsList) == -1
							&& g_stbAllFontsList
							&& toeInArray(family, g_stbAllFontsList) != -1
						) {
							url = '@import url("//fonts.googleapis.com/css?family=' + familyName + '"); ';
						}
						$style.html(url + $style.html() + ' .ffamily-'+familyClass+' {font-family:"'+family+'" !important;}');
					}
					this.replaceClass('ffamily-' + familyClass, classes.fontFamily);
				}
				this.getEditor().render();
			},
			addEditableField: function() {
				this.replaceClass('editable', ['editable', 'datefield', 'editfile']);
				toolbar.call('removeSelectableField');
				this.getEditor().render();
			},
            addEditableFileField: function() {
                this.replaceClass('editfile', ['editable', 'datefield', 'editfile']);
                toolbar.call('removeSelectableField');
                this.getEditor().render();
            },
			removeEditableField: function() {
				this.removeClass('editable');
				this.removeClass('editfile');
				this.getEditor().render();
			},
			addSelectableField: function() {
				var editor = this.getEditor();
				if(editor.getSelectedRangeLast()) {
					g_stbSetSelectableFieldDataDialog.dialog('open');
				} else {
					alert('You must select at least one cell in column.');
				}
			},
			applySelectableField: function() {
				var editor = this.getEditor(),
					range = toolbar.getValidRange(editor.getSelectedRangeLast());

				if (range === undefined) {
					return;
				}
				var row = range.highlight.row,
					col = range.highlight.col,
					cell = editor.getCellMeta(row, col),
					sourceInputs = $('#listOptsShell .listOpt input[name="source[]"]'),
					source = [],
					value = editor.getDataAtCell(row, col);

				for(var i = 0; i < sourceInputs.length; i++) {
					var val = $(sourceInputs[i]).val();

					if(!i) {
						value = val;
					}
					source.push(val);
				}
				// editor and validator will be set automatically after cell type change
				delete cell.editor;
				delete cell.validator;

				cell.baseType = cell.type;
				cell.type = 'dropdown';
				cell.source = source;
				toolbar.replaceClass('selectable', ['editable', 'selectable', 'datefield', 'editfile'], true);
				editor.setDataAtCell(row, col, value);
				editor.setCellMetaObject(row, col, cell);
				editor.validateCell(value, cell, function() {}, 'validateCells');
				editor.render();
			},
			removeSelectableField: function () {
				var editor = this.getEditor(),
					range = this.getValidRange(editor.getSelectedRangeLast());

				if (range === undefined) {
					return;
				}
				var row = range.highlight.row,
					col = range.highlight.col,
					cell = editor.getCellMeta(row, col);

				// editor and validator will be set automatically after cell type change
				delete cell.editor;
				delete cell.validator;
				delete cell.source;

				cell.type = cell.baseType || 'text';
				this.removeClass('selectable', true);
				editor.setCellMetaObject(row, col, cell);
				editor.validateCell(editor.getDataAtCell(), cell, function() {}, 'validateCells');

				editor.render();
			},
            editColumnsHeader: function() {
                g_stbSetEditColumnsHeaderDataDialog.dialog('open');
			},
            applyEditColumnsHeader: function() {
                var editor = this.getEditor(),
                    settingsColHeaders = $('#settingsColHeaders'),
                    headColInputs = $('#listHeadColsShell .listOpt input[name="head_cols[]"]'),
					headCols = [];

                headColInputs.each(function(){
                    headCols.push($(this).val());
				});

                editor.updateSettings({
                    colHeaders: headCols
                });

                settingsColHeaders.val(JSON.stringify(headCols));
                g_stbIsDataEdited['settings'] = true;
                editor.render();
			},
            removeEditColumnsHeader: function() {
                var editor = this.getEditor(),
                    settingsColHeaders = $('#settingsColHeaders');

                editor.updateSettings({
                    colHeaders: true
                });

                settingsColHeaders.val('');
                g_stbIsDataEdited['settings'] = true;
                editor.render();
            },
			addDateField: function() {
				this.replaceClass('datefield', ['editable', 'selectable', 'datefield', 'editfile']);
				//this.setFormat('date', $('input[name="dateFormat"]').val());
				this.getEditor().render();
			},
			removeDateField: function() {
				this.removeClass('datefield');
				this.getEditor().render();
			},
			addCollapsibleCell: function() {
				this.replaceClass('collapsibleCell', ['collapsibleCell']);
				this.getEditor().render();
			},
			removeCollapsibleCell: function() {
				this.removeClass('collapsibleCell');
				this.getEditor().render();
			},
			addTooltipCell: function() {
				this.replaceClass('tooltipCell', ['tooltipCell']);
				this.getEditor().render();
			},
			removeTooltipCell: function() {
				this.removeClass('tooltipCell');
				this.getEditor().render();
			},
			сonditionalFormatting: function() {
				if(app.Editor.Hot.getSelectedRangeLast()) {
					g_stbConditionsDialog.dialog('open');
				} else {
					alert('You must select at least one cell in table.');
				}
			}
		};
		$.each(proMethods, function(method, fn) {
			toolbar.addMethod(method, fn);
		});
		toolbar.subscribePro();
	});

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