// These three 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 excludedMembers = [];
var sortable_table_id = 'statuses_table_main';
jQuery(function () {
	jQuery("#"+sortable_table_id+" tbody").tableDnD({
		onDragClass: "dragged_tr",
		onDrop: function(tbody, row)
		{
			colorify_sort_column();
			setSavingAlert();
		}
	});
});

function colorify_sort_column()
{
	jQuery('td:first', jQuery("tr:even", jQuery('#'+sortable_table_id+' tbody'))).attr('style', 'background-color:#e0e0e0; color: #000 !important');
	jQuery('td:first', jQuery("tr:odd", jQuery('#'+sortable_table_id+' tbody'))).attr('style', 'background-color:#f3f4f8; color: #000 !important');
}

var saving_alert_set = false;
function setSavingAlert()
{
	if (!saving_alert_set)
	{
		jQuery("#"+sortable_table_id+" tfoot td").prepend(lmsg('panels.helpdesk.statuses_order_changed_save')+"&nbsp;&nbsp;&nbsp;");
		saving_alert_set = true;
	}
}

function editStatus(code, title, color, description, is_archived, archive_period, is_new)
{
	if (color.length == 0)
		color = 'ffffff';

	div = jQuery('#edit_status_div');

	div.find('input[name=code]').val(code);
	div.find('input[name=old_code]').val(code);
	div.find('input[name=title]').val(title);
	div.find('input[name=color]').val('#'+color).css('background-color', '#'+color);
	div.find('textarea[name=description]').val(description);
    div.find('input[name="archive_idle_time"]').val(archive_period);

    if(code == ''){
		$('#editStatusTitle').html(lmsg('panels.helpdesk_statuses.add_new_status')); // "Add new status");
	} else {
		$('#editStatusTitle').html(lmsg('panels.helpdesk_statuses.edit_status', title));
	}
	var archive_idle_time = jQuery('#archive_idle_time');
	if(is_archived == 1)
	{
		jQuery('#archive_checkbox').prop('checked', true);
		archive_idle_time.prop('disabled', false);
	} else
	{
		jQuery('#archive_checkbox').prop('checked', false);
		archive_idle_time.prop('disabled', true);
	}
	archive_idle_time.val(archive_period);

	if (jQuery('#status_code').val() == "")
        symbolicNameInitiallyBlank = true;
    else
        symbolicNameInitiallyBlank = false;

	return true;
}
function editGroup(group_id, name, description, state, statuses, is_new)
{
	var div = jQuery('#edit_group_div');
	div.find('input[name=group_id]').val(group_id);
	div.find('input[name=name]').val(name);
	div.find('textarea[name=description]').val(description);
	div.find('select[name=state]').val(state);
	if(group_id === '') {
		$('#editGroupTitle').text(lmsg('panels.helpddesk_statuses.add_status_group'));
	} else {
		$('#editGroupTitle').text(lmsg('panels.helpddesk_statuses.edit_group', name));
	}

	jQuery('#status_list').empty();
	jQuery.each(statuses, function(key, value){
		var isChecked = value.member ? true : false;
		var label = jQuery('<label/>', {
			'for' : 'member_' + key,
            'class' : 'form-check-label'
        });
		var check = jQuery('<input/>',{
			type : 'checkbox',
			id : 'member_' + key,
			name : 'members[]',
			value : key,
			checked : isChecked,
            'class' : 'form-check-input'
        });
		var div = jQuery('<div/>', {
			'class' : 'form-check'
		});
		check.appendTo(div);
		(label).append(value.title);
		label.appendTo(div);
		div.appendTo(jQuery('#status_list'));
	});

	div.modal('show');

	return true;
}

function deleteGroup(link){
	jQuery(link).tooltip('hide');
	var row = jQuery(link).parent().parent();
	var href = link.href;
	var csrfToken = jQuery('input[name="csrf_token"]').val();
	jQuery.ajax({
		url: href,
		method: 'POST',
		data: 'csrf_token=' + csrfToken
	});
	row.remove();
	return false;
}

function validateEditForm(context)
{
	if(context === 'status') {
		if (!isStatusCodeValid())
			return false;
		if (!isTitleExists())
			return false;
		return true;
	}
	if(context === 'group') {
		return true;
	}
}

function isStatusCodeValid()
{
	var container = jQuery('#edit_status_div');
	var code = jQuery.trim( container.find('input[name=code]').val() );
	if (code.length == 0)
	{
		alert(lmsg('helpdesk.project.status_code_empty_error'));
		return false;
	}

	if (isStatusCodeExists(container, code))
	{
		alert(lmsg('helpdesk.project.status_code_exists_error'));
		return false;
	}

	if ( isCodeChanged(container, code) && !confirm(lmsg('panels.helpdesk.change_code_confirm')) )
	{
		restoreOldCode(container);
		return false;
	}

	return true;
}

function isStatusCodeExists(container, code)
{
	var old_code = container.find('input[name=old_code]').val();
	if (old_code == code)
		return false;

	var codes = getAllCodes();
	for (var i = 0; i < codes.length; i++)
	{
		if (code == codes[i])
			return true;
	}

	return false;
}

function isTitleExists()
{
	var container = jQuery('#edit_status_div');
	var title = jQuery.trim( container.find('input[name=title]').val() );
	if(title.length == 0)
	{
		alert(lmsg('helpdesk.project.status_title_empty_error'));
		return false;
	}
	return true;
}

function isCodeChanged(container, new_code)
{
	var old_code = container.find('input[name=old_code]').val();
	if (old_code.length > 0 && old_code != new_code)
		return true;

	return false;
}

function restoreOldCode(container)
{
	container.find('input[name=code]').val(
		container.find('input[name=old_code]').val()
	);
}

function deleteStatus(link, status_title)
{
	var message;
	if (getStatusesCount() == 1)
		message = lmsg('panels.helpdesk.delete_last_status_confirm');
	else
		message = lmsg('panels.helpdesk.delete_status_confirm', status_title);

	if (confirm(message))
	{
		SendByPost(link);
	}
}

function getStatusesCount()
{
	return jQuery('#'+sortable_table_id).find('tbody tr').length;
}

function getAllCodes()
{
	var trs = jQuery('#statuses_table_main').find('tbody tr');
	var codes = new Array();

	jQuery.each(trs, function(i, tr){
		codes.push(jQuery.trim(jQuery(tr).find('td:first').text()));
	});
	return codes;
}

function prepareStatusesOrder()
{
	var codes = getAllCodes();
	jQuery('#statuses_order').val(codes.toString());

	// Everything is fine. So we can return true and this will submit the form
	return true;
}

jQuery(document).ready(function() {
	jQuery('#archive_checkbox').bind('change', function(){
		jQuery('#archive_idle_time').prop('disabled', !jQuery(this).prop('checked'));
	});

	if(jQuery('#archive_idle_time').val()!=="undefined" && jQuery('#archive_idle_time').val()!==undefined ) {
		if (jQuery('#archive_idle_time').val().length === 0) {
			jQuery('#archive_idle_time').val('0');
		}
	}

	colorify_sort_column();
	jQuery('#editGroup').bind('click', function(){
		editGroup('', '', '', 0, statuses, 1);
	});

	jQuery('#addStatus').bind('click', function(){
		editStatus('', '', '', '','');
	});

	jQuery('#status_enabled_check').on("change",function(){
        jQuery('#toggle_status_form')[0].submit();
	});

});

function generateSymName() {
	var length_limit = 40;
    var fieldName = $('#status_title').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;
    $('#status_code').val(lastGeneratedSymbolicName);
}

jQuery(document).ready(function()
{
	if($('#status_code').val() == "")
        symbolicNameInitiallyBlank = true;
    else
        symbolicNameInitiallyBlank = false;

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

	$('#status_save_button').change(function()
    {
        if (symbolicNameIsEmpty || (!hasEditedSymbolicName && symbolicNameInitiallyBlank))
            generateSymName();

    });

    $('#status_title').change(function()
    {
        if (symbolicNameIsEmpty || (!hasEditedSymbolicName && symbolicNameInitiallyBlank))
            generateSymName();

    });
});
