// note-tag.js
// Copyright (C) 2006 Notefish. All rights reserved.
// tagging support

// tag editor class
function TagEdit()
{
	GetElem("tag-cap").onclick   = function() { theApp.tagEdit.editTags();  };
	GetElem("new-tags").onclick  = function() { theApp.tagEdit.editTags();  };
	GetElem("tag-editor").onblur = function() { theApp.tagEdit._done(true); };
}

TagEdit.prototype.tags = ""; // current list of tags
TagEdit.prototype.oldDocKeyDown = null;
TagEdit.prototype.editPending = false;
TagEdit.prototype.editing     = false;

TagEdit.prototype.uninit = function()
{
	GetElem("tag-cap").onclick  = function() {};
	GetElem("new-tags").onclick = function() {};
}

TagEdit.prototype.editTags = function()
{	
	this.editPending = true;
	theApp.server.getTags();
};

TagEdit.prototype.onTagsReady = function(tags)
{
	this.tags = tags;

	if (this.editPending) this._edit();
	else this._displayTags();
};

TagEdit.prototype._edit = function()
{
	this.editPending = false;
	this.editing = true;

	GetElem("no-tags").style.display = "none";
	GetElem("pro-tags").style.display = "none";
	GetElem("edit-tags").style.display = "";
	
	var e = GetElem("tag-editor");
	e.value = this.tags.join(", ");
	
	// select edit box contents and set focus on it
	if (e.setSelectionRange){
		e.setSelectionRange(0, e.value.length);
	}
	if (e.createTextRange){
		var rng = e.createTextRange();
		rng.select();
	}

	this.oldDocKeyDown = document.onkeydown;
	document.onkeydown = function(e){ theApp.tagEdit._onDocKeyDown(e); };
	e.focus();
};

TagEdit.prototype._onDocKeyDown = function(e)
{
	e = FixEvent(e);
	switch (e.keyCode){
	case 27:
		this._done(false);
		break;

	case 13:
		this._done(true);
		break;
	}	
};

TagEdit.prototype._done = function(save)
{
	if (!this.editing) return;
	this.editing = false;

	this._clearDisplayTags();

	document.onkeydown = this.oldDocKeyDown;
	this.oldDocKeyDown = null;

	GetElem("edit-tags").style.display = "none";
	GetElem("no-tags").style.display = "none";
	GetElem("pro-tags").style.display    = "";

	if (save){
		theApp.server.setTags(GetElem("tag-editor").value);
	}
	else{
		this._displayTags();
	}
};

TagEdit.prototype._clearDisplayTags = function()
{
	var e = GetElem("pro-tags");

	// delete the existing tags
	var len = e.childNodes.length;
	for (var i = 0; i < len; ++i){
		var l = e.childNodes[i];
		if (l.nodeType == 3 || (l.nodeType == 1 && l.tagName.toLowerCase() == "a")){
			e.removeChild(l);
			--i; --len;
		}
	}
};

TagEdit.prototype._displayTags = function()
{
	var e = GetElem("pro-tags");
	var tags = this.tags;
	var len = tags.length;
	if (len > 0){
		for (var i = 0; i < len; ++i){
			var t = tags[i];
			var a = document.createElement("a");
			a.className = "tag";
			a.href = "search.php?query=" + encodeURIComponent(t) + "&st=tag";
			a.innerHTML = t;
			e.appendChild(a);
			if (i < len - 1) e.appendChild(document.createTextNode(", "));
		}
	}
	else{
		e.style.display = "none";
		GetElem("no-tags").style.display = "";
	}
};

