// $Id: TnmtRegLib.js,v 1.6 2010-04-14 13:00:55 jbesson Exp $

function TnmtRegLib(name) {

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

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

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

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

	var _urls = {
		sub    : getBaseURL() + '?action=tnmt_sub',
		cancel : getBaseURL() + '?action=tnmt_cancel_sub'
	};

	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() {

	var url;

	switch (__pub.params.op) {
		case 'S':
			url = _urls.sub;
			if (__pub.params.gameId != null) {
				url += '&game_id=' + __pub.params.gameId;
				if (__pub.params.pwdLmt == 'Y') {
					url += '&prv_tnmt_pwd=' + escape(__pub.params.pwd);
				}
				if (__pub.params.tokAmount != '') {
					url += '&fb_shown=Y';
				}
			} else {
				url += '&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;
			}
			break;
		case 'C':
			url = _urls.cancel + '&game_id=' + __pub.params.gameId;
			break;
	}

	return url;
}

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 {
		TnmtLobby.Req.poll();
	}
}

function hint(which) {

	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';
					if (__pub.params.tnmtType == 'S') {
						txt += ' starting at ' + __pub.params.startDesc;
					}

					sky.overlay.getChoice(
						'Registration Successful',
						txt,
						[
							sky.overlay.button(
								_quickPlay && !document.qp_no_redirect ? 'View tournament lobby' : 'Ok',
								function() { eval(proceedCode); }
							)
						]
					);
				} else {
					if (typeof BG != 'undefined') {
						BG.expectFundsReturn();
					} else if (typeof window.opener.BG != 'undefined') {
						window.opener.BG.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',
								function() { eval(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',
							function() { eval(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_game_def_id, qp_limit_type, qp_reg_max, qp_buy_in, qp_tnmt_type, qp_avoid_nickname, another) {

	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') {
			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;

		if (__pub.params.gameId == null) {
			__pub.params.qpGameDefId     = qp_game_def_id;
			__pub.params.qpLimitType     = qp_limit_type;
			__pub.params.qpRegMax        = qp_reg_max;
			__pub.params.qpBuyIn         = qp_buy_in;
			__pub.params.qpTnmtType      = qp_tnmt_type;
			__pub.params.qpAvoidNickname = qp_avoid_nickname;
		} 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;
		}
	}
	
	if (!chkLogin('TnmtReg.showForm()')) {
		return false;
	}

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

		txt += '<table>';
		txt += '<tr><th scope="row">Available Balance</th><td>' + State.login.disp_balance + '</td></tr>';
		txt += '<tr><th scope="row">Buy-in + Fee</th><td>' + __pub.params.buyIn + '</td></tr>';
		if (__pub.params.gameId != null) {
			txt += '<tr><th scope="row">Prize Pool</th><td>' + __pub.params.prizePool + '</td></tr>';
		}
		if (__pub.params.tokAmount != '') {
			txt += '<tr><th scope="row">Freebet amount</th><td>' + __pub.params.tokAmount + '</td></tr>';
		}
		txt += '</table>';

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

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

	}

	txt += '<span id="tnmt_reg_msg">&nbsp;</span>';

	sky.overlay.getChoice(
		title,
		txt,
		[
			sky.overlay.button(
				'Confirm',
				function () {
					TnmtReg.req();
				},
				function () {
					return false;
				}
			),
			sky.overlay.button(
				'Cancel',
				function() {
					eval(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,
		makeId : makeId,
		req : req,
		render : render,
		hint : hint,
		showForm : showForm
	};

	Req.regPar(_this);

	return _this;
}
