// $Id: TnmtRegLib.js,v 1.14 2011-08-18 14:16:27 jrixon Exp $

function TnmtRegLib(name) {

	var __pub = {
		name : name,
		params : {}
	};

	var _timeout = {
		ms : 15000,
		timer : null
	};

	var Req = ReqLib(name, {
		reqType : 'tnmt_reg',
		type : null,
		refreshNormal : null,
		refreshIdle : null,
		url : null,
		respType : 'arr',
		renderDelay : 600,
		ajaxMethod : 'POST'
	});

	var _result = '';
	var _msg    = '';
	var _quickPlay = false;
	var _els    = {};

	var _midRequest = false;


function canReq() {

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

function makeURL() {

	return getBaseURL();
}

function makePOST() {

	var args = [];

	switch (__pub.params.op) {
		case 'S':
			args[args.length] = 'action=tnmt_sub';
		break;

		case 'C':
			args[args.length] = 'action=tnmt_cancel_sub';
		break;

		default:
			warnfire('TnmtRegLib: invalid op:', __pub.params.op);
			return '';
	}

	switch (__pub.params.op) {
		case 'S':
			if (__pub.params.gameId != null) {
				args[args.length] = '&game_id=';
				args[args.length] = __pub.params.gameId;
				if (__pub.params.pwdLmt == 'Y') {
					args[args.length] = '&prv_tnmt_pwd=';
					args[args.length] = escape(__pub.params.pwd);
				}
				if (__pub.params.tokAmount != '') {
					args[args.length] = '&fb_shown=Y';
				}
			} else {
				args[args.length] = [
					'&qp=Y',
					'&game_def_id=',    __pub.params.qpGameDefId,
					'&limit_type=',     __pub.params.qpLimitType,
					'&reg_max=',        __pub.params.qpRegMax,
					'&buy_in=',         __pub.params.qpBuyIn,
					'&tnmt_type=',      __pub.params.qpTnmtType,
					'&avoid_nickname=', __pub.params.qpAvoidNickname,
					'&prev_game_id=',   __pub.params.qpPrevGameId
				       ].join('');
			}
		break;

		case 'C':
			args[args.length] = '&game_id=';
			args[args.length] = __pub.params.gameId;
		break;
	}

	return args.join('');
}

function makeId() {

	return null;
}

function req() {

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

	if (!chkLogin(TnmtReg.req)) {
		return false;
	}

	if(__pub.params.pwdLmt == 'Y') {
		_form  = document.forms['prvTnmtForm'];
		__pub.params.pwd = _form.prv_tnmt_pwd.value;
	}

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

	_midRequest = true;

	Req.req();

	return false;
}

function render() {

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

	_midRequest = false;

	dispLogin();

	_result = Req.pub.items[0];

	_quickPlay = false;
	if (_result == "OK") {
		if (__pub.params.gameId == null) {
			_quickPlay = true;
			__pub.params.gameName  = Req.pub.items[1];
			__pub.params.gameId    = Req.pub.items[2];
		}
		_msg = '';
	} else {
		_msg = Req.pub.items[1];
	}

	hint('done');

	if (document.isLobby) {
		Detail.Req.poll();
	} else {
		if (TnmtLobby && !TnmtLobby.Req.pushEnabled()) TnmtLobby.Req.poll();
	}
}

function hint(which) {

	if (__pub.params.AIRTableName != null) {
		var details;
		if (_result == 'OK') {
			details = __pub.params.gameName;
		} else {
			details = _msg;
		}
		window.parentSandboxBridge.quickplayHint(
			__pub.params.AIRTableName,
			which,
			_result,
			details);
		return;
	}

	var proceedCode = __pub.params.proceedCode, failCode = __pub.params.failCode;

	switch (which) {
		case 'update':
		case 'new':
			if (__pub.params.gameId != null) {
				_els.msg.innerHTML = 'Please wait...';
			} else {
				_els.msg.innerHTML = 'Searching...';
			}

			_els.buttons[0].hide();
			_els.buttons[1].hide();
			break;

		case 'done':

			if (_result == 'OK') {

				sky.overlay.destroy();

				var txt;

				if (__pub.params.op == 'S') {
					txt = ['Congratulations, ',
						   State.login.nickname,
						   ', you have successfully registered to play in the ',
						   __pub.params.gameName,
						   ' tournament'].join('');
					if (__pub.params.tnmtType == 'S') {
						txt = [txt, ' starting at ', __pub.params.startDesc].join('');
					}

					sky.overlay.getChoice(
						'Registration Successful',
						txt,
						[
							sky.overlay.button(
								_quickPlay && !document.qp_no_redirect
									? 'View tournament lobby'
									: 'Ok',
								_quickPlay && !document.qp_no_redirect
									? function() { openTnmtLobby(__pub.params.gameId); }
									: proceedCode
							)
						]
					);

				} else {
					if (typeof BG != 'undefined') {
						BG.expectFundsReturn();
					} else if (window && window.opener && window.opener.BG) {
						window.opener.BG.expectFundsReturn();
					} else if (window.parentSandboxBridge) {
						window.parentSandboxBridge.expectFundsReturn();
					}

					txt = State.login.nickname + ', you have successfully de-registered from the ' + __pub.params.gameName + ' tournament';
					if (__pub.params.tnmtType == 'S') {
						txt += ' starting at ' + __pub.params.startDesc;
					}
					if (_msg != '') {
						txt += '.<br>Your buy-in of ' + _msg + ' will be credited back to your Poker Account shortly.';
					}
					sky.overlay.getChoice(
						'Cancel Successful',
						txt,
						[
							sky.overlay.button(
								'Ok',
								proceedCode
							)
						]
					);
				}

			} else if (_result == 'OVS_FAIL_RETRY_ALLOWED') {

				sky.overlay.destroy();
				Nickname.showForm('verify');

			} else if (_result == 'TIMEOUT') {

				sky.overlay.destroy();
				txt = State.login.nickname + ', please be advised that we are unable to process your request at this time.  Please try again.';
				sky.overlay.getChoice(
					'Unsuccessful Registration',
					txt,
					[
						sky.overlay.button(
							'Retry',
							function() {
								TnmtReg.showForm();
							}
						)
					],
					'warning'
				);

			} else if (_result == "LOW_FUNDS") {

				sky.overlay.destroy();
				txt = State.login.nickname + ', please be advised that we are unable to process your request at this time due to insufficient funds being available.<br>Please go to the Cashier to transfer funds into your Poker Account and try again.';
				sky.overlay.getChoice(
					'Unsuccessful Registration',
					txt,
					[
						sky.overlay.button(
							'Ok',
							failCode
						)
					],
					'warning'
				);

			} else if (_result == "PRV_TNMT_INVALID_PWD") {

				sky.overlay.destroy();
				txt = _msg;
				sky.overlay.getChoice(
					'Unsuccessful Registration',
					txt,
					[
						sky.overlay.button(
							'Retry',
							function() {
								TnmtReg.showForm();
							}
						)
					],
					'warning'
				);

			} else {

				if (__pub.params.op == "S") {
					_els.msg.innerHTML = "Failed to register for tournament: " + _msg;
				} else {
					_els.msg.innerHTML = "Failed to cancel subscription: " + _msg;
				}
				_els.buttons[1].show();
			}

			break;
	}
}

function _timedout() {

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

	if (!_midRequest) {
		return;
	}
	_midRequest = false;

	Req.incrCount();

	_result = 'TIMEOUT';

	hint('done');

	if (document.isLobby) {
		Detail.Req.poll();
	}
}

function showForm(op,
				  game_id,
				  game_name,
				  buy_in,
				  start_desc,
				  tnmt_type,
				  prize_pool_total,
				  pwd_lmt,
				  token_amount,
				  proceedCode,
				  cancelCode,
				  failCode,
				  qp_info,
				  AIRTableName) {

	if (op != null) {
		__pub.params.op        = op;
		__pub.params.gameId    = game_id;
		__pub.params.gameName  = game_name;
		__pub.params.buyIn     = buy_in;
		__pub.params.startDesc = start_desc;
		__pub.params.tnmtType  = tnmt_type;
		__pub.params.prizePool = prize_pool_total;
		__pub.params.pwdLmt    = pwd_lmt;

		var re;
		if (typeof token_amount !== 'undefined' && token_amount !== null) {
			re = token_amount.match(/([\d\.]+)$/);
		} else {
			re = null;
		}
		if (re && parseFloat(re[1]) > 0) {
			__pub.params.tokAmount = token_amount;
		} else {
			__pub.params.tokAmount = '';
		}

		__pub.params.proceedCode = proceedCode;
		__pub.params.cancelCode  = cancelCode;
		__pub.params.failCode    = failCode;

		__pub.params.AIRTableName = AIRTableName;

		if (__pub.params.gameId == null) {
			__pub.params.qpGameDefId     = qp_info.game_def_id;
			__pub.params.qpLimitType     = qp_info.limit_type;
			__pub.params.qpRegMax        = qp_info.reg_max;
			__pub.params.qpBuyIn         = qp_info.buy_in;
			__pub.params.qpTnmtType      = qp_info.sng_type;
			__pub.params.qpAvoidNickname = qp_info.avoid_nickname;
			__pub.params.qpPrevGameId    = qp_info.prev_game_id;
		} else {
			__pub.params.qpGameDefId     = null;
			__pub.params.qpLimitType     = null;
			__pub.params.qpReqMax        = null;
			__pub.params.qpBuyIn         = null;
			__pub.params.qpTnmtType      = null;
			__pub.params.qpAvoidNickname = null;
			__pub.params.qpPrevGameId    = null;
		}
	}

	if (__pub.params.AIRTableName != null) {
		return false;
	}

	if (!chkLogin(TnmtReg.showForm)) {
		return false;
	}

	var title,
	txt = [];
	if (__pub.params.op == 'S') {
		title = 'Confirm Tournament Registration';
		if (__pub.params.gameId != null) {
			txt[txt.length] = '<div class="msg">Would you like to buy in to the ';
			txt[txt.length] = __pub.params.gameName;
			txt[txt.length] = ' tournament';
			if(__pub.params.tnmtType == 'S') {
				txt[txt.length] = ' starting at ';
				txt[txt.length] = __pub.params.startDesc;
			}
		} else {
			txt[txt.length] = '<div class="msg">Would you like to buy in to ';
			txt[txt.length] = (typeof qp_info !== 'undefined'
			                   && typeof qp_info.prev_game_id === 'integer'
			                   && qp_info.prev_game_id !== -1 ? 'another ' : 'a ');
			txt[txt.length] = __pub.params.gameName;
			txt[txt.length] = ' tournament';
		}
		txt[txt.length] = '?</div>';

		txt[txt.length] = '<table>';
		txt[txt.length] = '<tr><th scope="row">Available Balance</th><td>';
		txt[txt.length] = State.login.disp_balance;
		txt[txt.length] = '</td></tr>';
		txt[txt.length] = '<tr><th scope="row">Buy-in + Fee</th><td>';
		txt[txt.length] = __pub.params.buyIn;
		txt[txt.length] = '</td></tr>';

		if(__pub.params.gameId != null) {
			txt[txt.length] = '<tr><th scope="row">Prize Pool</th><td>';
			txt[txt.length] = __pub.params.prizePool;
			txt[txt.length] = '</td></tr>';
		}
		if(__pub.params.tokAmount != '') {
			txt[txt.length] = '<tr><th scope="row">Freebet amount</th><td>';
			txt[txt.length] = __pub.params.tokAmount;
			txt[txt.length] = '</td></tr>';
		}
		txt[txt.length] = '</table>';

		if(__pub.params.pwdLmt == "Y") {
			txt[txt.length] = '<form name="prvTnmtForm" action="" onSubmit="return false;">';
			txt[txt.length] = '<div class="tnmtRegPwd_1">';
			txt[txt.length] =
				'This tournament is password protected. Please enter the password below:</div>';
			txt[txt.length] = '<div class="tnmtRegPwd_2">';
			txt[txt.length] =
			  '<input name=prv_tnmt_pwd value="" size=18 maxlength=32 id=prv_tnmt_pwd type=text />';
			txt[txt.length] = '</div>';
			txt[txt.length] = '</form>';
		}

	}
	else {
		title = 'Confirm Cancel Registration';
		txt[txt.length] = '<div class="msg">';
		txt[txt.length] = State.login.nickname;
		txt[txt.length] = ', are you sure you would like to be de-registered from the ';
		txt[txt.length] = __pub.params.gameName;
		txt[txt.length] = ' tournament';
		if(__pub.params.tnmtType == 'S') {
			txt[txt.length] = ' starting at ';
			txt[txt.length] = __pub.params.startDesc;
		}
		txt[txt.length] = '?</div>';
	}

	txt[txt.length] = '<span id="tnmt_reg_msg">&nbsp;</span>';


	sky.overlay.getChoice(
		title,
		txt.join(''),
		[
			sky.overlay.button(
				'Confirm',
				function () {
					TnmtReg.req();
				},
				function () {
					return false;
				}
			),
			sky.overlay.button(
				'Cancel',
				cancelCode
			)
		],
		'pu_regconf'
	);

	_els = {
		msg     : document.getElementById('tnmt_reg_msg'),
		buttons : sky.overlay.getButtons()
	};

	return false;
}

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

	Req.regPar(_this);

	return _this;
}

