// $Id: StateClass.js,v 1.32 2011-08-04 12:54:46 jrixon Exp $

function StateClass() {

	this.loading = false;
	this.centre  = null;
	this.pageMem = {
		ok          : false,
		recovering  : false
	};
	this.selected = {
		itemId   : null,
		gameType : null,
		tr       : null
	};
	this.isLobbyPage = document.isLobby;
	this.loginDisp = {
		timer     : null,
		refresh   : 1000,
		logged_in : null
	};
	this.autoPopupAlert = false;
	this.lastClick = new Date().getTime();
	this.maxWindowsPopupAlert = false;
	this.login = {};
	this.openTableSettings = {
		dfltRules : {
			chkLogin         : true,
			trackWindow      : true,
			skipMaxWinCheck  : true,
			gameNameClue     : '',
			useOpener        : false
		},
		rules : {},
		gameType : null,
		itemType : null,
		itemId   : null
	};
	this.idle = false;
	this.applyFilters = true;
	this.connected = true;
}

StateClass.prototype.parseLogin = function() {

	var cookieVals = [];

	var cookie = get_cookie(document.login_cookie);

	var prevLoggedIn = this.login.logged_in;

	if (cookie) {
		cookieVals = cookie.split('|');
	}

	if (cookieVals.length != 19) {
		this.login = {
			logged_in         : false,
			login_status      : 'BAD_COOKIE',
			disp_login_status : ''
		};
		set_cookie(document.miniview_override_cookie, '', '', '/', '', '');
	} else if (cookieVals[1] != 'OB_OK') {
		this.login = {
			logged_in         : false,
			login_status      : cookieVals[1],
			disp_login_status : decodeCookieVal(cookieVals[13])
		};
		set_cookie(document.miniview_override_cookie, '', '', '/', '', '');
	} else {
		this.login = {
			logged_in         : true,
			login_status      : cookieVals[1],
			disp_login_status : decodeCookieVal(cookieVals[13]),
			cust_id           : cookieVals[0],
			ccy_code          : cookieVals[4],
			balance           : cookieVals[5],
			fp_balance        : cookieVals[6],
			points            : cookieVals[7],
			first_name        : cookieVals[8],
			nickname          : cookieVals[9],
			avatar            : cookieVals[10],
			disp_balance      : decodeCookieVal(cookieVals[12]),
			temp_auth         : cookieVals[2]  == '1' ? true : false,
			temp_reg          : cookieVals[3]  == '1' ? true : false,
			blocked           : cookieVals[14] == '1' ? true : false,
			league_opt_out    : cookieVals[15] == 'Y' ? true : false,
			vertical_chat     : cookieVals[16] == 'Y' ? true : false,
			launch_as_mini    : cookieVals[17] == 'Y' ? true : false,
			last_login        : cookieVals[18]
		};
	}

	// Detect change of login status
	if (typeof prevLoggedIn === 'boolean' && prevLoggedIn !== this.login.logged_in) {
		switch (this.login.logged_in) {
			case true:
			break;

			case false:
				Detail.onLogout();
			break;
		}
	}
}

// returns false if attempted to open window and failed; otherwise true.
StateClass.prototype.openTable = function(_gameType, _itemType, _itemId, _rules) {

	var settings = this.openTableSettings;

	if (typeof _gameType != 'undefined') {

		settings.gameType = _gameType;
		settings.itemType = _itemType;
		settings.itemId   = _itemId;

		// override default rules with the supplied ones
		for (var i in settings.dfltRules) {
			if (typeof _rules != 'undefined' && typeof _rules[i] != 'undefined') {
				settings.rules[i] = _rules[i];
			} else {
				settings.rules[i] = settings.dfltRules[i];
			}
		}
	}

	if (settings.rules.useOpener) {
		// don't try to use opener if there isn't one
		try {
			if (!window.opener || !window.opener.State) {
				settings.rules.useOpener = false;
			}
		} catch(e) {
			settings.rules.useOpener = false;
		}
	}

	if (settings.rules.chkLogin && !chkLogin(function() { State.openTable(); })) {
		return true;
	}

	// This is for opening a table popup in the AIR application.
	if (window.parentSandboxBridge) {
		window.parentSandboxBridge.popupTable(settings.gameType, settings.itemType, settings.itemId, get_cookie(document.secure_login_cookie));
		return true;
	}

	if (document._parentSandboxBridge) {
		document._parentSandboxBridge.popupTable(settings.gameType, settings.itemType, settings.itemId, get_cookie(document.secure_login_cookie));
		return true;
	}

	var windowId = settings.gameType + settings.itemId;

	if (settings.rules.trackWindow) {
		// check if this table is already open
		var win;
		if (settings.rules.useOpener) {
			win = window.opener.document.openWindows[windowId];
		} else {
			win = document.openWindows[windowId];
		}
		try {
			if (win && win.location && !win.closed) {
				win.focus();
				return true;
			}
		} catch(e) {
			if (settings.rules.useOpener) {
				window.opener.document.openWindows[windowId] = null;
			} else {
				document.openWindows[windowId] = null;
			}
		}
	}

	// If currently showing pop-up, don't try to open another window.
	if (this.maxWindowsPopupAlert) {
		return true;
	}

	// If FF, show warning when attempting to open too many windows
	if (!settings.rules.skipMaxWinCheck
	 && is_firefox()
	 && is_windows()
	 && typeof document.ff_max_windows != 'undefined'
	 && parseInt(document.ff_max_windows) != 'NaN'
	 && parseInt(document.ff_max_windows) > 0) {
		var numOpenWindows;
		if (settings.rules.useOpener) {
			numOpenWindows = window.opener.num_open_windows();
		} else {
			numOpenWindows = num_open_windows();
		}
		if (numOpenWindows >= parseInt(document.ff_max_windows)) {
			if (Nickname.showForm(
				'firefox_warning',
				function() { State.maxWindowsPopupAlert = false; State.openTable(); },
				function() { State.maxWindowsPopupAlert = false; },
				settings.rules.gameNameClue)
			) {
				this.maxWindowsPopupAlert = true;
				settings.rules.skipMaxWinCheck = true;
			}
			return true;
		}
	}

	if (settings.rules.useOpener) {
		return window.opener.State.openTableWork(settings, windowId);
	} else {
		return this.openTableWork(settings, windowId);
	}
}

StateClass.prototype.openTableWork = function(settings, windowId) {

	this.parseLogin();

	var pu_class,
	    launch_as_mini = this.login.launch_as_mini,
		mini_override  = get_cookie(document.miniview_override_cookie);
	if (mini_override != null && mini_override != '') {
		launch_as_mini = (mini_override == 'Y');
	}
	if (launch_as_mini) {
		pu_class = 'pu_mini_game';
	} else {
		pu_class = this.login.vertical_chat ? 'pu_large_game' : 'pu_small_game';
	}

	var url = [document.scgiURL, '?action=launch_tab&game_type=', settings.gameType, '&item_type=', settings.itemType, '&item_id=', settings.itemId, '&guid=', document.guid].join(''),
		win = pu(url, pu_class, 'flash_' + windowId);

	if (win) {
		if (settings.rules.trackWindow) {
			// store a reference to the popup
			document.openWindows[windowId] = win;
		}
		return true;

	} else {
		return false;
	}
}

StateClass.prototype.doSync = function(which, gameType, itemId) {

	var ret = {};
	var tr  = State.centre.List.getSelected().tr;
	var id  = State.centre.List.getSelected().id;

	if (tr == null
	 || tr.t == null
	 || tr.gameType != gameType
	 || id != itemId
	 || !Detail.pub.item.ok
	 || Detail.pub.gameType != gameType
	 || Detail.pub.itemId != itemId) {
		return ret;
	}

	var centre = this.centre.pub.name;

	if (gameType == 'S') {
		if (which == 'Detail') {
			if (centre == 'TableList') {
				TableList.renderSyncTR(tr, {
					num_seated : Detail.pub.item.num_seated
				});
			} else if (centre == 'MySelns') {
				MySelns.renderSyncTR(tr, {
					num_playing : Detail.pub.item.num_seated
				});
			}
		} else if (which == 'TableList') {
			ret = {
				num_seated : Detail.pub.item.num_seated
			};
		} else if (which == 'MySelns') {
			ret = {
				num_playing : Detail.pub.item.num_seated
			};
		}

	} else if (gameType == 'T') {
		var newest = Detail.pub.item.rs_time > TnmtList.pub.rsTime ? 'Detail' : 'TnmtList';
		if (which == 'Detail') {
			if (centre == 'TnmtList') {
				if (newest == 'Detail') {
					TnmtList.renderSyncTR(tr, {
						reg_number : Detail.pub.item.reg_number,
						status     : Detail.pub.item.status
					});
				} else if (newest == 'TnmtList') {
					ret = {
						reg_number : TnmtList.List.pub.items[tr.t].reg_number,
						status     : TnmtList.List.pub.items[tr.t].status
					};
				}
			} else if (centre == 'MySelns') {
				MySelns.renderSyncTR(tr, {
					num_playing : Detail.pub.item.reg_number
				});
			}
		} else if (which == 'TnmtList') {
			if (newest == 'Detail') {
				ret = {
					reg_number : Detail.pub.item.reg_number,
					status     : Detail.pub.item.status
				};
			} else if (newest == 'TnmtList') {
				Detail.renderSyncTnmt({
					reg_number    : TnmtList.List.pub.items[tr.t].reg_number,
					status : TnmtList.List.pub.items[tr.t].status
				});
			}
		} else if (which == 'MySelns') {
			ret = {
				num_playing : Detail.pub.item.reg_number
			};
		}
	}

	return ret;
}

/*  Update connected state.  If it has changed, do something.
 */
StateClass.prototype.setConnected = function(state) {

	if(typeof state === 'boolean' && this.connected !== state) {

		this.connected = state;

		if (this.connected) {
			warnfire('StateClass: connected');

			// If game list showing, force a poll
			if(this.centre.pub.name === 'TableList' || this.centre.pub.name === 'TnmtList') {
				printfire('StateLib: forcing', this.centre.pub.name, 'poll');
				this.centre.Req.poll();
			}
		}
		else {
			warnfire('StateClass: disconnected');

			if (typeof document.push === 'object') document.push.allow(false);
		}
	}
}

