// $Id: QuickplayLib.js,v 1.2 2009-11-20 11:59:16 jbesson Exp $

function QuickplayLib(name) {

	var __pub = {
		name : name
	}

	var Req = ReqLib(name, {
		reqType : 'quickplay',
		type : null,
		refresh : null,
		url : null,
		respType : 'arr',
		renderDelay : 600
	});

	var _urls = {
		reserve  : getBaseURL('committed') + '?action=do_quick_play',
		waitlist : getBaseURL('committed') + '?action=do_waitlist'
	};

	var _which = '';
	var _params = {
		useForm : false,
		reserve : {
			gameDefId : null,
			limitType : null,
			numSeats : null,
			stake : null,
			numSeated : null
		},
		waitlist : {
			op : null,
			tabId : null
		}
	};
	var _limitType = null;
	var _numSeats = null;
	var _stake = null;
	var _numSeated = null;

	var _result = '';
	var _msg = '';

	var _statuses = {
		TABLE_FULL       : 'RETRY',
		WAIT_ADD_FULL    : 'FULL',
		RESERVED         : 'OK',
		WAIT_ON_LIST     : 'OK',
		WAIT_NOT_ON_LIST : 'OK',
		TIMEOUT          : 'TIMEOUT'
	};

	var _retryMax   = 3;
	var _retryCount = 0;
	var _retryDelay = 5000;
	var _retryTimer = null;

	var _timeout = {
		ms : 5000,
		timer : null
	};
	var _midRequest   = false;

	var _hintTimer    = null;


function canReq() {

	if (Req.canReq(true) && !_midRequest) {
		return true;
	}
	return false;
}

function makeURL() {

	var url = _urls[_which];

	var params = _params[_which];

	switch (_which) {
		case 'reserve' :
			url +=
				  '&game_def_id='+ params.gameDefId
				+ '&limit_type=' + params.limitType
				+ '&num_seats='  + params.numSeats
				+ '&stake='      + params.stake
				+ '&num_seated=' + params.numSeated;
			break;
		case 'waitlist' :
			url +=
				  '&op='     + params.op
				+ '&tab_id=' + params.tabId;
			break;
	}

	return url;
}

function makeId() {

	return null;
}

function req(which, params, retrying) {

	if (!Req.canReq()) {
		return false;
	}

	if (!chkLogin()) {
		return false;
	}

	if (!retrying) {

		if (params == null) {
			// get params from dom
			switch (which) {
				case 'reserve' :
					qpMemStore();
					if (document.getElementById('qp_game_type_sel').value == 'S') {

						_params[which].gameDefId = document.getElementById('qp_game_def_id_sel').value;
						_params[which].limitType = document.getElementById('qp_cash_limit_type_sel').value;
						_params[which].numSeats  = document.getElementById('qp_cash_seats_sel').value;
						_params[which].stake     = document.getElementById('qp_cash_stake_sel').value;
						_params[which].numSeated = document.getElementById('qp_cash_num_seated_sel').value;

						if (_params[which].gameDefId == -1
						 || _params[which].limitType == -1
						 || _params[which].numSeats  == -1
						 || _params[which].stake     == -1
						 || _params[which].numSeated == -1)
						{
							_invalidForm();
							return false;
						}

					} else {
						var game_def_id = document.getElementById('qp_game_def_id_sel').value,
							buy_in     = document.getElementById('qp_sng_buy_in_sel').value,
							limit_type = document.getElementById('qp_sng_limit_type_sel').value,
							reg_max    = document.getElementById('qp_sng_reg_max_sel').value,
							tnmt_type  = document.getElementById('qp_sng_type_sel').value,
							proceedCode = 'openTnmtLobby(TnmtReg.pub.params.gameId)';

						if (game_def_id == -1
						 || buy_in      == -1
						 || limit_type  == -1
						 || reg_max     == -1
						 || tnmt_type   == -1)
						{
							_invalidForm();
							return false;
						}

						TnmtReg.showForm('S', null, sng_desc(game_def_id, limit_type, tnmt_type, reg_max), qp_cost_desc(buy_in, ' + '), null, 'R', null, null, proceedCode, null, null, game_def_id, limit_type, reg_max, buy_in, tnmt_type);
						return false;
					}
					break;
				case 'waitlist' :
					alert('Quickplay.req - form method not available for ' + which);
					return false;
					break;
			}
			_params.useForm = true;
		} else {
			if (params.gameType == 'T') {
				var proceedCode = 'openTnmtLobby(TnmtReg.pub.params.gameId)';
				TnmtReg.showForm('S', null, sng_desc(params.gameDefId, params.limitType, params.tnmtType, params.regMax), qp_cost_desc(params.buyIn, ' + '), null, 'R', null, null, proceedCode, null, null, params.gameDefId, params.limitType, params.regMax, params.buyIn, params.tnmtType);
				return false;
			} else {
				_params[which] = params;
				_params.useForm = false;
			}
		}

		_which = which;

		// reset retries
		_retryCount = 0;
		if (_retryTimer) {
			clearTimeout(_retryTimer);
			_retryTimer = null;
		}

	} else {
		// retrying so leave all as-is
	}

	_timeout.timer = setTimeout(_timedout, _timeout.ms);

	_midRequest = true;

	Req.req();

	return false;
}

function render() {

	if (_timeout.timer != null) {
		clearTimeout(_timeout.timer);
		_timeout.timer = null;
	}

	_midRequest = false;

	if (typeof _statuses[Req.pub.items[0]] != 'undefined') {
		_result = _statuses[Req.pub.items[0]];
	} else {
		_result = 'FAIL';
	}

	if (_result == 'TIMEOUT') {
		switch (_which) {
			case 'reserve' :
				_result = 'RETRY';
				break;
			case 'waitlist' :
				_result = 'FAIL';
				break;
		}
	}

	if (_result == 'RETRY' && ++_retryCount >= _retryMax) {
		_result = 'FAIL';
	}

	if (_result == 'OK') {
		switch (_which) {
			case 'reserve' :
				_msg = 'Opening table ' + Req.pub.items[2];
				State.openTable('S', 'T', Req.pub.items[1]);
				break;
			case 'waitlist' :
				if (_params[_which].op == 'A') {
					_msg = 'You have joined the waiting list';
				} else if (_params[_which].op == 'C') {
					_msg = 'You have left the waiting list';
				}
				break;
		}
	}

	hint('done');

	if (_which == 'waitlist' && document.isLobby) {
		Detail.Req.poll();
	}
}

function hint(which) {

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

	switch (which) {
		case 'update':
		case 'new':
			switch (_which) {
				case 'reserve' :
					document.getElementById('qp_hint').innerHTML = 'Searching...';
					break;
				case 'waitlist' :
					document.getElementById('qp_hint').innerHTML = 'Updating...';
					break;
			}
			break;

		case 'done':
			switch (_result) {
				case 'OK' :
					document.getElementById('qp_hint').innerHTML = _msg;
					_hintTimer = setTimeout(function() {
						 document.getElementById('qp_hint').innerHTML = '';
					}, 5000);
					if (_which == 'waitlist' ) {
						doWaitlistCookie(_params[_which].op, _params[_which].tabId);
					}
					break;

				case 'TIMEOUT' :
					if (_which == 'reserve' ) {
						_retryTimer = setTimeout(function() {
							req(_which, null, true);
						}, _retryDelay);
					} else if (_which == 'waitlist') {
						sky.overlay.doAlert('Sorry', 'Sorry, there was a problem, please try again', 'warning');
					}
					break;

				case 'RETRY' :
					_retryTimer = setTimeout(function() {
						req(_which, null, true);
					}, _retryDelay);
					break;

				case 'FULL' :
					document.getElementById('qp_hint').innerHTML = '';
					sky.overlay.doAlert('Sorry', 'Sorry, the waiting list is already full');
					break;

				case 'FAIL' :
					if (_which == 'reserve' ) {
						document.getElementById('qp_hint').innerHTML = '';
						var msg = '';
						var tryAgain = false;
						if (_params.useForm) {
							if (document.getElementById('qp_cash_num_seated_sel').value != 1) {
								msg += 'Click <a href="javascript:void(0)" onclick="retry_decr_min_players()">here</a> to reduce the minimum number of players to ' + (document.getElementById('qp_cash_num_seated_sel').value-1) + ' and retry.';
								tryAgain = true;
							} else {

								// Find next stake up
								var ss = document.getElementById('qp_cash_stake_sel'), idx = ss.selectedIndex;
								do {
									idx++;
								} while (idx < ss.options.length && ss.options[idx].disabled);

								if (idx < ss.options.length) {
									msg += 'Click <a href="javascript:void(0)" onclick="retry_incr_stake(' + idx + ')">here</a> to increase blind level to ' + ss.options[idx].text + ' and retry.';
									tryAgain = true;
								}
							}
						}
						var btns = [];
						if (tryAgain) {
							btns.push(
								sky.overlay.button(
									'Try Again',
									function() {
										Quickplay.req('reserve');
									}
								)
							);
						}
						btns.push(
							sky.overlay.button(
								'Cancel'
							)
						);
						sky.overlay.getChoice(
							'No table matching your request has been found',
							msg,
							btns
						);
					} else if (_which == 'waitlist' ) {
						document.getElementById('qp_hint').innerHTML = '';
						sky.overlay.doAlert('Sorry', 'Sorry, there was a problem, please try again', 'warning');
					}
					break;
			}
			break;
	}
}

function _invalidForm() {

	document.getElementById('qp_hint').innerHTML = 'Invalid search parameters';
	this.hintTimer = setTimeout(function() {
			document.getElementById('qp_hint').innerHTML = '';
	}, 5000);
}

function _timedout() {

	if (_timeout.timer != null) {
		clearTimeout(_timeout.timer);
		_timeout.timer = null;
	}

	if (!_midRequest) {
		return;
	}

	Req.incrCount();

	// pretend server responded with TIMEOUT
	Req.pub.items.length = 0;
	Req.pub.items.push('TIMEOUT');

	render();
}

function doWaitlistCookie(op, tabId) {

	var i, cookie, oldPairs = [], newPairs = [];

	cookie = get_cookie(document.waiting_list_cookie);
	if (cookie && cookie != '') {
		oldPairs = cookie.split('|');
	}

	for (i = 0; i < oldPairs.length; i += 3) {
		if (oldPairs[i] != tabId) {
			newPairs.push(oldPairs[i]);
			newPairs.push(oldPairs[i+1]);
			newPairs.push(oldPairs[i+2]);
		}
	}
	newPairs.push(tabId);
	newPairs.push(op);
	newPairs.push(Math.floor(new Date().getTime() / 1000));

	set_cookie(document.waiting_list_cookie, newPairs.join('|'), '', '/', '', '');
}

function shouldWaitlistPoll() {

	var cookie = get_cookie(document.waiting_list_cookie);

	if (cookie && cookie != '') {
		var pairs = cookie.split('|');
		var time = new Date().getTime();

		for (var i = 0; i < pairs.length; i += 3) {
			if (pairs[i+1] == 'A') {
				popup = get_cookie(document.popup_cookie + '_T' + pairs[i]);
				if (!popup || !popup.match(new RegExp('^[0-9]+$')) || parseInt(popup) < (time - 3000)) {
					// a waitlist table is not open so should poll
					return true;
				}
			}
		}
	}

	return false;
}

	var _this = {
		pub : __pub,
		Req : Req,
		canReq : canReq,
		makeURL : makeURL,
		makeId : makeId,
		req : req,
		render : render,
		hint : hint,
		doWaitlistCookie : doWaitlistCookie,
		shouldWaitlistPoll : shouldWaitlistPoll
	};

	Req.regPar(_this);

	return _this;
}
