
// Define all objects
var Tools, Dropdowns, Lang, Report, BattleExtension, BackCounter, User;

//############################################################################
//# Basic element methods
//############################################################################
Element.implement({
	hide: function(){this.setStyle('display','none');return this},
	show: function(){this.setStyle('display','block');return this},
	disable: function(){this.set('disabled','disabled');return this},
	enable: function(){this.removeProperty('disabled');return this},
	value: function(value){if(value)this.set('value',value);return this.get('value')}
});

//############################################################################
//# Tools
//############################################################################
Tools = {
	trim: function(str) {
		return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
	}
}

//############################################################################
//# Dropdowns
//############################################################################
Dropdowns = {
	init: function() {
		window.addEvent('domready', function(){
			$(document).addEvent('click',function(e) {
				$$('.dropdown-toggle, .menu').getParent("li").removeClass("open");
			});
			Dropdowns.bind();
		});
	},
	reinit: function() {
		$$(".dropdown-toggle, .menu").removeEvents('click');
		Dropdowns.bind();
	},
	bind: function() {
		$$(".dropdown-toggle, .menu").addEvent('click', function(e) {
			e.preventDefault();
			var has_class = this.getParent("li").hasClass("open");
			$$('.dropdown-toggle, .menu').getParent("li").removeClass("open");
			if( ! has_class) this.getParent("li").addClass("open");
			e.stopPropagation();
		});
	}
};

//############################################################################
//# Lang
//############################################################################
Lang = {
	numForm: function(n, forms) {
		return n%10==1&&n%100!=11?forms[0]:(n%10>=2&&n%10<=4&&(n%100<10||n%100>=20)?forms[1]:forms[2]);
	}
}

//############################################################################
//# Battle
//############################################################################
Battle = new Class({
	// Options
	selected: 1,
	onPopupClose: function() {},
	
	// Class initalisation
	initialize: function(options) {
		Object.append(this, options);
	},
	
	// Open popup
	initPopup: function(title, selection) {
		this.selected = selection;
		this.popup = new LightFace.Static({
			title: title,
			content: 'vote-options'
		});
	},
	
	// Vote
	vote: function(social_network) {
		var share = this.selected == 1 ? this.share1 : this.share2;
		var pic   = this.selected == 1 ? this.pic1   : this.pic2;
		var url   = '';
		
		if(social_network == 'fb') {
			url  = 'http://www.facebook.com/sharer.php?s=100';
			url += '&p[title]='     + encodeURIComponent(this.text);
			url += '&p[summary]='   + encodeURIComponent(share);
			url += '&p[url]='       + encodeURIComponent(this.url);
			url += '&p[images][0]=' + encodeURIComponent(pic);
		} else if(social_network == 'tw') {
			url  = 'http://twitter.com/share?';
			url += 'text='      + encodeURIComponent(this.text);
			url += '&url='      + encodeURIComponent(this.url);
			url += '&counturl=' + encodeURIComponent(this.url);
		} else if(social_network == 'vk') {
			url  = 'http://vkontakte.ru/share.php?';
			url += 'url='          + encodeURIComponent(this.url);
			url += '&title='       + encodeURIComponent(this.text);
			url += '&description=' + encodeURIComponent(share);
			url += '&image='       + encodeURIComponent(pic);
			url += '&noparse=true';
		} else if(social_network == 'ok') {
			url  = 'http://www.odnoklassniki.ru/dk?st.cmd=addShare&st.s=1';
			url += '&st.comments=' + encodeURIComponent(share);
			url += '&st._surl='    + encodeURIComponent(this.url);
		} else if(social_network == 'ml') {
			url  = 'http://connect.mail.ru/share?';
			url += 'url='          + encodeURIComponent(this.url);
			url += '&title='       + encodeURIComponent(this.text);
			url += '&description=' + encodeURIComponent(share);
			url += '&imageurl='    + encodeURIComponent(pic);
		}

		window.open(url,'','toolbar=0,status=0,width=626,height=436');
		
		return this.vote_ns()
	},
	
	// Vote count
	vote_ns: function() {
		new Request({
			url: '/vote/' + this.id + '/' + this.selected
		}).send();

		this.popup.close();
		this.onPopupClose.delay(400);

		var vote_count = $('vote-num-'+this.selected);
		vote_count.set('text', vote_count.get('text').toInt() + 1);

		$('vote-1').destroy();
		$('vote-2').destroy();
		$('voted_thank_you').show();

		return false
	},
	
	// Askbook Promo
	promoAskbook: function() {
		this.promoBox = new LightFace.Static({
			width:     500,
			draggable: true,
			title:     'AskBook.me',
			content:   'askbook_promo'
		});
	}

});

//############################################################################
//# Report
//############################################################################
Report = {
	open: function(title, battle_id) {
		this.popup = new LightFace.Request({
			url: '/battle/report/index/' + battle_id,
			title: title
		}).open();
		return false
	},
	close: function() {
		this.popup.close();
		return false;
	},
	submit: function() {
		if( ! Tools.trim($('report_text').get('value'))) return false;
		new Request({
			url:  $('report-form').get('action'),
			data: $('report-form').toQueryString(),
			onRequest: function() {
				$('report_text').disable();
				$('report_submit').disable();
				$('report_cancel').hide();
				$('report_loader').show();
				Report.popup.disable();
			},
			onSuccess: function() {
				Report.popup.enable();
				$('report-form').hide();
				$('report-success').show();
				setTimeout(function(){ Report.close() }, 3000)
			}
		}).send();
		return false;
	}
};

//############################################################################
//# BattleExtension
//############################################################################
BattleExtension = {
	open: function(title, battle_id) {
		this.popup = new LightFace.Request({
			url: '/battle/extend/index/' + battle_id,
			title: title
		}).open();
		return false
	},
	close: function() {
		this.popup.close();
		return false;
	},
	confirm: function(battle_id) {
		new Request({
			url: '/battle/extend/confirm/' + battle_id,
			onRequest: function() {
				$('extend_confirm').disable();
				$('extend_cancel').hide();
				$('extend_loader').show();
				BattleExtension.popup.disable();
			},
			onSuccess: function() {
				BattleExtension.popup.enable();
				$('extend_form').hide();
				$('extend_success').show();
				window.location.reload(true)
			}
		}).send();
		return false;
	}
};

//############################################################################
//# Counter
//############################################################################
BackCounter = new Class({
	Implements: [Options, Events],
	options: {
		update: 1000,
		big_format:   "{D} {H} {M} {S}",
		small_format: "<span class='number'>{number}</span> <span class='word'>{word}</span>",
		lang: {
			d: { 0: "Day",    1: "Days",    2: "Days"    },
			h: { 0: "Hour",   1: "Hours",   2: "Hours"   },
			m: { 0: "Minute", 1: "Minutes", 2: "Minutes" },
			s: { 0: "Second", 1: "Seconds", 2: "Seconds" }
		}
	},
	initialize: function(elements, options) {
		this.setOptions(options);
		this.finished = [];
		this.elements = elements
	},
	start: function() {
		if( ! this.elements) return;
		this.timer = setTimeout(function(){
			this.elements.each(function(item){
				var date_to  = item.get('data-to').toInt(),
					date_now = item.get('data-now').toInt(),
					days = 0, hours = 0, minutes = 0, seconds = 0;

				// Increment data-now with update seconds
				item.set('data-now', date_now + this.options.update / 1000);

				if(date_to <= date_now) {
					Array.append(this.finished, [item]);
					this.fireEvent('completed');
					return;
				}

				var diff = date_to - date_now;

				// Days
				if(diff > 86400) {
					days  = Math.floor(diff / 86400);
					diff -= days * 86400;
				}
				// Hours
				if(diff > 3600) {
					hours  = Math.floor(diff / 3600);
					diff  -= hours * 3600;
				}
				// Minutes
				if(diff > 60) {
					minutes  = Math.floor(diff / 60);
					diff    -= minutes * 60;
				}
				// Seconds
				seconds = diff;
				// Render the template
				this.setTime(item, days, hours, minutes, seconds);
			}.bind(this));
			this.start();
		}.bind(this), this.options.update)
	},
	setTime: function(item, days, hours, minutes, seconds) {
		var rendered = this.options.big_format.substitute({
			D: this.options.small_format.substitute({
				number: days,
				word: Lang.numForm(days, this.options.lang.d)
			}),
			H: this.options.small_format.substitute({
				number: hours,
				word: Lang.numForm(hours, this.options.lang.h)
			}),
			M: this.options.small_format.substitute({
				number: minutes,
				word: Lang.numForm(minutes, this.options.lang.m)
			}),
			S: this.options.small_format.substitute({
				number: seconds,
				word: Lang.numForm(seconds, this.options.lang.s)
			})
		});
		item.set("html", rendered)
	},
	stop: function () {
		clearInterval(this.timer)
	}
});

//############################################################################
//# User
//############################################################################
User = {

	battleRemove: function(title, battle_id) {
		if(confirm(title)) {
			window.location = '/battle/remove/index/' + battle_id;
		}
	}

};