var g_stbSetSelectableFieldDataDialog;
(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('');
		}
	};

	// 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']);
				toolbar.call('removeSelectableField');
				this.getEditor().render();
			},
			removeEditableField: function() {
				this.removeClass('editable');
				this.getEditor().render();
			},
			addSelectableField: function() {
				var editor = this.getEditor();
				if(editor.getSelectedRange()) {
					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.getSelectedRange());

				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'], 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.getSelectedRange());

				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();
			},
			addDateField: function() {
				this.replaceClass('datefield', ['editable', 'selectable', 'datefield']);
				//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.getSelectedRange()) {
					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));