var CUserMenu = Class.create({
	initialize: function(objRoot, objDir) {
		this.entries = this.active = this.menus = this.titles = null;
		this.observing = false;
	},

	hidePath: function()
	{
		Root.activate(null);
		Dir.hide();
	},

	switchMenu: function(title, hide)
	{
		var sect = $(title).up();
		var cookie_name = "pddbbs_um" + sect.previousSiblings().length.toString();

		// lo mostro
		if (sect.hasAttribute('hidden')) {
			new Effect.BlindDown(sect.down('.voices'), { duration: 0.2, afterFinish: function() {
				sect.removeAttribute('hidden');
				Cookie.set(cookie_name, '1', 1);
			} });
		// se posso nasconderlo, lo nascondo
		} else if (hide) {
			new Effect.BlindUp(sect.down('.voices'), { duration: 0.2, afterFinish: function() {
				sect.writeAttribute('hidden');
				Cookie.unset(cookie_name);
			} });
		}
	},
	switchMenuOnEvent: function(event)
	{
		this.switchMenu(event.element(), true);
	},

	activate: function(el)
	{
		el = $(el);
		if (el == this.active) return;
		if (this.active != null) Observer.deactivate(this.active);

		if (el != null) {
			this.hidePath();
			this.switchMenu(el.up().previous(), false);
			Observer.activate(el);
		}

		this.active = el;

		if (el != null && ['user-recent', 'user-search', 'user-new'].include(el.id)) {
			Event.observe(document, 'keydown', this.doSearch);
			this.observing = true;
		} else if (this.observing) {
			Event.stopObserving(document, 'keydown', this.doSearch);
		}
	},
	// fai la ricerca dei recent
	doSearch: function(event) {
		if (!['forum_picker', 'new_users', 'forum_list', 'new_users_list'].member(event.element().id) 
			&& event.keyCode == 13) {
			if (Ubk.followLink('do-search')) event.stop();
		}
	},

	clickOnEvent: function(event)
	{
		// annerisco il content solo se non ho aperto in altra finestra
		if ((event.isLeftClick() && event.ctrlKey) || event.isMiddleClick()) return;

		Ubk.hide('content');
		this.activate(event.element());
		
	},

	click: function(el)
	{
		this.activate(el);
		Ubk.followLink(el);
	},

	inbox: function(post)
	{
		this.activate('user-inbox');
		eval(decodeURIComponent($('user-inbox').href).substr(11)
			.replace('PM-GO=0', 'PM-GO=' + post)
		);
	},

	outbox: function(post)
	{
		this.activate('user-inbox');
		eval(decodeURIComponent($('user-inbox').href).substr(11)
			.replace('=inbox', '=outbox')
			.replace('PM-GO=0', 'PM-GO=' + post)
		);
	},

	observe: function()
	{
		var f = function() {

			this.menus = $$('#user-menu div.section');
			this.menus.shift(); // tiro via i tips che sono i primi
			this.titles = this.menus.invoke('down', '.title');

			for(i = 0; i < this.titles.length; i++) {
				t = this.titles[i];
				s = t.up();
				cn = "pddbbs_um" + s.previousSiblings().length.toString();
				if (Cookie.get(cn)) {
					s.down('.voices').show();
					if (s.hasAttribute('hidden')) s.removeAttribute('hidden');
					Cookie.set(cn, '1', 1);
				} else {
					s.down('.voices').hide();
					s.writeAttribute('hidden');
					Cookie.unset(cn);
				}
			}

			this.titles.invoke('observe', 'click', this.switchMenuOnEvent.bindAsEventListener(this));
		
			this.entries = $$('#user-menu a').filter(function(e) {
				return (!(e.ancestors().include($('tips'))) &&
					!(['login-button', 'bo-button', 'sitemap', 'tips-force', 'kml'].include(e.id)) &&
					!(e.hasClassName('forum_bmk')));
			});
			this.entries.invoke('observe', 'click', this.clickOnEvent.bindAsEventListener(this));
		};
		f.bind(this).defer();
	}
});

var CUserFeed = Class.create({
	moveUp: function(id)
	{
		var feed = $('feed_'+id);
		var prev = feed.previous();
		prev.up().removeChild(feed);
		prev.up().insertBefore(feed, prev);
	},
	moveDown: function(id) {
		var feed = $('feed_'+id);
		var next = feed.next(1);
		next.up().removeChild(feed);
		next.up().insertBefore(feed, next);
	},
	up: function(id)
	{
		Ubk.follow(null, 'users.php', 'AZIONE=feed_up&ID='+id, false, true);
	},
	down: function(id)
	{
		Ubk.follow(null, 'users.php', 'AZIONE=feed_down&ID='+id, false, true);
	},

	thumb: function(id)
	{
		Ubk.follow('feed_'+id, 'feed.php', 'TABELLA=t_s_user_feed&AZIONE=getFeed&ID='+id+'&XSL=system/xsl/user-feed-thumb.xsl', true, true);
	},

	makeSortable: function()
	{
		Sortable.create('forumcontent', {
			tag: 'div'
			,handle: '.top'
			,overlap: 'horizontal'
			,constraint: false
			,onUpdate: User.Feed.updateOrder
		});
	},

	updateOrder: function(container)
	{
		var childs = container.select('div');
		var ids = childs.pluck('id').collect(function(id) { return id.substr(id.lastIndexOf('_') + 1); });

		Ubk.follow(null, 'feed.php', 'TABELLA=t_s_user_feed&AZIONE=updateOrder&IDS='+ids.join('|'), false, true);
	}

});

var CUserLogin = Class.create({
	login: function()
	{
		var onComplete = function(request) { 
			if (!Ubk.isFailure(request)) {
				var ok_msg = request.responseText.substr(3);
				if (ok_msg.indexOf('javascript:') == 0)
					eval(ok_msg.substr(11));
				else
					window.location.replace(
						window.location.protocol + '//' + 
						window.location.host +
						window.location.pathname
					);
			}
		};

		new Ajax.Request(
			'login.php',
			{
				method: 'post'
				,evalScripts: false
				,parameters: 'AZIONE=login&' + Form.serialize($('login-form'))
				,onComplete: onComplete
				,asynchronous: true
			});
	},

	disconnect: function()
	{
		new Ajax.Request('login.php', { parameters: 'AZIONE=disconnect', asynchronous: false })
	},

	observe: function()
	{
		var f = function() {
			var autologin = function(event) { 
				if (event.keyCode == 13) {
					this.login(); 
					event.stop();
				}
			};
			$('login-form').observe('keydown', autologin.bindAsEventListener(this));
			$('username').focus();
		};
		f.bind(this).defer();
	},


	checkRegistration: function (onOk)
	{
		var today = new Date();
		if ($('birth')) {
			var born  = $F('birth').split('/');
			born = new Date(born[2], born[1] - 1, born[0]);

			// check data di nascita
			if ($F('pwd1') != $F('pwd2')) {
				Ubk.error(Locale.string(3003));
			} else if ($('ok-condition') && $F('ok-condition') == null) {
				Ubk.error(Locale.string(3004));
			} else if ($('ok-privacy') && $F('ok-privacy') == null) {
				Ubk.error(Locale.string(3005));
			} else if (today.getFullYear() - born.getFullYear() < 13) {
				Ubk.error(Locale.string(3006));
			} else if (today.getFullYear() - born.getFullYear() == 13 && today.getMonth() < born.getMonth()) {
				Ubk.error(Locale.string(3006));
			} else if (today.getFullYear() - born.getFullYear() == 13 && today.getMonth() == born.getMonth() && today.getDate() < born.getDate()) {
				Ubk.error(Locale.string(3006));
			} else {
				Ubk.tryThis(onOk);
			}
		} else {
			Ubk.tryThis(onOk);
		}
	},


 	lostPassword: function()
	{
		var email = prompt(Locale.string(4233));
		if (email == null) {
			return;
		} else if (email == '') {
			Ubk.error(Locale.string('CHK-EMAIL'));
		} else if (Fld.Check.mail({ value: email, focus: Prototype.K })) {
			Ubk.follow(null, 'users.php', 'AZIONE=lost_password&EMAIL='+email, false, true);
		}
	}
});

var CUserTopic = Class.create({
	toggleIgnore: function(check, topic)
	{
		var checked = (check.src.indexOf('SI.png') != -1);
		var cont = check.up(1);
		var ccont = '.topic-btn'+(cont.hasClassName('top') ? '.bot' : '.top');
		var ocont = cont.up().select(ccont)[0];
	
		var onComplete = function(request) {
			Ubk.working(false);
			if (checked) {
				check.src = 'img/ico/check/checkNO.png';
			} else {
				check.src = 'img/ico/check/checkSI.png';
			}
	
			Element.toggle(check.next());
			Element.toggle(check.next(1));
	
			var notify = ocont.select('.notify');
			notify.each(function(e) { 
				e.src = check.src;
				Element.toggle(e.next());
				Element.toggle(e.next(1));
			});
		}
		Ubk.follow(null, 'forum.php', 'AZIONE=toggle_notify&TABELLA=t_p_user_topic&TOPIC=' + topic + '&BIT=' + (checked ? '0' : '1'), false, true, onComplete);
	},
	bmkSync: function(topic)
	{
		var bot = $('bmk_topic_'+topic+'_bot');
		if (bot != null) {
			var top = $('bmk_topic_'+topic+'_top');
			bot.update(top.innerHTML);
		}
	}
});

var CUserCloud = Class.create({
	show: function(target, cloud, async, param)
	{
		var onComplete = function(request) {
			if (Ubk.isFailure(request)) {
				return;
			} else if (request.responseText.length > 0) {
				$(target).insert({bottom: request.responseText});
/*				if (target == 'user-groups') {
					var l = $(target).childElements();
					l[l.length - 1].toggle();
				}*/
			}
		};

		pars = 'STREAM=user-'+cloud;
		if (param) pars += '&CLAN='+param;
		Ubk.follow(null, 'system/cron/clouds.php', pars, true, async, onComplete);
	},
	popUp: function(cloud, async, param)
	{
		if ($('user-clan-'+param)) return;
		var onComplete = function(request) {
			if (Ubk.isFailure(request)) {
				return;
			} else if (request.responseText.length > 0) {
				document.body.insert({bottom: request.responseText});
				var fs = $(request.responseXML.documentElement.getAttribute('id'));
				fs.down('legend').writeAttribute('onclick', 'Element.remove(\''+fs.id+'\'); Draggables.drags.each(function(d){if (d.id == \''+fs.id+'\') d.destroy();});');
				var view = document.viewport.getDimensions();
				fs.setStyle({ width: Math.round(view.width / 3 * 2) + 'px' });
				Ubk.center(fs);
				new Draggable(fs);
			}
		};

		pars = 'STREAM=user-'+cloud;
		if (param) pars += '&CLAN='+param;
		Ubk.follow(null, 'system/cron/clouds.php', pars, true, async, onComplete);
	},
	toggle: function(legend)
	{
		$(legend).siblings().each(function(e) {
			new Effect.toggle(e, 'blind', { duration: 0.2 });
		});
	}
});

// gestione dal profilo
var CUserForumBmk = Class.create({
	moveUp: function(id, forum)
	{
		var move = function(block) {
			var prev = block.previous();
			prev.up().removeChild(block);
			prev.up().insertBefore(block, prev);
		};
		move($('pfbmk_'+id));
		move($('fbmk_'+forum));
	},
	moveDown: function(id, forum) {
		var move = function(block) {
			var next = block.next(1);
			if (next) {
				next.up().removeChild(block);
				next.up().insertBefore(block, next);
			} else {
				next = block.up();
				block.up().removeChild(block);
				next.appendChild(block);
			}
		};

		move($('pfbmk_'+id));
		move($('fbmk_'+forum));
	},
	up: function(forum)
	{
		Ubk.follow(null, 'users.php', 'AZIONE=bmk_forum_up&ID='+forum, false, true);
	},
	down: function(forum)
	{
		Ubk.follow(null, 'users.php', 'AZIONE=bmk_forum_down&ID='+forum, false, true);
	},

	add: function()
	{
		var onComplete = function(request) {
			Ubk.working(false);
			this.addElement($F('i_forum_id'));
			Ubk.followLink('user-dtl-forums');	// ricarico l'elenco
		};

		Ubk.follow(null, 
			'users.php', 
			'AZIONE=bmk_forum_add&TABELLA=t_s_user_forum_bmk&FORUM='+$F('i_forum_id'),
			false, true, onComplete.bind(this));

	},

	remove: function(id, forum)
	{
		var onOk = function() {
			var onComplete = function(request) {
				Ubk.working(false);
				this.removeElement(forum);
				$('pfbmk_'+id).remove();	// rimuovo la riga
			};
	
			Ubk.follow(null, 
				'general.php', 
				'AZIONE=elimina&TABELLA=t_s_user_forum_bmk&ID='+id,
				false, true, onComplete.bind(this));
		};
		Ubk.confirm(Locale.string('CONF-DELETE'), onOk.bind(this));

	},

	addElement: function(forum)
	{
		var onComplete = function(request) {
				Ubk.working(false);
				$('fbmks').insert({bottom: request.responseText});
			};
		Ubk.follow(null, 
			'general.php', 
			'AZIONE=mostra_riga&TABELLA=t_a_forum&ID='+forum+'&FORUM='+forum+'&FILE=hp/user/links/forum-bmk.xml',
			false, true, onComplete);
	
	},

	removeElement: function(forum)
	{
		$('fbmk_'+forum).remove();
	}
});

var CUserForum = Class.create({
	initialize: function() {
		this.Bmk = new CUserForumBmk();
	},
	// dalla home di un forum
	setHome: function(forum)
	{
		Ubk.confirm(Locale.string(3036), function() {
			var onComplete = function() {
					Ubk.working(false);
					$('user-home').toggle();
					$('user-home').next().toggle();
				};
			Ubk.follow(null, 'users.php', 'AZIONE=set_hp&FORUM='+forum, false, true, onComplete);
		});
	},

	toggleIgnore: function(check, forum)
	{
		var onComplete = function() {
			Ubk.working(false);
			if (check.src.indexOf('SI.png') != -1) {
				check.src = 'img/ico/check/checkNO.png';
			} else {
				check.src = 'img/ico/check/checkSI.png';
			}
		}
		Ubk.follow(null, 'forum.php', 'AZIONE=toggle_ignore&TABELLA=t_p_user_forum_ignore&FORUM=' + forum, false, true, onComplete);
	},

	toggleIgnoreFeed: function(check, forum)
	{
		var checked = (check.src.indexOf('SI.png') != -1);
	
		var onComplete = function(request) {
			Ubk.working(false);
			if (checked) {
				check.src = 'img/ico/check/checkNO.png';
			} else {
				check.src = 'img/ico/check/checkSI.png';
			}
	
			Element.toggle(check.next());
			Element.toggle(check.next(1));
		}
		Ubk.follow(null, 'forum.php', 'AZIONE=toggle_ignore&TABELLA=t_p_user_forum_ignore&FORUM=' + forum, false, true, onComplete);
	},

	// switch ignore ricorsivo su profilo
	toggleIgnoreTree: function(check, forum)
	{
		var onComplete = function() {
			if (check.src.indexOf('SI.png') != -1) {
				check.src = 'img/ico/check/checkNO.png';
			} else {
				check.src = 'img/ico/check/checkSI.png';
			}
			Ubk.follow('tab', 'forum.php', 'AZIONE=mostra_attuale&TABELLA=t_a_forum&FILE=hp/user/details/forums.xml', true, true, null);
		};
		Ubk.follow(null, 'forum.php', 'AZIONE=toggle_ignore&TABELLA=t_p_user_forum_ignore&FORUM=' + forum, false, false, onComplete);
	}
});

var CUserUpdaters = Class.create({
	initialize: function()
	{
		this.doBlink = false;

		this.tick = 20;
		this.blinks = 4;
		this.delay = 1;

		this.duration = ((this.tick - (this.delay * this.blinks)) / this.blinks) / 2;
	},
	online: function()
	{
		var options = {
				method: 'get'
				,asynchronous: true
				,frequency: this.tick
				,decay: 1
				,parameters: 'AZIONE=mostra&MODE=W&FILE=hp/user/online.xml&PAGE-SIZE=0'
		}
		new Ajax.PeriodicalUpdater('online-now', 'users.php', options );

		return this;
	},

	blinkSetup: function(el, title)
	{
		var sk = 'blink-' + el;
		
		if (!$(el).hasAttribute('baseColor'))
			$(el).writeAttribute('baseColor', $(el).getStyle('color'));

		Effect.Queues.get(sk).each(function(effect) {
			effect.cancel();
			if (title) {
	 			effect.element.setStyle({color: effect.element.readAttribute('baseColor')});
			} else {
				effect.element.setStyle({opacity: 1});
			}
		});

		return sk;
	},
 
	blinkTitle: function(el, status)
	{
		var sk = this.blinkSetup(el, true);

		if (status) {
			var oc = $(el).readAttribute('baseColor');

			for(i = 0; i < this.blinks; i++) {
				new Effect.Morph(el, {
					style: { color: $(el).next('.voices').getStyle('background-color') }
					, duration: this.duration
					, queue: { position: 'end', scope: sk }
					, delay: (i ? this.delay : 0)
				});
				new Effect.Morph(el, {
					style: { color: oc }
					, duration: this.duration
					, queue: { position: 'end', scope: sk }
				});
			}
		}
	},
 
	blink: function(el, status)
	{
		var sk = this.blinkSetup(el, false);
		var vcs = $(el).up('.voices');
		
		if (status) {
			var oc = $(el).readAttribute('baseColor');

			$(el).writeAttribute('blinking');
			for(i = 0; i < this.blinks; i++) {
				new Effect.Opacity(el, {
					from: 1
					, to: 0.4
					, duration: this.duration
					, queue: { position: 'end', scope: sk }
					, delay: (i ? this.delay : 0)
				});
				new Effect.Opacity(el, {
					to: 1
					, from: 0.4
					, duration: this.duration
					, queue: { position: 'end', scope: sk }
				});
			}
		} else {
			$(el).removeAttribute('blinking');
		}
	},
 
	counters: function(parts)
	{
		var updaters = this;
		var update = function(options) {
			new Ajax.Request('users.php', options);
		};
		var onComplete = function(request, JSON) {
			try {
				var o = request.responseText.evalJSON(true);
				// voci
				for(var p in parts) {
					if (o[p]) {
						$(parts[p]).update(o[p]);
						if (updaters.doBlink) {
							if (o[p+'-blink'] && o[p+'-blink'] == 'on') updaters.blink(parts[p], true);
							if (o[p+'-blink'] && o[p+'-blink'] == 'off') updaters.blink(parts[p], false);
						}
					}
				}
				// titoli
				if (updaters.doBlink) {
					for(var p in parts) {
						if (o[p]) {
							var vcs = $(parts[p]).up('.voices');
							var blinks = vcs.select('*[blinking]').length;
							updaters.blinkTitle(vcs.previous().identify(), (blinks > 0));
						}
					}
				}
			} catch(e) { }

			this.delay(updaters.tick, options);
		};

		var options = {
				method: 'get'
				,asynchronous: true
				,parameters: 'AZIONE=get_num&TABELLA=t_a_user&WHAT='
				,onComplete: onComplete.bind(update)
		};
	
		var counters = [];
		for(var p in parts)
			if ($(parts[p])) counters.push(p);

		if (counters.length) {
			options.parameters += counters.join('|');
			update(options);
		}

		return this;
	},
	
	observe: function() 
	{
		var f = function() {
			this.online();
			this.counters(
				{
					pm: 'user-inbox'
					, 'new': 'user-new'
					, signaled: 'user-signaled'
					, gaming: 'user-gaming'
					, surfing: 'users-surfing'
					, playing: 'users-playing'
				}
			);
		};
		f.bind(this).defer();
	},

 	observeGuest: function()
	{
		var f = function() {
			this.online();
			this.counters(
				{
					surfing: 'users-surfing'
					, playing: 'users-playing'
				}
			);
		};
		f.bind(this).defer();
	}
});

var CUser = Class.create({
	initialize: function() {
		
		this.Menu = new CUserMenu;

		this.Login = new CUserLogin;
		this.Updaters = new CUserUpdaters;

		this.Topic = new CUserTopic;
		this.Forum = new CUserForum;
		this.Feed = new CUserFeed;

		this.Cloud = new CUserCloud;

		Event.observe(window, 'onunload', this.disconnect);
	},

	profile: function(user)
	{
		Ubk.follow('content', 'users.php', 'AZIONE=mostra_riga&ID='+user+'&FILE=hp/user/user.xml&MODE=RW', true, true, null);
	},

	setHome: function(page)
	{
		Ubk.confirm(Locale.string(3036), function() {
			var onComplete = function() {
					Ubk.working(false);
					$('user-home').toggle();
					$('user-home').next().toggle();
				};
			if (page == 'recent')
				page += '.'+$F('recent-days');
			Ubk.follow(null, 'users.php', 'AZIONE=set_hp&PAGE='+page, false, true, onComplete);
		});
	},

	goHome: function()
	{
		var onComplete = function(request) {
				Ubk.working(false);
				eval(request.responseText);
			};
		Ubk.follow(null, 'users.php', 'AZIONE=get_hp', false, true, onComplete);
	}
});