/* (c) 2008-2009, Nikiforov Vladimir aka Volod */

function addTagToText(t)
{
	ta = document.getElementById('tags');
	if (ta.value != '')	ta.value += ', ';
	ta.value += t;
}

function loadTags_callback(a)
{
	
	f = document.getElementById('TagEditForm');
	
	f.avtags.options.length = 0;
	
	for (var i = 0; i < a.length; i++)
	{
		f.avtags.options[i] = new Option(a[i], a[i], false, false);
	}

	sortSelect(f.avtags);
}

function loadTags(id, which)
{
	$.getJSON(
		'/otd_tag_form.php',
		{id: id, action: 'gettags', which: which},
		loadTags_callback
	);
}

function onListKeyPress(f, e, action)
{
	if ((e.keyCode == 13) || (e.keyCode == 10))
	{
		if (e.ctrlKey)
		{
			submitTagsForm(f.id.value, true);
		}
		else
		{
			if (action == 1)
				addTag(f);
			if (action == 2)
				removeTag(f);
			if (action == 3)
				addNewTag(f);
		}
	}

	if (e.keyCode == 27)
		dialog.cancel();
}


function addNewTag(f)
{
	index = f.tags.options.length;
	if (f.newtag.value != '')
	{
		f.tags.options[index] = new Option( f.newtag.value, 0, false, true);
		f.newtag.value = '';
	}
	else
	{
		alert('Заполните поле слева от этой кнопки');
	}
}

function addTag(f)
{	
	moveBetweenSelectors(f.avtags, f.tags);
	sortSelect(f.avtags);
	sortSelect(f.tags);
}

function removeTag(f)
{
	moveBetweenSelectors(f.tags, f.avtags);
	sortSelect(f.avtags);
	sortSelect(f.tags);
}


function submitTagsForm_callback(reload)
{
	if (document.result != 'OK')
		alert(document.result);
	else
		if (reload)
			document.location.reload();
		else
			dialog.cancel();
}

function submitTagsForm(id, reload)
{
	e = document.getElementById('TagEditForm');
	tags = '';
	for (i=0; i < e.tags.length; i++)
		if (e.tags[i])
			tags += ',' + e.tags[i].text;

	sendRequest({
		'url' : '/otd_tag_form.php?id=' + id + '&action=save&tags=' + escape(tags),
		'callback' : 'submitTagsForm_callback(' + reload + ')',
		'result' : document,
		'field' : 'result'
	});
	return false;
}

function openTagsForm_callback(id)
{
	f = document.getElementById('TagEditForm');
	sortSelect(f.avtags);
	sortSelect(f.tags);	
//dialog.show() - перед focus, а то IE ругается, что не может сфокусироваться на невидимом элементе
	dialog.show();
	f.avtags.focus();
	if (f.avtags.options.length > 0)
		f.avtags.options[0].selected = true;
}

function openTagsForm(id, reload)
{
	if (document.windowID > 0)
	{
		r = (document.windowID == id);
		dialog.cancel();
		if (r) return;
	}
	document.windowID = id;
	
	dialog.open({
		'url' : '/otd_tag_form.php',
		'params' : 'reload=' + reload + '&id=' + id,
		'callback' : 'openTagsForm_callback(' + id + ')'
	});
}