/* Add Tags */
/**
 * Turns a URL into an argument for links which function
 * purely as event launchers.
 */
String.prototype.getUrlArgument = function() {
	// Parses a URL like "javascript:void(42);" and returns "42"
	if (val = this.match(/[Jj]avascript:void\(\'?(.*?)\'?\);?/i)) {
		if (val[1]) return val[1];
	}
	return this;
}

var AddTags = Class.create();
AddTags.prototype = {
	//Properties
	el: null,
	parent:null,
	ajax: null,
	ajaxUrl: null,
	TagValue: null,
	
	//Constructor
	initialize: function(el) {
		this.el = el;
		this.id = this.el.id;
		this.ajaxUrl = window.location;
		this.observeLink();
		if(document.all)
			Event.observe($('newtags'), 'keydown', this.ieKeyPress.bind(this));
	},
	
	//Methods
	ieKeyPress: function (e) {
		if(e.keyCode == 13)
			this.addTags();
	},
	observeLink: function () {
		this.removeFunc = this.addTags.bindAsEventListener(this);
		Event.observe(this.el, 'click', this.removeFunc);
	},
	addTags: function () {
		if (!/^\s*$/.test($('newtags').value)) {
			this.TagValue = $('newtags').value;
			this.AjaxOut();
		}
		
	},
	AjaxOut: function() {
		var vars = '__ajax__=TagAdd&tagvalue=' + this.TagValue + '&content_id=' + this.id;
		//alert(vars);
		this.ajax = new Ajax.Request(this.ajaxUrl,
			{
				parameters: vars,
				onSuccess: this.AjaxIn.bind(this)
			}
		);
	},
	AjaxIn : function(req) {
		//alert(req.responseText);
		var result = req.responseXML.getElementsByTagName('result')[0];
		if(result.getAttribute('prevtagged')=="false")
		{
			var a = document.createElement('a');
			a.href = '/tags/listing/'+result.getAttribute('tagid');
			a.id = 'tag'+result.getAttribute('tagid');
			a.appendChild(document.createTextNode($('newtags').value+'(1)'));
			if ($('tags').getElementsByTagName('a').length != 0)
			{
				$('tags').appendChild(document.createTextNode(', '));
			}
			$('tags').appendChild(a);
			
		}
		else
		{
			//alert('tag'+result.getAttribute('tagid'));
			var a = $('tag'+result.getAttribute('tagid'));
			if(result.getAttribute('inserted')=="true")
			{
				//increment number
				//var t = a.text;
				var t = a.innerHTML;
				//alert(t);
				var length = t.length;
				var left_paren_pos;
				for(i=length-1;i>-1;i--)
				{
					if(t.charAt(i)=='(')
					{
						left_paren_pos = i;
						i=-1;
					}
				}
				var tagnum = parseInt(t.substring(left_paren_pos+1,length-1));
				tagnum++;
				var newtext = t.substring(0,left_paren_pos+1) + tagnum + ')';
				a.innerHTML = newtext;
			}
		}
		$('newtags').value = '';
		new Effect.Highlight(a);
	}
};

EventSelectors.register({
	'.addtags input.image': function(el) {
		new AddTags(el);
	}
}, true);

/*
var AddTags_Rules = {
	'.addtags input.image' : function(el){
		new AddTags (el);
	}
};
Behaviour.register(AddTags_Rules);*/