var form = jQuery('#edit_field_form');
var fieldId = jQuery('#field_id');
var sectionEditDiv = jQuery('#section_edit_div');

var fieldNumberSelect = jQuery('#field_number_select');
var defaultValue = jQuery('#default_value');
var fieldTwoCells = jQuery('#field_two_cells');
var fieldTwoCellsRow = jQuery('#field_two_cells_row');
var fieldInlineLayoutRow = jQuery('#field_inline_layout_row');
var fieldInlineLayoutCheckbox = jQuery('#field_inline_layout');
var fieldOnTopRow = jQuery('#field_on_top_row');
var stringFormatLabel = jQuery('#string_format_label');
var stringFormatSelect = jQuery('#field_string_format_select');
var fieldEditDiv = jQuery('#field_edit_div');
var fieldTypeSelect = jQuery('#field_type_select');
var fieldStringFormatSelect = jQuery('#field_string_format_select');
var fieldDescr = jQuery('#field_description');
var fieldValues = jQuery('#field_values, #field_values_group');
var fieldValuesLabel = jQuery('#field_values_label');
var fieldPicklist = jQuery('#field_picklist');
var fieldPicklistBlock = jQuery('#field_picklist_block');
var fieldLabel = jQuery('#field_label');
var fieldRequired = jQuery('#field_required');
var fieldDisabled = jQuery('#field_disabled');
var fieldDisabledRow = jQuery('#disabled_row');
var fieldDynamic = jQuery('#field_dynamic');
var fieldDynamicTd = jQuery('#field_dynamic_td');
var fieldStyle = jQuery('#field_style');
var fieldStyleSelect = jQuery('#field_style_select');
var fieldTitleSize = jQuery('#field_title_size');
var fieldStyle2 = jQuery('#field_style2');
var fieldStyle2Select = jQuery('#field_style2_select');
var fieldFieldSize = jQuery('#field_field_size');
var fieldStyleSelect2 = jQuery('#field_style_select2');
var reloadOnChangeRow = jQuery('#field_dynamic_td');
var requiredRow = jQuery('#required_row');
var editPermsLink = jQuery('#edit_perms_link, #edit_perms_group');
var specialDefaultValueDiv = jQuery('#special_default_value_div');
var bbcodeDefaultValueDiv = jQuery('#bbcode_default_value');
var groupDefaultValueDiv = jQuery('#default_group_div');
var roleDefaultValueDiv = jQuery('#default_role_div');
var spanDateDefault = jQuery('#span_date_default');
var spanDateTimeDefault = jQuery('#span_date_time_default');
var yearsRangeBlock = jQuery('#years_range_block');
var defaultValueLabel = jQuery('#default_value_label');
var spanDefaultValue = jQuery('#span_default_value');
var constraintsBlock = jQuery('#constraints_block');
var fieldSymName = jQuery('#field_sym_name');
var hintRow = jQuery('#description_tr');
var current_field_info = {};
var positionDropdownValues = [];

// These tree bools are used used to decide if we should 'generate' a symbolic name - as we wouldn't want to overwrite a users existing symbolic name
var symbolicNameInitiallyBlank = false;
var hasEditedSymbolicName = false;
var symbolicNameIsEmpty = false;
var lastGeneratedSymbolicName = '';
var formulaOpen = false;
var formulaArea = null;

var symNameSection = null;
var symNameService = null;
require(['jquery', '/intranet/forms/js/symNameService.js'], function ($, symNameServiceProvider){
    symNameService = symNameServiceProvider;
    symNameSection = symNameService.createSection($('.ic_sym_name_section'));
    symNameService.bindSection(symNameSection);
});

function updateFieldOnTopVisibility() {
	if (fieldTwoCells.is(':checked') || fieldTwoCellsRow.css('display') == 'none')
		fieldOnTopRow.hide();
	else
		fieldOnTopRow.show();
}

function setFieldStyle(id, val) {
	jq_$(id).val(val);
}

function onChangeType() {
	var fieldTypeSelected = jQuery('#field_type_select').find('option:selected').val();
	if (fieldTypeSelected <= 0)
		return ;

	current_field_info.type = parseInt(fieldTypeSelected, 10);
	current_field_info.items = fieldValues.val();

	displayField(current_field_info);
}

function displayField(field_info) {
	var type = parseInt(field_info.type, 10);

	var fieldOptions = field_info.items_arr ? field_info.items_arr : {};
	var itemsStr = field_info.items ? field_info.items : "";
	var defaultValue = field_info.default_value ? field_info.default_value : null;

	stringFormatLabel.hide();
	stringFormatSelect.hide();
	fieldValues.hide();
	fieldValuesLabel.hide();
	fieldPicklistBlock.hide();
	editPermsLink.hide();
	specialDefaultValueDiv.hide();
	spanDateDefault.hide();
	spanDateTimeDefault.hide();
	showNoDefaultCheckbox(false);
	yearsRangeBlock.hide();
	spanDefaultValue.empty();
	spanDefaultValue.show();
	defaultValueLabel.show();
	requiredRow.show();
	fieldDisabledRow.show();
	reloadOnChangeRow.show();
	bbcodeDefaultValueDiv.hide();
	groupDefaultValueDiv.hide();
	roleDefaultValueDiv.hide();
	fieldInlineLayoutRow.hide();
	fieldLabel.prop('disabled', false);
	fieldRequired.prop('disabled', false);
	fieldDisabled.prop('disabled', false);
	fieldTwoCellsRow.show();
	fieldDynamic.prop('disabled', false);
	fieldStyle.prop('disabled', false);
	fieldStyleSelect.prop('disabled', false);
	fieldTitleSize.prop('disabled', false);
	fieldStyle2.prop('disabled', false);
	fieldStyle2Select.prop('disabled', false);
	jQuery('#field_field_size_block').show();
	constraintsBlock.show();
	jQuery('#field_style_block').show();
	jQuery('#label_style_block').show();
	jQuery('#label_field_size_block').show();
	hintRow.show();

	switch (type)
	{
		case document.cla_forms.field_types.TYPE_SHORT_STRING:
			stringFormatLabel.show();
			stringFormatSelect.show();
			showDefaultString('form-control input-width-sm float-left', defaultValue); // todo: add class to set field size
			break;
		case document.cla_forms.field_types.TYPE_MEDIUM_STRING:
			stringFormatLabel.show();
			stringFormatSelect.show();
			showDefaultString('form-control input-width-md float-left', defaultValue); // todo: add class to set field size
			break;
		case document.cla_forms.field_types.TYPE_LONG_STRING:
			showDefaultString('form-control input-width-lg float-left', defaultValue); // todo: add class to set field size
			break;
		case document.cla_forms.field_types.TYPE_SHORT_TEXT:
			showDefaultText('form-control', [20, 2], defaultValue, 'short');
			break;
		case document.cla_forms.field_types.TYPE_MEDIUM_TEXT:
			showDefaultText('form-control', [40, 4], defaultValue, 'medium');
			break;
		case document.cla_forms.field_types.TYPE_LONG_TEXT:
			showDefaultText('form-control', [60, 8], defaultValue, 'long');
			break;
		case document.cla_forms.field_types.TYPE_BBCODE_TEXT:
			showBBCodeText(defaultValue);
			break;
		case document.cla_forms.field_types.TYPE_CHECKBOX:
			constraintsBlock.hide();
			jQuery('<input/>', {
				type: 'checkbox',
				name: 'default_value',
				id: 'default_value',
				checked: defaultValue ? true : false,
				value: '1'
			}).appendTo(spanDefaultValue);
			break;
		case document.cla_forms.field_types.TYPE_RADIO:
			fieldValues.show();
			fieldValuesLabel.show();
			fieldValues.val(itemsStr);
			showDefaultRadios(fieldOptions, defaultValue);
			showNoDefaultCheckbox(true, false, field_info.no_default);
			fieldInlineLayoutRow.show();
			fieldInlineLayoutCheckbox.prop('checked', (field_info.inline_layout == 0 ? '' : 'checked'));
			break;
		case document.cla_forms.field_types.TYPE_SELECT:
			fieldValues.show();
			fieldValuesLabel.show();
			fieldValues.val(itemsStr);
			fieldPicklistBlock.show();
			//fieldRequired.prop('disabled', true);
			showNoDefaultCheckbox(true, true, field_info.no_default);
			showDefaultSelects(fieldOptions, defaultValue, false);
			break;
		case document.cla_forms.field_types.TYPE_MULTIPLE_SELECT:
			fieldValues.show();
			fieldValuesLabel.show();
			fieldValues.val(itemsStr);
			fieldPicklistBlock.show();
			showNoDefaultCheckbox(true, false, field_info.no_default);
			showDefaultSelects(fieldOptions, defaultValue, true);
			constraintsBlock.hide();
			break;
		case document.cla_forms.field_types.TYPE_MULTIPLE_CHECKBOXES:
			fieldValues.show();
			fieldValuesLabel.show();
			fieldValues.val(itemsStr);
			showNoDefaultCheckbox(true, false, field_info.no_default);
			showDefaultSelects(fieldOptions, defaultValue, true);
			constraintsBlock.hide();
			fieldInlineLayoutRow.show();
			fieldInlineLayoutCheckbox.prop('checked', (field_info.inline_layout == 0 ? '' : 'checked'));
			break;
		case document.cla_forms.field_types.TYPE_DATE:
			if (!fieldOptions.start_year)
				fieldOptions.start_year = (new Date()).getFullYear() - 20;
			if (!fieldOptions.end_year)
				fieldOptions.end_year = fieldOptions.start_year + 40;
			yearsRangeBlock.show();
			showDefaultDates(fieldOptions, defaultValue);
			jQuery('#start_year').val(fieldOptions.start_year);
			jQuery('#end_year').val(fieldOptions.end_year);
			break;
		case document.cla_forms.field_types.TYPE_LABEL:
			defaultValueLabel.hide();
			requiredRow.hide();
			fieldTwoCellsRow.hide();
			reloadOnChangeRow.hide();
			fieldDisabledRow.hide();
			jQuery('#field_field_size_block').hide();
			constraintsBlock.hide();
			jQuery('#field_style_block').hide();
			break;
		case document.cla_forms.field_types.TYPE_USERLIST:
			if (field_info.id > 0)
				editPermsLink.show();
			fieldValues.val('');
			showNoDefaultCheckbox(true, true, field_info.no_default);
			showDefaultSelects(fieldOptions, defaultValue, false);
			fieldPicklistBlock.show();
			constraintsBlock.hide();
			break;
		case document.cla_forms.field_types.TYPE_MULTIPLE_USERLIST:
			if (field_info.id > 0)
				editPermsLink.show();
			fieldValues.val('');
			showNoDefaultCheckbox(true, false, field_info.no_default);
			showDefaultSelects(fieldOptions, defaultValue, true);
			constraintsBlock.hide();
			fieldPicklistBlock.show();
			break;
		case document.cla_forms.field_types.TYPE_DOCUMENT:
			defaultValueLabel.hide();
			constraintsBlock.hide();
			break;
		case document.cla_forms.field_types.TYPE_HTML:
			constraintsBlock.hide();
			showDefaultHtml(defaultValue);
			break;
		case document.cla_forms.field_types.TYPE_NOTICE:
			constraintsBlock.hide();
			reloadOnChangeRow.hide();
			fieldDisabledRow.hide();
			requiredRow.hide();
			// defaultValueLabel.hide();
			hintRow.hide();
			jQuery('#label_style_block').hide();
			jQuery('#label_field_size_block').hide();
			fieldTwoCellsRow.hide();
			fieldOnTopRow.hide();

			showDefaultHtml(defaultValue);
			break;
		case document.cla_forms.field_types.TYPE_GROUP:
			constraintsBlock.hide();
			fieldDynamic.prop('disabled', true);
			showNoDefaultCheckbox(true, false, field_info.no_default);
			showDefaultGroups(defaultValue);
			break;
		case document.cla_forms.field_types.TYPE_ROLE:
			constraintsBlock.hide();
			fieldDynamic.prop('disabled', true);
			showNoDefaultCheckbox(true, false, field_info.no_default);
			showDefaultRoles(defaultValue);
			break;
		case document.cla_forms.field_types.TYPE_FILE:
		case document.cla_forms.field_types.TYPE_SIGNATURE_PAD:
			defaultValueLabel.hide();
			constraintsBlock.hide();
			reloadOnChangeRow.hide();
			break;
		case document.cla_forms.field_types.TYPE_DATE_PICKER:
			showDefaultDatePicker(defaultValue);
			break;
		case document.cla_forms.field_types.TYPE_DATE_TIME_PICKER:
			showDefaultDateTimePicker(defaultValue);
			break;
		case document.cla_forms.field_types.TYPE_FINANCIAL:
			showDefaultString('form-control', defaultValue);
			break;
		default:
			break;
	}
	return true;
}

// show or hide "no default" option
function showNoDefaultCheckbox(show, is_select, checked)
{
	jQuery('#span_no_default').toggle(show);
	jQuery('#span_no_default_normal').toggle(!is_select);
	jQuery('#span_no_default_select').toggle(is_select);
	jQuery('#no_default').prop('checked', checked);
}

function showDefaultString(css_class, value)
{
    var inputGroup = jQuery('<div />', {
        'class' : 'input-group'}).appendTo(spanDefaultValue)

	var input = jQuery('<input />', {
		'class' : css_class,
		type: 'text',
		name: 'default_value',
		id: 'default_value',
		value: value,
		click: function(){ storeCaret(this); },
		select: function(){ storeCaret(this); },
		keyup: function(){ storeCaret(this); },
		change: function(){ storeCaret(this); }
	}).appendTo(inputGroup);

    var inputAppend =jQuery('<div></div>', {
        'class' : 'input-group-append'
    }).appendTo(inputGroup);
	// expandable option for users needing formulae
	jQuery(	'<a></a>', {
		'class' : 'btn dropdown-toggle btn-outline-secondary input-group-append formula-expand-toggle',
		'rel' : 'tooltip',
        'href': 'javascript:void(0)',
        'data-toggle': 'dropdown',
		'title' : lmsg('helpdesk.edit_form.expand_formula'),
		click: function () { expandForFormula(input); }
	}).html('<span>ƒ</span>').appendTo(inputAppend);

	specialDefaultValueDiv.show();
}

function showDefaultText(css_class, sizes, value, length)
{
	// prevent null being set as text value on text fields
	if (!value) { value = ""; }

	// Long text overlaps the modal so override the columns with a width 100%
	var style = '';
	if (length === 'long')
		style='width:100%';

	jQuery('<textarea />', {
		'class': css_class,
		name: 'default_value',
		id: 'default_value',
		cols: sizes[0],
		rows: sizes[1],
		style: style,
		click: function(){ storeCaret(this); },
		select: function(){ storeCaret(this); },
		keyup: function(){ storeCaret(this); },
		change: function(){ storeCaret(this); }
	}).text(value).appendTo(spanDefaultValue);
	specialDefaultValueDiv.show();
}

function showBBCodeText(value)
{
	spanDefaultValue.hide();
	bbcodeDefaultValueDiv.find('textarea').val(value);
	bbcodeDefaultValueDiv.show();
}

function showDefaultGroups(values)
{
	var group_ids = [];
	if (values !== null)
		group_ids = values.split(',');
	groupDefaultValueDiv.find('option').each(function(){
		var group_id = jQuery(this).val();
		if (jQuery.inArray(group_id, group_ids) >= 0)
			jQuery(this).prop('selected', true);
		else
			jQuery(this).prop('selected', false);
	});
	groupDefaultValueDiv.show();
}

function showDefaultRoles(values)
{
	var role_ids = [];
	if (values !== null)
		role_ids = values.split(',');
	roleDefaultValueDiv.find('option').each(function(){
		var role_id = jQuery(this).val();
		if (jQuery.inArray(role_id, role_ids) >= 0)
			jQuery(this).prop('selected', true);
		else
			jQuery(this).prop('selected', false);
	});
	roleDefaultValueDiv.show();
}

function showDefaultRadios(values, selected) {
	spanDefaultValue.empty();
	jQuery.each(values, function(index, value) {
		spanDefaultValue.append('<div class="form-check form-check-inline"><input class="form-check-input" type="radio" name="default_value" id="default_value' + index + '" value="' + index + '"><label class="form-check-label" for="default_value' + index + '">' + html_entity_encode(value) + '</label></div>');
		if (index == selected)
			jQuery('#default_value'+index).prop('checked', true);
		//jQuery('<br/>').appendTo(spanDefaultValue);
	});
	return true;
}

function showDefaultSelects(allValues, selectedValues, is_multiple) {
	spanDefaultValue.empty();
	var name = 'default_value';
	var multiple = false;
	if (is_multiple) {
		name = name + '[]';
		multiple = true;
	}

	var inputSelect = jQuery('<select/>', {
		name: name,
		id: name,
		class: 'form-control',
		multiple: multiple
	});

	jQuery.each(allValues, function(index, value) {
		var option = createOption(value, index, selectedValues);
		option.appendTo(inputSelect);
	});

	inputSelect.appendTo(spanDefaultValue);

	return true;
}

function showDefaultDates(fieldOptions, selectedDate)
{
	spanDefaultValue.empty();

	var day = jQuery('<select/>', {
		'class': 'form-control',
		name: 'day_select',
		id: 'day_select'
	});

	var option, i;

	if (!selectedDate)
	{
		selectedDate = {
			'day' : 0,
			'month' : 0,
			'year' : 0
		};
	} else
	{
		if (selectedDate.day == parseInt(selectedDate.day, 10))
			selectedDate.day = '' + parseInt(selectedDate.day, 10);
		if (selectedDate.month == parseInt(selectedDate.month, 10))
			selectedDate.month = '' + parseInt(selectedDate.month, 10);
	}

	option = createOption('--', '0', selectedDate.day);
	option.appendTo(day);

	option = createOption('CUR', '{now:day}', selectedDate.day);
	option.appendTo(day);

	for(i =1; i <= 31; i++) {
		option = createOption(String(i), String(i), selectedDate.day);
		option.appendTo(day);
	}

	day.appendTo(spanDefaultValue);

	var month = jQuery('<select/>', {
		'class': 'form-control',
		name: 'month_select',
		id: 'month_select'
	});

	option = createOption('--', '0', selectedDate.month);
	option.appendTo(month);

	option = createOption('CUR', '{now:month}', selectedDate.month);
	option.appendTo(month);

	for(i =1; i <= 12; i++) {
		option = createOption(moment('2009-'+(i > 9 ? i : '0' + i)+'-01').format('MMM'), String(i), selectedDate.month);
		option.appendTo(month);
	}

	month.appendTo(spanDefaultValue);

	var year = jQuery('<select/>', {
		'class': 'form-control',
		name: 'year_select',
		id: 'year_select'
	});

	option = createOption('--', '0', selectedDate.year);
	option.appendTo(year);

	option = createOption('CUR', '{now:year}', selectedDate.year);
	option.appendTo(year);

	var from, to;
	if (fieldOptions && fieldOptions.start_year > 0 && fieldOptions.end_year > 0) {
		from = parseInt(fieldOptions.start_year, 10);
		to = parseInt(fieldOptions.end_year, 10);
	} else {
		from = 2000;
		to = 2020;
	}

	for (i = from; i <= to; i++) {
		option = createOption(String(i), String(i), selectedDate.year);
		option.appendTo(year);
	}

	year.appendTo(spanDefaultValue);
}

function showDefaultHtml(value)
{
	jQuery('<a/>', {
		href: '#',
		name: 'link_html_edit',
		id: 'link_html_edit',
		html: inputHTMLText,
		click: function() {
			window.open('../forms/fck_field.php?field_id=' + jQuery('#field_id').val(),'_blank', 'width=735,height=490,scrollbars=yes,resizable=yes,hotkeys=no,maximize=no,visible=no');
			return false;
		}
	}).appendTo(spanDefaultValue);
	jQuery('<textarea/>', {
		id: 'default_value',
		name: 'default_value',
		html: value //inputHTMLText
	}).appendTo(spanDefaultValue).hide();
}

function showDefaultDatePicker(value)
{
	var re_res;
	jQuery('<label class="date-picker"><input class="date_picker form-control" type="text" value="" name="default_value" id="default_value" autocomplete="off" onchange="jQuery(\'#date_default_now\').prop(\'checked\', 0);" /></label>')
		.appendTo(spanDefaultValue);
	var $el = jQuery('#default_value');
	date_picker_init($el);
	spanDateDefault.show();

	if ((re_res = /(\d{4})(\d{2})(\d{2})/.exec(value)))	{
		date_picker_set_date($el, re_res[1] + '-' + re_res[2] + '-' + re_res[3]);
	} else if (value == '{now}') {
		$el.val(value);
	} else {
		value = '';
	}

	jQuery('#date_default_now').prop('checked', (value === '{now}'));
}

function showDefaultDateTimePicker(value)
{
	var re_res;
	var time = '';
	var now = false;

	if (value === null)
	value = '{now}';

	if (value.length == 8)
	{
		if ((re_res = /(\d{4})(\d{2})(\d{2})/.exec(value)))
			value = moment(re_res[1] + '-' + re_res[2] + '-' + re_res[3]); // ISO format
	} else if (value == '{now}')
	{
		now = true;
		time = '';
	} else if (value == 0)
	{
		value = '';
	} else
	{
		if ((re_res = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/.exec(value)))
		{
			value = moment(re_res[1] + '-' + re_res[2] + '-' + re_res[3]);  // ISO format
			time = re_res[4] + ":" +  re_res[5];
		}
	}
	jQuery('<label class="date-picker mr-1"><input class="date_picker form-control" type="text" value="" name="default_value" id="default_value" autocomplete="off" onchange="jQuery(\'#date_default_now\').prop(\'checked\', 0);" /></label>')
		.appendTo(spanDefaultValue);
	var $el = jQuery('#default_value');
	date_picker_init($el);
	if (typeof value == 'object')
		date_picker_set_date($el, value);
	else
		$el.val(value);

	jQuery('<input type="text" class="cla_time_picker form-control" name="default_time_value" id="default_time_value" autocomplete="off">')
		.appendTo(spanDefaultValue).val(time);
	jQuery('#default_time_value').on('focus click', function (e)
	{
		if (!jQuery(this).data('time_picker_initialized'))
			jQuery(this).data('time_picker_initialized', 1).timepicker({"timeFormat":"H:i","scrollDefault":"now","maxTime":"23:59"}).timepicker('show');
	});

	spanDateTimeDefault.show();
	jQuery('#date_time_default_now').prop('checked', (value === '{now}' ? 'checked' : ''));
}

//function for encode html entity (htmlspecialchars)
function html_entity_encode(s) {
	var div = document.createElement('div');
	div.appendChild(document.createTextNode(s));
	return div.innerHTML;
}

function createOption(optionText, optionValue, selectedValues) {
	var selected = false;
	if (selectedValues)
	{
		var arr = selectedValues.split(',');
		jQuery.each(arr, function(k, v) {
			if (v == optionValue)
				selected = true;
		});
	}
	var option = jQuery('<option/>', {
		value: optionValue,
		selected: selected,
		html: optionText
	});
	return option;
}

function trim(str) {
	var re = new RegExp('^[ \\s\xA0]+|[ \\s\xA0]+$', 'g');
	return str.replace(re, '');
}

function expandForFormula(input)
{
	var value = input.val();

	// create textarea
	formulaArea = jQuery('<textarea >', {
		'class' : 'expanded-formula form-control'
	}).text(value).on('blur', function () {
		// collapse on blur
		formulaOpen = false;
		window.setTimeout(function () {
			collapseFormula(input, formulaArea);
		}, 200);
	}).keypress(function(event) {
		// prevent enter from being used
		if (event.which === 13)
			return false;
	}).keyup(function(event) {
		input.val($(this).val());
	});

	// keep formula focus if we use the default formula dropdown
	jQuery('#special_default_select').on('focus', function () {
		formulaOpen = true;
	});

	// set focus
	window.setTimeout(function () {
		formulaArea.focus();
		formulaOpen = true;
	}, 0);

	// append the formula textarea and set new height of form-control
	input.after(formulaArea);
	input.parent().css({
        height: '120px',
        position: 'initial'
	});
}

function collapseFormula(input, formula)
{
	if (!formulaOpen) {
		input
			.val(formula.val())
			.parent().css({ height: 'inherit' });
		formula.remove();
		formulaArea = null;
	}
}

function generateSymName() {
	var length_limit = 40;
    var fieldName = fieldLabel.val();

    var rus = {'а':'a', 'б':'b', 'в':'v', 'г':'g', 'д':'d', 'е':'e', 'ё':'jo', 'ж':'zh', 'з':'z', 'и':'i', 'й':'j', 'к':'k', 'л':'l', 'м':'m', 'н':'n', 'о':'o', 'п':'p', 'р':'r', 'с':'s', 'т':'t', 'у':'u', 'ф':'f', 'х':'h', 'ц':'c', 'ч':'ch', 'ш':'sh', 'щ':'sch', 'ъ':'', 'ы':'y', 'ь':'', 'э':'e', 'ю':'ju', 'я':'ja'};
    var pattern = /[^a-zA-Z0-9_]/g;

	fieldName = fieldName.toLowerCase();
    var sanitizedTitle  = '';
    for (var i = 0; i < fieldName.length; i++)
    {
        var charact = fieldName.substring(i, i + 1);
        if (rus[charact])
            sanitizedTitle += rus[charact];
        else
            sanitizedTitle += charact;
    }

    if (sanitizedTitle.match(pattern))
        sanitizedTitle = sanitizedTitle.replace(pattern, "_");

	if (sanitizedTitle.length > length_limit)
		sanitizedTitle = sanitizedTitle.substring(0, length_limit);

    lastGeneratedSymbolicName = sanitizedTitle;
    fieldSymName.val(lastGeneratedSymbolicName);
}

function addToDefaultValue(txt) {
	var d;
	d = jQuery('#default_value[type=text]:visible');
	if (d.length) {
		if (d.caretPos) {
			var caretPos = d.caretPos;
			caretPos.text = txt;
			d.focus();
		}
		else {
			d.val(d.val() + jQuery(txt).val());
			d.focus();
		}
	}

	if (formulaOpen && formulaArea) {
		formulaArea.val(d.val());
		formulaArea.focus();
	}

	return true;
}

function storeCaret(ftext) {
	if (ftext.createTextRange)
		ftext.caretPos = document.selection.createRange().duplicate();
}

function getLastFieldPosition()
{
    var dropDrownValue = positionDropdownValues.slice(-1)[0];
    return dropDrownValue.id;
}

function setPositionDropdownValueAndOptions(values, exclude_id, dropdown_id)
{
    var html = '';
    for (var i=0; i < values.length; i++)
    {
        var value = values[i];

        if (value.id != exclude_id)
            html += '<option value="'+value.id+'">'+value.text+'</option>';
    }

    $("#"+dropdown_id).html(html);
}


function editField(field_info, e, show_formula) {

	current_field_info = field_info;
	var delete_link = field_info.del_link;

	if (delete_link !== undefined) {
		jQuery('#del_link').prop('href', delete_link);
		jQuery('#delete_field_button').show();
	} else {
		jQuery('#delete_field_button').hide();
	}

	fieldEditDiv.modal();

	var handler = function() {
		jQuery('#field_label').focus();

		if (show_formula)
			expandForFormula(jQuery("#default_value"));

		fieldEditDiv.off('shown.bs.modal', handler);
	};

	// Focus on field title once modal window is fully loaded
	fieldEditDiv.on('shown.bs.modal', handler);

	resetSelectedTab(fieldEditDiv);

	var type = field_info.type;
	fieldTypeSelect.val(type);

    setPositionDropdownValueAndOptions(positionDropdownValues, field_info.position + 1, 'field_number_select');

	// show whatever depends on the field type
	displayField(field_info);

	// Fill common options
	fieldId.val(field_info.id);
	fieldLabel.val(field_info.label);
	fieldSymName.val(field_info.sym_name);
	if (symNameService) {
	    symNameService.resetSection(symNameSection);
    }
	fieldDescr.val(field_info.description);
	fieldNumberSelect.val(field_info.position);
	stringFormatSelect.val(field_info.string_format);
	fieldRequired.prop('checked', field_info.required);
	fieldDisabled.prop('checked', field_info.disabled);
	fieldStyle.val(field_info.style);
	fieldStyleSelect.val(field_info.style);
	fieldStyle2.val(field_info.style2);
	fieldStyle2Select.val(field_info.style2);
	jQuery('#field_group_cells').prop('checked', field_info.group_cells);
	fieldPicklist.prop('checked', field_info.picklist);
	fieldTitleSize.val(field_info.title_size);
	fieldFieldSize.val(field_info.field_size);
	fieldDynamic.prop('checked', field_info.dynamic);

	jQuery('#field_on_top').prop('checked', field_info.on_top);
	fieldTwoCells.prop('checked', field_info.two_cells);
	updateFieldOnTopVisibility();

    if (e) {
        // Set the anchor to point to this Row ID
        var row_id = jQuery(e).parents('.row-fluid').attr('id');
        if(row_id !== undefined) {
        	var action = form.prop('action'),
        		index = action.indexOf('#');

        	// strip out any existing location hash on the form action
        	if(index > 0) {
        		action = action.substr(0, index);
        	}

        	form.prop('action', action + '#' + row_id);
        }
    }

	jQuery('#field_constraint_reg_exp').val(field_info.constraint_reg_exp);
	jQuery('#field_constraint_more_than').val(field_info.constraint_more_than);
	jQuery('#field_constraint_less_than').val(field_info.constraint_less_than);
	jQuery('#field_constraint_size_bigger_than').val(field_info.constraint_size_bigger_than);
	jQuery('#field_constraint_size_smaller_than').val(field_info.constraint_size_smaller_than);

    symbolicNameInitiallyBlank = (jQuery('#field_sym_name').val() == "");

	return true;
}

function editFieldDefault(type, showdiv, properties) {
	var field_info = JSON.parse(default_field_info);

	if (typeof(showdiv) === 'undefined')
		showdiv = 1;
	if (showdiv == 1)
		fieldEditDiv.show();

	type = parseInt(type, 10);

	field_info.type = type;

	// Notice defaults to having no label
	if (type == document.cla_forms.field_types.TYPE_NOTICE)
	{
		field_info.two_cells = 1;
		field_info.field_size = field_info.field_size + field_info.title_size;
		field_info.title_size = 0;
	}

	if (type == document.cla_forms.field_types.TYPE_LABEL)
	{
		field_info.two_cells = 1;
		field_info.title_size = field_info.field_size + field_info.title_size;
		field_info.field_size = 0;
	}

	// Multiple checkboxes default to no default
	if (type == document.cla_forms.field_types.TYPE_MULTIPLE_CHECKBOXES)
		field_info.no_default = 1;

	field_info.position = getLastFieldPosition();

	if (properties)
		jQuery.extend(field_info, properties);

	return editField(field_info);
}

function addNewField(type) {
	editFieldDefault(type, 0, {label: ''});
	fieldLabel.val('');
}

function resetSelectedTab(elem){
	$(elem.find('a[href="#properties"], a[href="#sect_properties"]')).click();
}

function editSection(section_info, e) {
	sectionEditDiv.modal();
	resetSelectedTab(sectionEditDiv);

	setSectionDescr('description_section', section_info.description);

	jQuery('#section_id').val(section_info.id);
	jQuery('#section_label').val(section_info.title);

	// Focus on section title once modal window is fully loaded
	sectionEditDiv.on('shown.bs.modal', function() {
		jQuery('#section_label').focus();
	})

	var style = section_info.style;
	jQuery('#section_style').val(style);
	jQuery('#section_style_select').val(style);

	var styleContent = section_info.style_content;
	jQuery('#section_content_style').val(styleContent);
	jQuery('#section_content_style_select').val(styleContent);

	jQuery('#section_position').val(section_info.position);
	jQuery('#visible_checkbox').prop('checked', section_info.is_visible);
	jQuery('#new_tab_checkbox').prop('checked', section_info.new_tab);

	// Set the anchor to point to this Row ID
	var row_id = jQuery(e).parent('.ic-section-title').attr('id');
	var section_form = jQuery('#edit_section_form');
	section_form.prop('action', section_form.prop('action') + '#' + row_id);

	if (section_info.del_link !== undefined) {
		jQuery('#del_section_link').prop('href', section_info.del_link);
		jQuery('#delete_section_button').show();
	} else {
		jQuery('#delete_section_button').hide();
	}


	return true;
}

function editSectionDefault() {
	var section_info = JSON.parse(default_section_info);
	var position = jQuery('#section_position').find('option').size();
	section_info.position = position;
	section_info.title = 'Default section ' + position;  // Position here makes unique string

	return editSection(section_info);
}

function openUserlistPerms(form_id, field_id) {
	window.open('../forms/edit_perms.php?form_id=' + form_id + '&field_id='+field_id, '_blank', 'width=500,height=340,scrollbars=yes,resizable=yes,hotkeys=no,maximize=no,visible=no');
	return false;
}

jQuery(document).ready(function() {

	symbolicNameInitiallyBlank = ($('#field_sym_name').val() == "");

	jQuery('#section_edit_div,#field_edit_div').on('shown', function(){
		jQuery('#field_label,#section_label').focus();
	});
	jQuery('#field_type_select').bind('change', function() {
		onChangeType();
	});
	jQuery('#swap_view_link').bind('click', function() {
		return SendByPost(this);
	});
	jQuery('#styles_editor_link').bind('click', function() {
		jQuery('#styles_div').show();
		jQuery('#styles_editor_link').hide();
		return false;
	});
	jQuery('#styles_editor_link2').bind('click', function() {
		jQuery('#styles_div').hide();
		jQuery('#styles_editor_link').show();
		return false;
	});
	jQuery('.js-add-field').on('click', function(e) {
		e.preventDefault();
		editFieldDefault(document.cla_forms.field_types.TYPE_SHORT_STRING);
	});
	jQuery('.js-add-section').bind('click', function(e) {
		e.preventDefault();
		editSectionDefault();
	});
	jQuery('#special_default_select').bind('change', function() {
		addToDefaultValue(this);
	});
	jQuery('#save_field_button').bind('click', function() {
        if (symbolicNameIsEmpty || (!hasEditedSymbolicName && symbolicNameInitiallyBlank))
            generateSymName();

		var scrollTop = $(document).scrollTop();
		$("input[name='last_scroll_position_y']").val(scrollTop);
	});
	jQuery('#delete_field_button').bind('click', function() {
		return SendByPost(document.getElementById('del_link'), confirm('Are you sure?'));
	});
	jQuery('#delete_section_button').bind('click', function() {
		return SendByPost(document.getElementById('del_section_link'), confirm('Are you sure?'));
	});
	jQuery('#grid_editor_link').bind('click', function(){
		jQuery('#grid_div').show();
		jQuery('#grid_editor_link').hide();
		jQuery('#field_style_select5').val('SectionHeader').change();
		jQuery('#field_style_select3').val('FieldName').change();
		jQuery('#field_style_select4').val('FieldInput').change();
		jQuery('#position_select').val(jQuery('#position_select :last').val());
		jQuery('#field_two_cells2').prop('checked', true);
		return false;
	});
	jQuery("#discard_changes").bind('click', function() {
		return !!confirm(lmsg('helpdesk.issue.confirm_reset'));
	});
	jQuery('#deleteSelected').on('click', function(){
		jQuery('#changeFieldsForm').submit();
	});

	// tabs
	jQuery(".tabs").each(function(){
		cla_tabs_init(jQuery(this), { show_override : function () {} });
	});

    // Get values of position dropdown
    $('#field_number_select > option').each(function(){
        positionDropdownValues.push(
            {
                "text" : $(this).text(),
                "id" : $(this).attr('value')
            });
    });

    $('#field_sym_name').change(function(){
        if ($(this).val() != lastGeneratedSymbolicName)
            hasEditedSymbolicName = true;
        if ($(this).val() == "")
            symbolicNameIsEmpty = true;
    });

    $('#field_label').change(function(){

        if (symbolicNameIsEmpty || (!hasEditedSymbolicName && symbolicNameInitiallyBlank))
            generateSymName();

    });

    // hide parent container for hidden infocapture elements;
	$('.infocapture-hidden').parent().addClass('infocapture-hidden-parent');

});
