/**
 * @author		TimWolla / Tatzelwurm
 * @copyright	2001-2011 WoltLab Community/WBB3Addons
 * @license		GNU Lesser Public License <http://www.gnu.org/licenses/lgpl.html>
 */
document.observe('dom:loaded', function () {
	$$('#userGalleryBoxHeadlines a').each (function (e) {
		e.observe('click', function (e) {
			new Ajax.Updater('userGalleryBoxImageContainer', this.href.gsub('Portal', 'UserGalleryBox'));
			
			var old = $$('#userGalleryBoxHeadlines .selected')[0];
			var oldSort = old.down('a').className;
			if (old != this.parentNode) {
				// remove old Class Names
				old.removeClassName('selected');
				old.down('a').removeClassName('DESC');
				old.down('a').removeClassName('ASC');

				// if image set, remove image
				if (old.down('img')) {
					old.down('img').remove();
				}
				// change asc to desc if not "lastCommented"
				if (!old.down('a').href.include('ugbSortField=lastCommented')) {
					// reset to DESC an new link to ASC
					old.down('a').href = old.down('a').href.gsub('ugbSortOrder=ASC', 'ugbSortOrder=DESC');
					this.href = this.href.gsub('ugbSortOrder=DESC', 'ugbSortOrder=ASC');
				}
				// Add Class name
				this.parentNode.addClassName('selected');

				// insert Image if not "lastCommented" ** this do not work !!!
				if (!this.href.include('ugbSortField=lastCommented')) {
					this.insert(new Element('img', { src: iconPaths.DESC }));
				}
				this.href = this.href.gsub('ugbSortOrder=DESC', 'ugbSortOrder=ASC');
			}
			else {
				if (this.href.include('ugbSortField=lastCommented')) {
					e.stop();
					return;
				}
				if (this.hasClassName('DESC')) {
					// change to ASC
					this.addClassName('ASC');
					this.removeClassName('DESC');
					this.down('img').src = this.down('img').src.gsub('DESC', 'ASC');
					this.href = this.href.gsub('ugbSortOrder=ASC', 'ugbSortOrder=DESC');
				}
				else {
					// change to DESC
					this.addClassName('DESC');
					this.removeClassName('ASC');
					this.down('img').src = this.down('img').src.gsub('ASC', 'DESC');
					this.href = this.href.gsub('ugbSortOrder=DESC', 'ugbSortOrder=ASC');
				}
			}
			e.stop();
		}.bindAsEventListener(e));
	});
});
