/* 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 ShowHideModuleClass = Class.create();
ShowHideModuleClass.prototype = {
	//Properties
	el: null,
	id: null,
	show:null,
	parent:null,
	ajax: null,
	modName: 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.show = show;
		if (this.show)
			this.observeShow();
		else
			this.observeHide();
	},
	
	//Methods
	observeHide: function () {
		Event.observe(this.el, 'click', this.showHideModule.bind(this));
	},
	observeShow: function () {
		Event.observe(this.el, 'click', this.showHideModule.bind(this));
	},
	showHideModule: function () {
		Element.removeClassName(this.el, this.show ? 'status_show' : 'status_hide');
		Element.addClassName(this.el, !this.show ? 'status_show' : 'status_hide');
		this.el.innerHTML = this.show ? 'hide' : 'show';
		this.parent = this.el.parentNode;
		var searchText = this.show ? 'currently hidden' : 'currently shown';
		var replaceText = !this.show ? 'currently hidden' : 'currently shown';
		this.parent.innerHTML = this.parent.innerHTML.replace(searchText, replaceText);
		this.show = this.show ? false : true;
		this.AjaxOut();
		new Effect.Highlight(this.parent);
	},
	refindLink: function () {
		var links = this.parent.getElementsByTagName('a');
		if (links.length == 1)
			this.el = links[0];
		else if (links.length > 1)
		{
			$A(links).each(this.walkLinks.bind(this));
		}
	},
	walkLinks: function (el) {
		if (Element.hasClassName(el, this.show ? 'status_show' : 'status_hide')) {
			this.el = el;
		}
	},
	AjaxOut: function() {
		var vars = '__ajax__=' + this.modName + '&id=' + this.id + '&status=' + (this.show ? 'hide' : 'show');
		//alert( vars );
		this.ajax = new Ajax.Request(window.location,
			{
				parameters: vars,
				onSuccess: this.AjaxIn.bind(this)
			}
		);
	},
	AjaxIn : function(req) {
		this.refindLink(); 
		this.observeHide();
	}
};

/*var ShowHideModuleClass_Rules = {
	'.status a.status_show' : function(el){
		new ShowHideModuleClass (el, true);
	},
	'.status a.status_hide' : function(el){
		new ShowHideModuleClass (el, false);
	}
};
Behaviour.register(ShowHideModuleClass_Rules);*/
EventSelectors.register({
	'.status a.status_show' : function(el){
		new ShowHideModuleClass (el, true);
	},
	'.status a.status_hide' : function(el){
		new ShowHideModuleClass (el, false);
	}
}, true);
