//-----( AJAX functions for tags )-------------------------------------------------

// remove tag --------------------------------------------
function removeTag (obj, contenttotagid) {
	var pars = 'contenttotagid=' + contenttotagid;
	new Effect.Highlight(obj, {startcolor:'#ffd743', endcolor:'#fffce4'})

	// call /assets/remove_tag.php with the parameters and call tag_remove afterwards
	myAjax = new Ajax.Request('/assets/ajax/remove_tag.php', {method: 'get', parameters: pars, onSuccess: tagRemoved});
}

function tagRemoved (requestObj) {
	Element.remove(requestObj.responseText);
}


// add tag --------------------------------------------
function addTag (f) {
	var tag = f.tag.value;
	var userid = f.userid.value;
	var contenttype = f.contenttype.value;
	var contentid = f.contentid.value;
	var pars = 'tag=' + escape(tag) + '&userid=' + userid + '&contenttype=' + contenttype + '&contentid=' + contentid;
	
	// call /assets/add_tag.php with the parameters and call tagAdded afterwards
	myAjax = new Ajax.Request('/assets/ajax/add_tag.php', {method: 'get', parameters: pars, onSuccess: tagAdded});
}

function tagAdded (requestObj) {
	if (requestObj.responseText == '0') {
		alert ('Etiketten finns redan!');
		return;
	}
	// clear the input field on success
	var f = $('add_tag_form');
	var field = f.tag;
	field.value = '';   
	
	// loop through all pairs of tags on the format "id1:tag1;id2:tag2;..."
	var tagPairs = requestObj.responseText.split(";");
	var numTagPairs = tagPairs.length;
	var tagPair, tagId, tagValue;
	
	for (var i = 0; i < numTagPairs; i++) {
		tagPair = tagPairs[i].split(":");
		tagId = tagPair[0];
		tagValue = tagPair[1];
		// add HTML for the new tag and highlight it!
		new Insertion.Bottom('tag_list', '<li id="tag-'+tagId+'"><a href="/tag/'+tagValue+'/">'+tagValue+'</a><a class="tag_list_del" href="#" onclick="removeTag($(\'tag-'+tagId+'\'), '+tagId+');return false;"><img src="/pics/btn_tag_del.gif" alt="Ta bort etikett" /></a>');
		new Effect.Highlight('tag-' + tagId, {startcolor:'#ffd743', endcolor:'#fffce4'})
	}
}


function readCookie (name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function get_logged_in_user() {
	return readCookie("cuser");
}
function output_login_info() {
	var user = get_logged_in_user();
	if (user) {
		document.write ('<a href="/user/view/' + user + '/">' + user + '</a> | <a href="/logout/">Logga ut</a>');
	} else {
		document.write ('<a href="/login/">Logga in</a> | <a href="/user/add/">Ny anv&auml;ndare</a>');
	}	
}
