﻿var soundManager;
var invitesReceiver = $.init(function() {
	var 
	self = this,
	invites = {},
	isCollapsed = false,
	blinkQueue = [], // Очередь для инвайтов, которые показываются при isCollapsed == true
	blinkQueueInterval,  // Функция, которая будет показывать инвайты из blinkQueue
	readyToBlink = true, // Флаг для определения того, можно ли показать следующий инвайт из blinkQueue
	notifyID = 0,
	minimizedCallback,
	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'); // пустой элемент
		});
	};

	var blink = function() {
		$('.i-number', popup).animate({ opacity: .01 }, 250).animate({ opacity: 1 }, 250);
	};

	this.startNotify = function() {
		if (notifyID) return;

		blink();

		notifyID = setInterval(function() {
			blink();
		}, 1000);
	}

	this.stopNotify = function() {
		clearInterval(notifyID);
		notifyID = 0;
	}

	this.toggleNotify = function(state) {
		if (typeof state == 'undefined')
			state = false;

		return state ? this.startNotify() : this.stopNotify();
	};

	this.getChatHost = function() {
		return 'http://chat.' + window.location.hostname.replace(/^www\./, '');
	};

	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; // delete me

				invite.find('.bar').css({ width: invite.lifetime || this.lifetime + '%' });

				invitesReceiver.enqueueInvite(invite);

				if (invite.fresh && !!soundManager) {
					soundManager.playInvite();
					soundManager.toggleMute();
				}
			});

		if (!!soundManager && soundManager.isMuted())
			soundManager.toggleMute();

		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')
			.each(function() {
				self.toggleNotify(!!invitations && invitesReceiver.isCollapsed);
			})
			.text(invitations);

		if ($('#invites-popup').length)
			document.title = (invitations || 'No') + ' Chat Invitation' + (invitations == 1 ? '' : 's');
	};

	this.toggleInvitations = function(minimize) {
		if (!popup) return;

		popup.find('li:not(.template)').each(function() {
			var invite = $(this);

			container.removeClass('notify');

			invite.parent().stop(true, true);
			invite.stop(true, true).animate({ opacity: minimize ? 0 : 1, height: minimize ? 0 : invite.restore('height') }, 200, function() {
				invite.css({ display: minimize ? 'none' : '', opacity: null });
			});
		});

		if (!minimize) {
			readyToBlink = true;
			blinkQueue = [];
			clearInterval(blinkQueueInterval);
			blinkQueueInterval = null;
		}

		this.toggleNotify(minimize);
	};

	this.enqueueInvite = function(invite) {
		if (invite.length && invite.fresh && invite.parents().index(container) == -1) {
			togglePopup(false);

			$("img.smile", invite).attr("src", function() {
				return invitesReceiver.getChatHost() + this.src.substring(this.src.indexOf("/i/"));
			});

			invite
				.prependTo(container)
				.css({ display: 'block' })
				.filter(':visible')
				.store('height', invite.height())
				.height(0);

			// Разная анимация для разного состояния invitesReceiver.isCollapsed
			if (invitesReceiver.isCollapsed) {
				blinkQueue[blinkQueue.length] = invite;

				blinkQueueInterval = blinkQueueInterval || setInterval(function() {

					if (readyToBlink) {
						readyToBlink = false;

						var blinkingInvite = blinkQueue[0];

						if (!blinkQueue[0])
							return;

						container.addClass('notify');
						blinkingInvite.animate({ height: invite.restore('height') }, 1000);

						blinkingInvite.hover(function() {
							clearTimeout($(this).restore('fadeTimeout'));
							blinkingInvite.parent().stop().css({ opacity: null });
						}, function() {
							blinkingInvite.store('fadeTimeout', setTimeout(function() {
								if (invitesReceiver.isCollapsed)
									blinkingInvite.parent().animate({ opacity: 0 }, 2400, function() {
										blinkingInvite.css({ display: 'none', height: 0 });
										blinkingInvite.parent().css({ opacity: null });
										container.removeClass('notify');
										readyToBlink = true;
									});

								blinkQueue.shift();

								if (blinkQueue.length == 0) {
									clearInterval(blinkQueueInterval);
									blinkQueueInterval = null;
								}

								readyToBlink = !invitesReceiver.isCollapsed;
							}, 2500)); // blinkingInvite.store
						}); // linkingInvite.hover

						blinkingInvite.mouseout();

					} // if (readyToBlink)

				}, 500); // setTimeout
			} // if (invitesReceiver.isCollapsed)
			else {
				invite.animate(
					 { height: invite.restore('height') },
					1000,
					'linear',
					function() { }
				);
			}

		}
	};
});

var popupController = $.init(function() {
	var 
	chats = {},
	invites,
	options = {
		chat: {
			height: 680,
			width: 815,
			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(
				invitesReceiver.getChatHost() + '/chat/' + a + (a && '/'),
				w || options.chat.name || ('chat' + (a || '')),
				buildWindowFeatures(options.chat)
			);

			chats[a || 'chat'].focus();
		} catch (e) {
			if (console && console.log)
				console.log(e && e.message);
		}
	};

	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;

		var wd = 800;
		var hg = 600;
		var lf = screen.availWidth / 2 - wd / 2;
		var tp = screen.availHeight / 2 - hg / 2;

		invites = window.open(
			'http://chat.' + window.location.hostname.replace(/^www\./, '') + '/invites/',
			options.invites.name || 'invitespopup',
			buildWindowFeatures(options.invites),
			'chat',
			'width=' + wd + ',height=' + hg + ',top=' + tp + ',left=' + lf + ',toolbar=no,menubar=no,scrollbars=yes,resizable=yes,location=no,directories=no,status=no'
		);

		invites.focus();
	};
});

