﻿// Common overrides

popupController.openChat = function() {
	var attendee;
	for (var i = 0; i < arguments.length; i++)
		typeof arguments[i] == 'number'
			? attendee = arguments[i] : null;

	window.location.href = 'http://' + window.location.host +
		'/Pages/Security/RegisterLoginLadyInfo.aspx?GirlID=' + attendee +
		'&fromProfile=1&toLiveChat=1&ReturnUrl=%2fPages%2fLady%2fProfile%2fProfilePreview.aspx%3fLadyID%3d' + attendee + '%26livechat%3d1';
};

serviceChannel.sendBusy = null;



// Main

$.init(invitesReceiver, function() {
	var 
	self = this,
	interval = 0,
	loadedInvites = {},
	enqueued = {},
	loadCount,
	lastTime = 0,
	currentInviteIndex = 1,
	sumLoaded = 0;

	// Configurations
	var 
	inviteLifetime = 40,
	enableLog = false,
	maxBatchSize = 3,
	minStart = 5,
	maxStart = 10,
	minInviteDelay = 0,
	maxInviteDelay = 40,
	minBatchDelay = 20,
	maxBatchDelay = 40;

	log = function() {
		if (enableLog && typeof console != 'undefined') {
			var logstr = ''
			for (var i = 0; i < arguments.length; i++) {
				logstr += arguments[i] + ' ';
			}
			console.log(logstr);
		}
	};

	size = function(obj) {
		var count = 0;
		for (var e in obj) { ++count; }
		return count;
	};

	randomRange = function(minVal, maxVal) {
		return Math.floor(Math.random() * (maxVal - minVal + 1) + minVal);
	};

	this.base$enqueueInvite = this.enqueueInvite;
	this.base$cleanUp = this.cleanUp;

	this.enqueueInvite = function(invite) {
		if (!invite.fresh)
			return;

		invite.lifetime = 100;
		invite.shown = false;
	};

	this.cleanUp = function(invites) {
		// Init before enqueue
		loadInterval = this.interval / 1000;
		loadCount = 0;

		// Copy invites in indexed array starts with 1
		var doLoad = interval + loadInterval >= lastTime;
		log('cur time:', interval, 'enqueued until:', lastTime, 'do load?', doLoad);
		if (doLoad) {
			$.each(invites, function(key) {
				if (this.fresh) {
					loadedInvites[currentInviteIndex + loadCount++] = this;
				}
			});
			sumLoaded += loadCount;
			log(loadCount, 'invites loaded', sumLoaded);

			// Unqueue all invites
			enqueueInvites(true);
		}

		$.each(invites, function(key) {
			this.stale = !this.is(':visible');
		});

		// Base clean up
		self.base$cleanUp(invites);
	};

	enqueueInvites = function(isFirst) {
		var batchSize = randomRange(1, maxBatchSize),
			startInterval = isFirst ? randomRange(minStart, maxStart) : 0,
			maxTime = 0;

		lastTime = Math.max(Math.max(lastTime, interval), startInterval);

		log('start invite', currentInviteIndex, ':', lastTime);

		enqueued[lastTime] = loadedInvites[currentInviteIndex];
		delete loadedInvites[currentInviteIndex];
		++currentInviteIndex;

		for (var i = 2; i <= batchSize; i++, currentInviteIndex++) {
			if (!loadedInvites[currentInviteIndex]) {
				break;
			}

			var tmpTime = randomRange(minInviteDelay, maxInviteDelay);
			enqueued[lastTime + tmpTime] = loadedInvites[currentInviteIndex];
			delete loadedInvites[currentInviteIndex];

			log('invite', currentInviteIndex, ':', lastTime + tmpTime);
			maxTime = Math.max(maxTime, tmpTime);
		}

		var batchDelay = randomRange(minBatchDelay, maxBatchDelay);

		lastTime += maxTime + inviteLifetime + batchDelay;

		log('next batch starts: ', lastTime);
		log(currentInviteIndex, sumLoaded);

		log('');
		while (currentInviteIndex <= sumLoaded) {
			enqueueInvites(false);
		}
	}

	this.timer = setInterval(function() {
		++interval;

		var invite = enqueued[interval];
		if (invite && (invite.fresh = true)) {
			self.base$enqueueInvite(invite);
			invite.shown = true;
		}

		var i = interval - inviteLifetime, attendee = 0;

		if (enqueued[i] && (attendee = enqueued[i].data('attendee'))) {
			self.closeInvitation(attendee, function() {
				delete enqueued[i];
			});
		}

		$.each(enqueued, function() {
			if (!this.shown)
				return;

			this.lifetime -= 100 / inviteLifetime;
			$(this).find('.bar').css({ width: Math.max(this.lifetime, 0) + '%' });
		});

		$('#invitations').text($('#chat-invites ul li:not(.template)').length);

	}, 1000);
});