﻿var invitesReceiver = $.init(function() {
	var 
	invites = {},
	popup,
	template,
	container,
	togglePopup = this.togglePopup = function(empty) {
		empty = empty === undefined ? !popup.find('li:not(.template)').length : !!empty;

		if (popup.is(':visible') == empty)
			popup.removeClass('empty').css('opacity', empty ? 1 : 0)
			.animate({
				opacity: empty ? 0 : 1
			}, {
				duration: 1100,
				complete: function() {
					$(this).css('opacity', '').toggleClass('empty', empty);
				}
			});

		return popup;
	},
	closeInvitation = this.closeInvitation = function() {
		var attendee, callback, complete;
		for (var i = 0; i < arguments.length; i++)
			$.isFunction(arguments[i])
				? (callback
					? complete = arguments[i]
						: callback = arguments[i]) : attendee = arguments[i] || attendee;

		$.each(attendee ? invites[attendee] : invites, function(id) {
			if ($(this).parents().index(container) == -1)
				return;

			id = attendee || id;

			if (callback)
				callback.call($(this), id);

			$(this)
				.css({ opacity: 1 })
				.animate({ opacity: 0, height: 0 }, 1000, function() {
					$(this).remove();

					togglePopup();

					if (complete)
						complete.call($(this), id);
				});

			invites[id] = $('html:empty'); // пустой элемент
		});
	};

	this.init = function(_popup) {
		container = (template = (popup = _popup).find('.template')).parent();

		return this;
	};

	this.process = function(notifications, attendee) {
		$.each(invites, function() {
			this.fresh = !(this.stale = true);
		});

		if (notifications)
			$.each(notifications, function() {
				var invite = (
					invites[this.member.id]
					|| (invites[this.member.id] = template.bindo(this))
				);

				invite.stale = (invite.fresh = !invite.stale) && false;
				invite.timestamp = this.timestamp;

				invite.find('.bar').css({ width: invite.lifetime || this.lifetime + '%' });

				invitesReceiver.enqueueInvite(invite);
			});

		invitesReceiver.cleanUp(invites);
	};

	this.cleanUp = function(invites) {
		var invitations = 0;

		$.each(invites, function(id) {
			!this.length
				? delete invites[id]
					: !this.stale
						? (invitations += this.length)
							: closeInvitation(id);
		});

		$('#invitations').text(invitations);

		if ($('#invites-popup').length)
			document.title = (invitations || 'No') + ' Chat Invitation' + (invitations == 1 ? '' : 's');
	};

	this.enqueueInvite = function(invite) {
		if (invite.length && invite.fresh && invite.parents().index(container) == -1) {
			togglePopup(false);
			invite
				.prependTo(container)
				.filter(':visible')
				.store('height', invite.height())
				.height(0)
				.animate(
					 { 'height': invite.restore('height') },
					 { duration: 1000 }
				);
		}
	};
});

var popupController = $.init(function() {
	var 
	chats = {},
	invites,
	options = {
		chat: {
			height: 600,
			width: 800,
			toolbar: 0,
			scrollbars: 0,
			status: 0,
			resizable: 1,
			location: 0,
			menuBar: 0
		},
		invites: {
			height: 625,
			width: 260,
			toolbar: 0,
			scrollbars: 0,
			status: 0,
			resizable: 0,
			location: 0,
			menuBar: 0
		}
	},
	buildWindowFeatures = function(features) {
		var s = '';

		for (var key in features)
			if (key != 'name' && !$.isFunction(features[key]))
				s += ',' + key + '=' + features[key];

		return s.replace(/^,/, '');
	};

	this.init = function(o) {
		for (var k in o)
			for (var p in ((options[k] || (options[k] = {})) && o[k]))
				options[k][p] = o[k][p];
	};

	this.checkInvitesPopup = function() {
		try {
			if (invites && invites[0] && 'sleeve' == invites[0].name)
				return true;

			if (!window.invitesSubscribed)
				return false;

			invites = window.open('', options.invites.name || 'invitespopup');

			return window.invitesSubscribed = (invites && invites[0] && 'sleeve' == invites[0].name);
		} catch (e) {
			return window.invitesSubscribed = !!(invites = undefined);
		}
	};

	this.openChat = function() {
		var a, w;

		for (var i = 0; i < arguments.length; i++)
			typeof arguments[i] == 'number'
				? a = arguments[i]
					: typeof arguments[i] == 'string'
						? w = arguments[i]
							: null;

		try {
			chats[(a = a || '') || 'chat'] = window.open(
				'http://chat.' + window.location.hostname.replace(/^www\./, '') + '/chat/' + a + (a && '/'),
				w || options.chat.name || ('chat' + (a || '')),
				buildWindowFeatures(options.chat)
			);

			chats[a || 'chat'].focus();
		} catch (e) {
		}
	};

	this.openInvites = function() {
		options.invites.left =
			($.browser.msie
				? window.screenLeft + document.documentElement.clientWidth
					: window.screenX + window.outerWidth) - 260;

		options.invites.top =
			($.browser.msie
				? window.screenTop + document.documentElement.clientHeight
					: window.screenY + window.outerHeight) - 700;

		invites = window.open(
			'http://chat.' + window.location.hostname.replace(/^www\./, '') + '/invites/',
			options.invites.name || 'invitespopup',
			buildWindowFeatures(options.invites)
		);

		invites.focus();
	};
});

