/* Home Page Module Sort */
/**
 * 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 AddPeer = Class.create();
AddPeer.prototype = {
	//Properties
	el: null,
	parent:null,
	ajax: null,
	ajaxUrl: null,
	modName: null,
	id: null,
	
	//Constructor
	initialize: function(el, show) {
		this.el = el;
		this.modName = this.el.href.getUrlArgument().split('|')[0];
		this.id = this.el.href.getUrlArgument().split('|')[1];
		this.observeLink();
	},
	
	//Methods
	observeLink: function () {
		this.removeFunc = this.addPeer.bindAsEventListener(this);
		Event.observe(this.el, 'click', this.removeFunc);
	},
	addPeer: function ()
	{
		this.parent = this.el.parentNode;
		if (Element.hasClassName(this.el, 'in_network'))
		{
			this.el.innerHTML = 'Add to Peer Network';
			this.action = true;
			Element.removeClassName(this.el, 'in_network');
		}
		else {
			this.el.innerHTML = 'Remove from Peer Network';
			this.action = false;
			Element.addClassName(this.el, 'in_network');
		}
		this.AjaxOut();
		new Effect.Highlight(this.parent);
	},
	AjaxOut: function() {
		var vars = '__ajax__=' + this.modName + '&id=' + this.id + '&action=' + (this.action ? 'remove' : 'add');
		//alert( vars );
		this.ajax = new Ajax.Request(window.location,
			{
				parameters: vars,
				onSuccess: this.AjaxIn.bind(this)
			}
		);
	},
	AjaxIn : function(req)
	{
		//alert(req.responseText);
		//var result = DOM.getElementTextNS(null, 'result', req.responseXML, 0);
		//alert(result);
		
		this.refindLink();
		this.observeHide();
	}
};


EventSelectors.register({
	'.add_peer a': function(el) {
		new AddPeer(el, true);
	}
}, true);

/*var AddPeer_Rules = {
	'.add_peer a' : function(el){
		new AddPeer (el, true);
	}
};
Behaviour.register(AddPeer_Rules);*/
