// $Id: BGLib.js,v 1.3 2009-12-22 16:22:02 jbesson Exp $

function BGLib(name) {

	var __pub = {
		name : name,
		doLoginUpd : false
	}

	var _pollRules = {
		next     : {ms : 0,     startAtZero : true},
		fast     : {ms : 4000,  startAtZero : false},
		normal   : {ms : 24000, startAtZero : false},
		loginUpd : {ms : 60000, startAtZero : true}
	}

	// set this to a time within which we can reasonably expect a cleardown
	// refund to have happened - make it as short as possible
	var _expectFundsRefresh = 5000;

	var _clickIdle = 300000;
	var _pollInterval = 1000;

	try {eval(applyOverrideJS);} catch (e) {}

	var Req = ReqLib(name, {
		reqType : 'bg',
		type : null,
		refreshNormal : null,
		refreshIdle : null,
		url : 'bg_www',
		respType : 'arr',
		renderDelay : null
	});

	var _polls = {};
	for (var i in _pollRules) {
		_polls[i] = {
			when  : Math.ceil(_pollRules[i].ms / _pollInterval),
			count : _pollRules[i].startAtZero ? 0 : Math.ceil(_pollRules[i].ms / _pollInterval)
		};
	}
	var _waitlistPoll = false;
	var _timer = null;

	var _adCols = ['id', 'sort', 'priority', 'private', 'content'];

	var _clock = {
		timer : null,
		date  : null
	}

function canPoll() {

	// blocked if mid-login
	return Login.canReq();
}

function canResp() {

	// blocked if mid-login
	return Login.canReq();
}

function makeURL() {

	var url, upd, waitlist, max_ad_id;

	if (__pub.doLoginUpd && location.toString().substr(0,5) == "https") {
		url = Req.pub.urls.normal;
		upd = 'Y';
		__pub.doLoginUpd = false;
	} else {
		url = Req.pub.urls.dirty;
		upd = 'N';
	}

	if (_waitlistPoll) {
		waitlist = 'Y';
		_waitlistPoll = false;
	} else {
		waitlist = 'N';
	}

	max_ad_id = get_cookie(document.max_ad_id_cookie);
	if (!max_ad_id) {
		max_ad_id = '';
	}

	return url + "&upd=" + upd + '&waitlist=' + waitlist + '&max_ad_id=' + max_ad_id + '&ms=' + new Date().getTime();
}

function makeId() {

	return null;
}

function poll() {

	var mode, shouldWaitlistPoll = false;

	if (_timer != null) {
		clearTimeout(_timer);
		_timer = null;
	}

	for (mode in _polls) {
		_polls[mode].count++;
	}

	if (_polls['next'].when > 0) {
		mode = 'next';
	} else {
		shouldWaitlistPoll = Quickplay.shouldWaitlistPoll();
		if (shouldWaitlistPoll) {
			mode = 'fast';
		} else {
			mode = 'normal';
		}
	}

	if (_polls[mode].count >= _polls[mode].when) {

		_polls['next'].count   = 0;
		_polls['fast'].count   = 0;
		_polls['normal'].count = 0;

		if (mode == 'next') {
			// don't do 'next' next time
			_polls['next'].when = 0;
		}

		if (_polls['loginUpd'].count >= _polls['loginUpd'].when
		 && (new Date().getTime() - State.lastClick) <= _clickIdle
		) {
			__pub.doLoginUpd = true;
		}

		if (__pub.doLoginUpd) {
			// doLoginUpd may have been set to true elsewhere
			_polls['loginUpd'].count = 0;
		}

		if (shouldWaitlistPoll) {
			_waitlistPoll = true;
		}

		Req.poll();
	}

	_timer = setTimeout(poll, _pollInterval);
}

function _pollNext(msFromNow) {

	_polls['next'].when  = Math.ceil(msFromNow / _pollInterval);
	_polls['next'].count = 0;
}

function render() {

	var cookie = Req.pub.items[0];
	if (cookie != '') {
		set_cookie(document.login_cookie, cookie, '', '/', '', '');
	}

	Login.setLoginUID(Req.pub.items[Req.pub.items.length - 1]);

	dispLogin();

	_usersShow(Req.pub.items[1], Req.pub.items[2]);
	_clockStart(Req.pub.items[Req.pub.items.length - 2]);

	var active_tnmts;
	if (Req.pub.items[3] != '') {
		active_tnmts = Req.pub.items[3].split('|');
	} else {
		active_tnmts = [];
	}
	var i, popup, win, popup_game_id;
	for (i = 0; i < active_tnmts.length; i+=2) {
		popup = get_cookie(document.popup_cookie + '_M' + active_tnmts[i]);
		if (!popup || !popup.match(new RegExp('^[0-9]+$')) || parseInt(popup) < (new Date().getTime() - 3000)) {
			win = State.openTable('T','M', active_tnmts[i], {gameNameClue : 'Tournament ' + active_tnmts[i+1] + ': '});
			if (!win && !State.autoPopupAlert) {
				popup_game_id = active_tnmts[i];
				State.autoPopupAlert = true;
				sky.overlay.getChoice(
					'Tournament Starting',
					active_tnmts[i+1] + ' is starting now.</p><p>You appear to have popup-blocking enabled so click Launch to open the tournament.</p><p>To find help on allowing popups in your browser, click <a href="' + document.helpURLS.base + '" rel="external" class="pu_help">here</a>.</p>',
					[
						sky.overlay.button( 'Launch', function() {
							State.autoPopupAlert = false;
							State.openTable('T','M',popup_game_id);
						}),
						sky.overlay.button( 'Cancel', function() {
							State.autoPopupAlert = false;
						})
					]
				);
			}
		}
	}

	var starting_tnmts;
	if (Req.pub.items[4] != '') {
		starting_tnmts = Req.pub.items[4].split('|');
	} else {
		starting_tnmts = [];
	}

	var active_snps;
	if (Req.pub.items[5] != '') {
		active_snps = Req.pub.items[5].split('|');
	} else {
		active_snps = [];
	}

	for (i = 0; i < active_snps.length; i+=2) {
		popup = get_cookie(document.popup_cookie + '_T' + active_snps[i]);
		if (!popup || !popup.match(new RegExp('^[0-9]+$')) || parseInt(popup) < (new Date().getTime() - 3000)) {
			win = State.openTable('S','T', active_snps[i]);
			if (!win && !State.autoPopupAlert) {
				popup_game_id = active_snps[i];
				State.autoPopupAlert = true;
				sky.overlay.getChoice(
					'Active Cash Game',
					'You are currently seated at ' + active_snps[i+1] + '.</p><p>You appear to have popup-blocking enabled so click Launch to open the table.</p><p>To find help on allowing popups in your browser, click <a href="' + document.helpURLS.base + '" rel="external" class="pu_help">here</a>.</p>',
					[
						sky.overlay.button( 'Launch', function() {
							State.autoPopupAlert = false;
							State.openTable('S','T',popup_game_id);
						}),
						sky.overlay.button( 'Cancel', function() {
							State.autoPopupAlert = false;
						})
					]
				);
			}
		}
	}

	var max_ad_id = Req.pub.items[6];

	var num_ads = Req.pub.items[7];

	var i, r, ad;
	var ads = [];
	i = 8;
	for (r = 0; r < num_ads; r++) {

		ad = {};
		for (c = 0; c < _adCols.length; c++) {
			ad[_adCols[c]] = Req.pub.items[i+c];
		}

		ads.push(ad);
		i += _adCols.length;
	}

	// !!!!!!!!!!!!!!! for now, display starting tnmts as ticker adverts ???????????????????
	for (i = 0; i < starting_tnmts.length; i+=2) {
		ads.push({
			id       : 'TNMT_' + starting_tnmts[i],
			sort     : 'T',
			priority : '1',
			private  : '1',
			content  : '<b>Tournament ' + starting_tnmts[i+1] + ' will start soon.</b>'
		});
	}

	Advert.handleAdverts(ads);
}

function hint(which) {

	return;
}

function expectFundsReturn() {

	__pub.doLoginUpd = true;

	_pollNext(_expectFundsRefresh);
}

function _clockShow() {

	var o = document.getElementById('clockDisp');
	if (o) {
		var mins = Number(_clock.date.getMinutes());
		if (mins < 10) {
			mins = '0' + mins;
		}

		var sec = Number(_clock.date.getSeconds());
		if (sec < 10) {
			sec = '0' + sec;
		}

		o.innerHTML = _clock.date.getHours() + ':' + mins + ':' + sec;
	}
}

function _clockHide() {

	var o = document.getElementById('clockDisp');
	if (o) {
		o.innerHTML = '';
	}
}

function _clockUpdate() {

	if (_clock.timer) {
		clearTimeout(_clock.timer);
		_clock.timer = null;
	}

	_clock.date.setTime(_clock.date.getTime() + 1000);

	_clockShow();

	_clock.timer = setTimeout(_clockUpdate, 1000);
}

function _clockStart(ifxDate) {

	if (_clock.timer) {
		clearTimeout(_clock.timer);
		_clock.timer = null;
	}

	var match = ifxDate.match('(....)-(..)-(..) (..):(..):(..)');

	if (match != null) {
		_clock.date = new Date(
			match[1],
			match[2] - 1,
			match[3],
			match[4],
			match[5],
			match[6]
		);
		_clockShow();
		_clock.timer = setTimeout(_clockUpdate, 1000);
	} else {
		_clockHide();
	}
}

function _usersShow(num_conn, num_seated) {

	var o = document.getElementById('lobstate');

	if (o) {
		var lis = o.getElementsByTagName('li');
		if (lis && lis.length == 2) {
			lis[0].innerHTML = '<strong>' + num_conn + '</strong> Online';
			lis[1].innerHTML = '<strong>' + num_seated + '</strong> Seated';
		}
	}
}

	var _this = {
		pub : __pub,
		Req : Req,
		canPoll : canPoll,
		canResp : canResp,
		makeURL : makeURL,
		makeId : makeId,
		poll : poll,
		render : render,
		hint : hint,
		expectFundsReturn : expectFundsReturn
	};

	Req.regPar(_this);

	return _this;
}
