// code for cascade tags selection
function setupCascadeTags() {
	$("#tag_l1").change(function(){
		var newValue = $(this).val();
		clearSelect("#tag_l2");
		clearSelect("#tag_l3");
		if(newValue>0) {
			$.ajax({
				url: "?action=tags&sa=subtags&pid="+newValue, 
				dataType: "json",
				success: function(data) {
						loadValues("#tag_l2", data);
					},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					alert(errorThrown);
				}
			});
		}
	});

	$("#tag_l2").change(function(){
		var newValue = $(this).val();
		clearSelect("#tag_l3");
		if(newValue>0) {
			$.ajax({
				url: "?action=tags&sa=subtags&pid="+newValue, 
				dataType: "json",
				success: function(data) {
						loadValues("#tag_l3", data);
					},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					alert(errorThrown);
				}
			});
		}
	});
}

function loadValues(select, data)
{
	$.each(data, function() {
		$(select).append($('<option></option>').val(this.ID_TAG).html(this.tag));
	});
}

// clear a tag select of non default values
function clearSelect(select)
{
	$(select+" option[value!='-1']").remove();
	$(select).val(-1);
}

function onAddTag()
{
	var l1 = $('#tag_l1').val();
	var l2 = $('#tag_l2').val();
	var l3 = $('#tag_l3').val();
	var topic = $('#topic_id').val();
	if(l1>0)
	{
		$.ajax({
			url: "?action=tags&sa=tagtopic",
			data: {'topic': topic, 'l1':l1,'l2':l2,'l3':l3},
			dataType: "json",
			success: function(data) {
					if(data.id>0) {
						writeTag(data, true);
					} else {
						alert('Already set!');
					}
				},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				alert(errorThrown);
			}
		});
	}
}

function writeTag(data, withRemove)
{
	newHtml = '<li id="rt_'+data.id+'">';
	newHtml+= data.t1;
	if(data.t2!='')
		newHtml+= ' - '+data.t2;
	if(data.t3!='')
		newHtml+= ' - '+data.t3;
	newHtml+=' <input class="remTagBtn" ';
	if(!withRemove)
		newHtml += ' style="display: none;"';
	newHtml+=' type="button" value="'+txt_tags_rem_cat+'" onclick="removeTag('+data.id+');">';
	newHtml+= '</li>';
	$('#remTagArea').append(newHtml);
}

function removeTag(id)
{
		$.ajax({
			url: "?action=tags&sa=remtagtopic",
			data: {'id':id},
			dataType: "json",
			success: function(data) {
					$('#rt_'+id).remove();
				},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				alert(errorThrown);
			}
		});	
}
