// --------------------------------------------------------
// ridefinizione metodi Ubk

CUbkHistory.addMethods({
	isValidTarget: function (target) {
		return ['content', 'forumcontent'].include(target);
	}
});

CUbk.addMethods({
	setup: function() {
		$('working').setOpacity(0.65);
		// box di conferma
		var confirm = $('confirm');
		this.confirmBox = {
			box: confirm
			,msg: confirm.select('.question').reduce()
			,ok: confirm.select('.ok').reduce()
			,canc:confirm.select('.cancel').reduce()
		};
		// su opera lo fa sdare malamente
/*		if (!Prototype.Browser.Opera)
			new Draggable(this.confirmBox.box, {
				handle: 'btn'
				,zindex: 1201
				,onStart: function(d, evt) { d.element.setStyle({ cursor: 'move' }); }
				,onEnd: function(d, evt) { d.element.setStyle({ cursor: 'default' }); }
				,starteffect: null
				,endeffect: null
			});*/
		// box di errore
		var err = $('error');
		this.errorBox = {
			box: err
			,msg: err.select('.message').reduce()
			,ok: err.select('.ok').reduce()
		};
		// box di info
		var info = $('info');
		this.infoBox = {
			box: info
			,msg: info.select('.message').reduce()
			,ok: info.select('.ok').reduce()
		};
		// dimensioni wait
		var wait = $('wait');
		this.wait = {
			img: wait
			,dim: wait.getDimensions()
			,position: function(target) {
// 				target = $(target);
// 				var pos = target.cumulativeOffset();
// 				var dim = target.getDimensions();
//				var scroll = document.body.cumulativeScrollOffset();
// 				Ubk.wait.img.setStyle({ 
// //					top: ((dim.height - Ubk.wait.dim.height) / 2 + pos.top + scroll.top) + 'px'
// //					,left: ((dim.width - Ubk.wait.dim.width) / 2 + scroll.left) + 'px'
// 					top: ((dim.height - Ubk.wait.dim.height) / 2 + pos.top) + 'px'
// 					,left: ((dim.width - Ubk.wait.dim.width) / 2 + pos.left) + 'px'
// 				});
			}
			,show: function(target) {
				var dim = $(target).getDimensions();
				var disp = $(target).getStyle('display');
				if ((dim.height == 0 && dim.width == 0) || (disp == 'none')) return;

				Ubk.wait.position(target);
				Ubk.wait.img.show();
			}
			,hide: function() {
				Ubk.wait.img.hide();
			}
		};

		this.currentBox = null;
		Event.observe(document, 'keydown', this.hideBox.bindAsEventListener(this));
		
		// observers su box
		[this.confirmBox.ok, this.confirmBox.canc, this.errorBox.ok, this.infoBox.ok]
			.invoke('observe','mouseover',Observer.over)
			.invoke('observe','mouseout',Observer.out);
	},

	isVisible: function (target) {
		if (!$(target)) return false;
		if ($(target).readAttribute('hidden')) return false;
		var dim = $(target).getDimensions();
		var disp = $(target).getStyle('display');
	
		return (!((dim.height == 0 && dim.width == 0) || (disp == 'none')));
	},

	hideDraggables: function()
	{
		var hide = function(e){this.hide(e.id);};
		Draggables.drags.each(hide.bind(this));
	},

	center: function(target)
	{
		target = $(target);
		var td = target.getDimensions();
		var scroll = document.body.cumulativeScrollOffset();
		var view = document.viewport.getDimensions();
		target.setStyle({ 
			top: ((view.height - td.height) / 4 + scroll.top) + 'px'
			,left: ((view.width - td.width) / 2 + scroll.left) + 'px'
		});
	},

	confirm: function(message, onOk, onCancel)
	{
		this.confirmBox.msg.update(message.replace(/\n/, '<br/>'));
		this.confirmBox.ok.onclick = this.hide.curry('confirm', onOk).bind(this);
		this.confirmBox.canc.onclick = this.hide.curry('confirm', onCancel).bind(this);

		this.show('confirm');
	},

	error: function(message, onOk)
	{
		this.errorBox.msg.update(message.replace(/\n/, '<br/>'));
		this.errorBox.ok.onclick = this.hide.curry('error', onOk).bind(this);

		this.show('error');
	},

	alert: function(message)
	{
		this.infoBox.msg.update(message.replace(/\n/, '<br/>'));
		this.infoBox.ok.onclick = this.hide.curry('info').bind(this);

		this.show('info');
	},

	hide: function (target, afterFinish)
	{

		if (!$(target)) { return; }

		if (!this.isVisible(target)) { 
			this.tryThis(afterFinish);
			return;
		}

		var setHidden = function() {
			$(target).writeAttribute('hidden');
			Ubk.tryThis(afterFinish);
		};	

		switch(target)	{
		case 'content':
			this.wait.show(target);
			this.hideDraggables();
		case 'search-result':
			this.wait.show(target);
			Element.setOpacity(target, 0.2);
			setHidden.call();
			// new Effect.Fade(target, {duration: 0.2, from: 1, to: 0.2, afterFinish: setHidden, queue: {position: 'end', scope: target}});
			break;
		case 'forumcontent':
		case 'topiclist':
		case 'posts':
		case 'pms':
			this.wait.show(target);
			this.hideDraggables();
			new Effect.Fade(target, {from: 1.0, to:0.4, duration: 0.2, afterFinish: setHidden });
			break;
		case 'tab':
		case 'mdtl':
			this.wait.show(target);
			this.hideDraggables();
			new Effect.Fade(target, {duration: 0.2, afterFinish: afterFinish, queue: {position: 'end', scope: target}});
			break;
		case 'server-dtl':
			new Effect.BlindUp(target, {duration: 0.2, afterFinish: afterFinish, queue: {position: 'end', scope: target}});
			break;
		case 'confirm':
		case 'error':
		case 'info':
			this.currentBox = null;
		case 'pm':
		case 'moderation':
			var aft = function() {
				this.hide('working');
				setHidden.call();
			};
			new Effect.Fade(target, {duration: 0.2, afterFinish: aft.bind(this)});
			break;
		case 'emoticons':
			new Effect.Fade(target, {duration: 0.2, afterFinish: setHidden });
			break;
		default:
			Element.hide(target);
			this.tryThis(afterFinish);
			break;
		}
	},

	show: function (target, afterFinish)
	{
		this.wait.hide();

		if (!$(target)) return;

		if (this.isVisible(target)) {
			this.tryThis(afterFinish);
			return;
		}
	
		if ($(target).id.indexOf('feed_') == 0) {
			new Effect.Appear(target, {duration: 0.2});
			return;
		}

		var unsetHidden = function() {
			$(target).removeAttribute('hidden');
			Ubk.tryThis(afterFinish);
		};
	
		switch(target)	{
		case 'content':
		case 'search-result':
			Element.setOpacity(target, 1);
			unsetHidden.call();
//			new Effect.Appear(target, {duration: 0.2, from: 0.2, to: 1, queue: {position: 'end', scope: target}, afterFinish: unsetHidden } );
			break;
		case 'forumcontent':
		case 'topiclist':
		case 'posts':
		case 'pms':
			var aft = function() {
				$(target).writeAttribute('hidden');
				if (this.isVisible('new_post')) {
					Element.scrollTo('new_post');
				} else {
					Element.scrollTo(target);
				}
				this.tryThis(unsetHidden);
			};
			new Effect.Appear(target, {from: 0.4, to:1.0, duration: 0.2, afterFinish: aft.bind(this)});
			break;
		case 'tab':
		case 'mdtl':
			this.wait.show(target);
			new Effect.Appear(target, {duration: 0.2, queue: {position: 'end', scope: target}, afterFinish: function() {
				Ubk.tryThis(afterFinish);
				Element.scrollTo(target);
			}} );
			break;
		case 'server-dtl':
			new Effect.BlindDown(target, {duration: 0.2, queue: {position: 'end', scope: target}, afterFinish: afterFinish});
			break;

		case 'working':
			Element.setStyle('working', { 
				height: Math.max(document.body.getHeight(), document.viewport.getHeight()) + 'px'
			});
			Element.show('working');
			this.tryThis(afterFinish);
			break;
		case 'confirm':
		case 'error':
		case 'info':
			this.currentBox = this[target + 'Box'];
		case 'pm':
		case 'moderation':
// 			this.center(target);
			this.show('working', function() {
				new Effect.Appear(target, {duration: 0.2, afterFinish: unsetHidden});
			});
			break;
		case 'emoticons':
			new Effect.Appear(target, {duration: 0.2, afterFinish: unsetHidden});
			break;
		default:
			Element.show(target);
			this.tryThis(afterFinish);
			break;
		}
	},
 	hideBox: function(event) {
		if (this.currentBox != null) {
			switch(event.keyCode) {
			case 13:
			case 32:
				this.currentBox.ok.onclick.call();
				break;
			case 27:
				if (this.currentBox.canc)
					this.currentBox.canc.onclick.call();
				else
					this.currentBox.ok.onclick.call();
			}
		}
	}
});


// --------------------------------------------------------
// Risultati ricerca

var CSearch = Class.create({
	initialize: function() {
	},

	toggleResult: function()
	{
		var me = $('toggle_all');
		var lns = $('search-result').select('.'+me.className).each(Ubk.followLink);
	
		if (me.className == 'open') {
			me.className = 'close';
			me.title = Locale.string(347);
		} else {
			me.className = 'open';
			me.title = Locale.string(356);
		}

	},

	toggleForum: function (forum, source)
	{
		var link = $('toggle_' + forum);
		var result = $('result_' + forum);
	
		if (link.className == 'close') {
			link.className = 'open';
			link.title = Locale.string(356);
			new Effect.toggle(result, 'blind', {duration: 0.2});
		} else {
			link.className = 'close';
			link.title = Locale.string(347);
			if (result.readAttribute('loaded')) {
				new Effect.toggle(result, 'blind', {duration: 0.2});
			} else {
				var fToggle = function() {
					result.writeAttribute('loaded');
					new Effect.toggle(result, 'blind', {duration: 0.2});
				};
				Ubk.follow(result.id, 'general.php', 'AZIONE=mostra_riga&TABELLA=t_a_forum&ID='+forum+'&FILE=hp/search/result-topics.xml&GROUPING=G&SOURCE='+source, true, false, fToggle);
			}
		}
	},

	noTopic: function()
	{
		$('search-result').update('<span class="EOF">' + Locale.string(515) + '</span>');
	},

				
	readAll: function(user)
	{
		var onOk = function() {
			var onComplete = function() { 
				Ubk.working(false); 
				this.noTopic();
				Element.hide('toggle_all');
				Element.hide('read_all');
			};
			Ubk.follow(null, 'general.php', 'AZIONE=esegui_stored_procedure&NOME-STORED=user_read_all&PARAMETRO-0='+user, false, true, onComplete.bind(this));
		};
		Ubk.confirm(Locale.string(3029), onOk.bind(this));
	},

	readForum: function(user, forum)
	{
		var onOk = function() {
			var onComplete = function() { 
				Ubk.working(false); 
				Element.remove('list_forum_'+forum); 
			};
			Ubk.follow(null, 'general.php', 'AZIONE=esegui_stored_procedure&NOME-STORED=forum_read&PARAMETRO-0='+user+'&PARAMETRO-1='+forum, false, true, onComplete.bind(this));
		};
		Ubk.confirm(Locale.string(3030), onOk.bind(this));
	},

	readTopic: function(user, topic)
	{
		var onOk = function() {
			var onComplete = function() { 
				var target = 'topic_'+topic;
				var mid = $(target).up();
				Ubk.working(false);
				Element.remove(target); 
				// se non ho questo elemento, vuol dire che sono in modalita' raggruppata
				// non e' bellissimo ma x ora va bene
				if ($('result') == null) {
					// se rimane solo il clear dentro mid, rimuovo tutto il forum
					if (mid.childNodes.length == 1)
						Element.remove(mid.up(1));
				} else if (mid.childNodes.length == 0) {
					this.noTopic();
				}
			};
			Ubk.follow(null, 'general.php', 'AZIONE=esegui_stored_procedure&NOME-STORED=topic_read&PARAMETRO-0='+user+'&PARAMETRO-1='+topic, false, true, onComplete.bind(this));
		};
		Ubk.confirm(Locale.string(3031), onOk.bind(this));
	}

});

// --------------------------------------------------------
// logo roll

var CLogo = Class.create({
	initialize: function() {
		this.running = false;
	},
	roll0: function() {
		frame1 = function() { $('h1').innerHTML = $('h1').innerHTML.replace(/oo/g, 'OO') } ;
		frame2 = function() { $('h1').innerHTML = $('h1').innerHTML.replace(/OO/g, 'oo') } ;
		
		frame1();
		frame2.delay(1);
		frame1.delay(2);
		frame2.delay(3);
	},

	roll1: function()
	{
		frame1 = function() { $('h1').innerHTML = $('h1').innerHTML.replace(/:\./g, ';)') } ;
		frame2 = function() { $('h1').innerHTML = $('h1').innerHTML.replace(/;\)/g, ':.') } ;
	
		frame1();
		frame2.delay(2);
	},


	roll2: function ()
	{
		frame1 = function() { $('h1').innerHTML = $('h1').innerHTML.replace(/:\./g, ':[').replace(/\.:/g, ']:') } ;
		frame2 = function() { $('h1').innerHTML = $('h1').innerHTML.replace(/:\[/g, ':.').replace(/\]:/g, '.:') } ;
	
		frame1();
		frame2.delay(2);
	},
	
	roll3: function()
	{
		frame1 = function() { $('h1').innerHTML = $('h1').innerHTML.replace(/zoo/g, 'Zzo') } ;
		frame2 = function() { $('h1').innerHTML = $('h1').innerHTML.replace(/Zzo/g, 'Zzz') } ;
		frame3 = function() { $('h1').innerHTML = $('h1').innerHTML.replace(/Zzz/g, 'Zzzz') } ;
		frame4 = function() { $('h1').innerHTML = $('h1').innerHTML.replace(/Zzzz/g, 'Zzz') } ;
		frame5 = function() { $('h1').innerHTML = $('h1').innerHTML.replace(/Zzz/g, 'Zzo') } ;
		frame6 = function() { $('h1').innerHTML = $('h1').innerHTML.replace(/Zzo/g, 'zoo') } ;
	
		frame1();
		frame2.delay(1);
		frame3.delay(2);
		frame4.delay(3);
		frame5.delay(4);
		frame6.delay(5);
	},
	
	roll: function()
	{
		if (this.running) {
			var idx = Math.round( Math.random() * 100 ) % 3;
			this['roll'+ rest].delay(10);
			this.roll.delay(10);
		}
	},
	
	stop: function() {
		this.running = false;
	},

	start: function() {
		this.running = true;
		this.roll();
	}
});

// ----------------------------------------------------
// sincronizzazione titolo finestra

var CTitle = Class.create({
	initialize: function() {
		this.synchronizer = this.first = null;
	}

	,sync: function()
	{
		if (this.first == null)
			this.first = $$('head title').reduce().textContent;
	
		var titles = $$('h2');
		if (titles.length) {
			document.title = this.first + ' - ' + titles.pluck('textContent').join(' ');
		} else {
			document.title = this.first;
		}
	},

	watch: function()
	{
		if (!this.synchronizer) {
			this.synchronizer = new PeriodicalExecuter(this.sync, 0.5);
		}
	},

	stopWatching: function()
	{
		if (this.synchronizer) {
			this.synchronizer.stop();
			this.synchronizer = null;
		}
	}
});

// ----------------------------------------------------
// hide paginator target

var CPaginatorFrontEnd = Class.create({
	hideTarget: function(event, paginator, target)
	{
		var ancestors = paginator.ancestors();
		if (target == 'pms') {
			Ubk.hide(target);
		} else if (Event.element(event).tagName.toLowerCase() != 'a'
			|| ancestors.include('mdtl')
			|| ancestors.include('tab')
			|| ancestors.include('search-result')
			) {
			return;
		} else if (['posts', 'topiclist', 'forumcontent', 'content'].include(target)) {
			Ubk.hide(target);
		}
	}
});

// ----------------------------------------------------
// tips

var CTips = Class.create({
	initialize: function(lang)
	{
		this.index = null;	// random by server
		this.count = null;	// non sappiamo quanti sono
		this.lang  = lang;
		this.cookie_name = "pddbbs_tips";
// 		Event.observe(document, 'dom:loaded', this.setup.bindAsEventListener(this));
		this.setup();
	},
	setup: function()
	{
		this.container = $('tips');
		this.executer = null;
		this.load(false);
	},
 	time_run: function()
	{
		var check = function()
		{
			var c   = Cookie.get(this.cookie_name);
			var now = new Date();
			var value = [now.getFullYear(), now.getMonth() + 1, now.getDate()].join('');
			// prima delle 12 nn faccio niente
			if (now.getHours() < 12)
				return;
			// dopo le dodici: se non l'ho ancora mostrato di oggi, lo mostro
			if (c == null || c < value) {
				this.load(false);
				Cookie.set(this.cookie_name, value, 1);
			}
			// e poi chiudo
			this.executer.stop();
		};
		this.executer = new PeriodicalExecuter(check.bind(this), 5 * 60);	// ogni 5 minuti
	},
	previous: function()
	{
		if (this.index != null) {
			if (--this.index < 0) this.index = this.count - 1;
			this.load(true);
		}
	},
	next: function()
	{
		if (this.index != null) {
			if (++this.index >= this.count) this.index = 0;
			this.load(true);
		}
	},
	load: function(force)
	{
		var onComplete = function(request) {
			var json = request.responseText.evalJSON(true);
			if (json == null) {
				Ubk.hide(this.container.id);
			} else {
				this.index = json.index;
				this.count = json.count;
				this.container.down('.subject').update(json.subject);
				this.container.down('.message').update(json.body);
				Ubk.show(this.container.id);
			}
		};
		var pars = 'AZIONE=get_tip&LANG='+this.lang+'&FORCE=' + (force ? 'TRUE' : 'FALSE');
		if (this.index != null) 
			pars += '&NUMERO=' + this.index ;

		Ubk.follow(null, 'general.php', pars, false, true, onComplete.bind(this));
	}
});