var LobbyTooltip = Class.create(CasinoTooltip, {
	_show: function() {
		$$('div.casino-tooltip').invoke('hide');
		if (this.options.content)
			this.text = this.options.content;

		// setup dom object
		this.tooltip = new Element('div').addClassName('casino-tooltip').setStyle({position: 'absolute', width: this.options.width+'px', display: 'none', zIndex: 999});
		if (this.options.className!='')
			this.tooltip.addClassName(this.options.className);
		this.tooltip.update(this.options.template.evaluate({text: this.text, position: this.options.position}));
		$$('body').first().insert(this.tooltip);
		this._reposition();
		if(document.viewport.getHeight() - this.element.viewportOffset()[1] < 150 && !Prototype.Browser.Opera){
			this.tooltip.setStyle({marginTop: '-170px'});
		}

		if(Prototype.Browser.IE)
			this.options.animateDuration = 0;

		new Effect.Parallel([
			new Effect.Move(this.tooltip, { sync: true, y: this.moveTop, x: this.moveLeft, mode: 'relative' }), 
			new Effect.Appear(this.tooltip, { sync: true}) 
		], { 
			duration: this.options.animateDuration,
			delay: this.options.delay
	    });
	}
});

var lobbyjar = new CookieJar({
	expires: 2592000, // 30 days
	path: '/'
});

var casinoLobby = function(){
	return {
		/**
		 * translations/options/order
		 */
		translations: {
			locale: 'en',
			tournament: undefined,
			sort1: undefined,
			sort2: undefined,
			sort3: undefined,
			specialgame: undefined,
			maxwin: undefined,
			newgame: undefined,
			minigames: undefined,
			links: { allgames: undefined, videoslots: undefined, slots: undefined, tablegames: undefined, classicvideopokers: undefined, othergames: undefined }
		},
        options: {
            groupUid: undefined,
            catUid: undefined,
            gameUid: undefined,
            gameSystem: undefined,
            gameDnm: undefined,
			popup: undefined
        },
		order: ['videoslots', 'slots', 'tablegames', 'classicvideopokers', 'othergames'],

		/**
		 * Lobby: popup handler
		 */
		_popup: function(element){
			if(casinoLobby.options.popup != undefined)
				casinoLobby.options.popup.close();

			var popWidth = 320, popHeight = 240, popDim = element.className.replace('popup ', '').split('_');
            if(popDim.length == 3){
				popWidth = popDim[1];
				popHeight = popDim[2];
			}
			//var split = this.href.split('/');
			//var gameid = (split[split.length-1] == 'CM_01') ? split[split.length-2].replace('_sw', '') + '_sw' : split[split.length-2];
			var frame = element.href + '&fullscreen=1&popup=1';

            if(frame.indexOf('/casino-games/') > 0)
                frame = element.href.replace('/casino-games/', '/popup/');

			window.open(frame, 'CasinoEuro', 'width=' + popWidth + ', height=' + popHeight + ', resizable=no,scrollbars=no');
		},
		/**
		 * Lobby: expand and animate denominations
		 */
		_toggleDenomination: function(){
			$$('#lobby div.list li.denomination > a:first, div.minilobby div.list li.denomination > a:first').invoke('observe', 'click', function(e){
				Event.stop(e);
				var self = this;
				if(!self.hasClassName('block')){
					self.addClassName('block');
					if(self.hasClassName('expand')){
						self.removeClassName('expand');
						new Effect.BlindUp(self.next('ul'), {duration: 0.5, afterFinish: function(effect){ self.removeClassName('block') } });
					}else{
						self.addClassName('expand');
						new Effect.BlindDown(self.next('ul'), {duration: 0.5, afterFinish: function(effect){ self.removeClassName('block') } });
					}
				}
				$$('div.casino-tooltip').invoke('hide');
			});
		},
		/**
		 * Lobby: tooltips handler
		 */
		_tooltips: function(){
			$$('#lobby .list > ul > li > a, div.minilobby .list > ul > li > a').each(function(el){
				if(el.hasClassName('tooltip'))
					return;
				el.addClassName('tooltip');

				// webtrends : Link clicks
				el.observe('click', function(){
					var menuItemName = (el.innerHTML).unescapeHTML().replace(/^\s+|\s+$/, '').replace('&nbsp;', '').replace(/\W+$/,'');
					var menuItemLink = 'link-click/casino-lobby/' + menuItemName.toLowerCase().replace(' ', '-');
					dcsMultiTrack('DCS.dcsuri',menuItemLink,'WT.ti',menuItemLink,'WT.z_link_page','casino/play','WT.z_link_type','play','WT.z_link_place','casino-lobby','WT.z_link_name',menuItemName,'WT.z_link_event','clicked','WT.si_x','','WT.si_n','','WT.z_error_page','','WT.z_error_type','','WT.z_error_message','','WT.z_login','','WT.z_register','','WT.z_sorting','','WT.z_tab','');
				});

				var gameJackpot, gameBonus, gameTitle, gameLines, gameNew, gameTournament, left, jackpotValue;
				var parent = el.up('li');

				var lines = parent.getAttribute('title');
				parent.setAttribute('title', '');

				var gameId = parent.id.replace('game_', '');
				var categoryName = el.up('div.category').down('h3').innerHTML;
				if(parent.hasClassName('new')){
					gameTitle = '<h3 class="new">' + el.innerHTML + '</h3>';
					gameNew = '<p class="new">' + casinoLobby.translations.newgame + '</p>';
				}else{
					gameTitle = '<h3>' + el.innerHTML + '</h3>';
				}
				if(lines != null) gameLines = '<p>' + lines + '</p>';
				if(parent.hasClassName('bonus')) gameBonus = '<p class="bonus">' + casinoLobby.translations.specialgame + '</p>';
				if(parent.getAttribute('rel') != null && parent.getAttribute('rel') != ''){
					jackpotValue = casinoLobby._formatValue(parseInt(parent.getAttribute('rel')));
					gameJackpot = '<p class="jackpot">' + casinoLobby.translations.maxwin + ' ' + jackpotValue + '&euro;</p>';
				}
				if(casinoLobby.translations.tournament != undefined)
					gameTournament = '<p class="tournament">' + casinoLobby.translations.tournament + '</p>';


				left = (el.up('ul:nth-child(4)') != null || el.up('ul:nth-child(5)') != null ? -200 : 150);
				if(Prototype.Browser.IE6){ // because of incorrect selects behaviour
					if(el.up('ul:nth-child(3)') != null || el.up('ul:nth-child(5)')) left -= 210;
					else if((el.up('ul:nth-child(2)') != null || el.up('ul:nth-child(4)'))) left -= 60;
				}

				// some weird ie security bug + rounded corners option
				tooltipHTML = new Template(
					'<div class="image"' + (Prototype.Browser.IE ? '><img src="/images/games/#{id}.jpg" />' : ' style="background-image: url(/images/games/#{id}.jpg)">') + '</div>' +
						'<div class="info #{id}">' +
						'<p>#{category}</p>' +
						'#{title}#{lines}#{star}#{jackpot}#{bonus}#{tournament}' +
					'</div>'
				);

				new LobbyTooltip(el, {
					template: '<div class="tooltip-content #{position}">#{text}</div>',
					position: 'below',
					className: 'lobbyTooltip',
					width: 384,
					topOffset: 0,
					leftOffset: left,
					delay: 0.5,
					animateDuration: 0.3,
					movement: 0,
					content: tooltipHTML.evaluate({id: gameId, category: categoryName, title: gameTitle, lines: gameLines, star: gameNew, jackpot: gameJackpot, bonus: gameBonus, tournament: gameTournament})
				});

			});
		},
		/**
		 * Lobby: ajax request
		 * onUninitialised: 0
		 * onLoading: 1 
		 * onLoaded: 2 
		 * onInteractive: 3
		 * onComplete: 4
		 */
		_ajaxCall: function(catUID, gameSort){
			var request = '/' + casinoLobby.translations.locale + '/json/newlobby/';
			if((catUID == 'classicvideopokers' || catUID == 'premiumvideopokers' || catUID == 'videopokers') && gameSort == false)
				request += '?catUID=classicvideopokers';
			else
				request += (catUID == 'all-games') ? '' : '?catUID=' + catUID;

			var lobbyCategories = new Element('div', {id: 'lobbyCategories'});

			if(gameSort && catUID != '')
				ajaxcasino.setLoading($('lobby' + catUID), 'sort_' + catUID + '_loading');
			else
				ajaxcasino.setLoading($('lobbyCategories'), 'lobbyCategoriesLoading');

			new Ajax.Request(request , {
				method: 'get',
				asynchronous: false,
				onSuccess: function(response) {
					var respJSON = response.responseText.evalJSON();

					// get the right sorting order ! fix JSON and strip unecessary data instead !
					var catsort = [0];
					if(catUID == '' || catUID == 'all-games'){
						catsort = [];
						casinoLobby.order.each(function(uid){
							respJSON.categories.each(function(cat, c){
								if(cat.uid == uid) catsort.push(c);
							});
						});
					}

					catsort.each(function(cat){
						var category = respJSON.categories;
                        if(category.length > 0) category = category[cat];

						var categoryWrap = new Element('div', {'class': 'category', id: 'lobby' + category.uid});

						//' + (gameSort == 2 ? ' selected="selected"' : '') + '
						var lobbyHeader = new Element('div', {'class': 'header'}).update(
							'<h3>' + category.name + '</h3>' +
							'<select name="' + category.uid + '_sort">' +
								'<option value="1">' + casinoLobby.translations.sort1 + '</option>' +
								'<option value="2">' + casinoLobby.translations.sort2 + '</option>' +
								'<option value="3">' + casinoLobby.translations.sort3 + '</option>' +
							'</select>'
						);
						lobbyList = new Element('div', {'class': 'list'});

						var gameRow, gameWrap, gameClass, elements = 1, rest = 0, i = 0, step = 0, gameDnm;
						var gameCount = category.gameGroups.length;

						if(gameCount > 5){
							elements = Math.floor(gameCount / 5);
							rest = gameCount - (elements * 5);
							step = rest;
						}

						// alphabetic sorting option
						if(gameSort == 2){
							category.gameGroups.sort(function(a, b) {
								var x = a.name.toLowerCase();
								var y = b.name.toLowerCase();
								return ((x < y) ? -1 : ((x > y) ? 1 : 0));
							});
						}else if(gameSort == 3){
							category.gameGroups.sort(function(a, b) {
								var x = a.popularity;
								var y = b.popularity;
								return ((x > y) ? -1 : ((x < y) ? 1 : 0));
							});
						}

						var ulWrap = [new Element('ul'), new Element('ul'), new Element('ul'), new Element('ul'), new Element('ul')];   
						category.gameGroups.each(function(group, index){
							var gameClass = '', popup = '', jackpot = 0;
							if(group.newGame) gameClass = 'new';
							if(group.jackpotValue > 0){
								gameClass = 'jackpot';//(gameClass == '') ? 'jackpot' : gameClass;
								jackpot += group.jackpotValue;
							}
							if(group.bonus) gameClass += ' bonus';

							// denomination!
							if(group.games.length > 1){
								gameRow = new Element('li', {id: group.uid, 'class': 'denomination' + (gameClass != '' ? ' ' + gameClass : '')}).insert(new Element('a', {href: '#'}).update(group.name));
								if(jackpot > 0) gameRow.setAttribute("rel", jackpot);
								gameWrap = new Element('ul', {style: "display: none"});
								gameDnm = '';

								group.games.each(function(dnm){
									// check & add popup class
									popup = '';
									if(dnm.popup || window.location.href.indexOf('live-casino') > 0)
										popup += 'popup dim_' + dnm.width + '_' + dnm.height;

									gameWrap.insert(new Element('li').update(new Element('a', {href: casinoLobby._makeGameURL(group.formatedName, category.uid, dnm.formatedGameText, dnm.uid, dnm.systemUid), 'class': popup}).update(dnm.gameText.replace('?', '&euro;'))));
									gameDnm += "; " + dnm.gameText.replace('?', '&euro;');
								});

								// insert
								if(gameDnm != '')
									gameRow.setAttribute('title', gameDnm.substr(2));
								ulWrap[i].insert(gameRow.insert(gameWrap));
							}else{
								// check & add popup class
								if(group.games[0].popup || window.location.href.indexOf('live-casino') > 0)
									popup += 'popup dim_' + group.games[0].width + '_' + group.games[0].height;

								ulWrap[i].insert(new Element('li', {id: group.uid, 'class': gameClass, rel: (jackpot > 0) ? jackpot : '', title: group.games[0].gameText.replace('?', '&euro;')}).update(new Element('a', {href: casinoLobby._makeGameURL(group.formatedName, category.uid, null, group.games[0].uid, group.games[0].systemUid), 'class': popup}).update(group.name)));
							}
							// create next container
							if((index + 1 - (rest < 1 ? step : 0)) % (elements + (rest > 0 ? 1 : 0)) == 0 && i < 4){ ++i; --rest; }
						});

						// insert into appropriate container
						categoryWrap.insert(lobbyHeader);
						ulWrap.each(function(col){
							lobbyList.insert(col);
						});

						if(gameSort){
							$$('#lobby' + category.uid + ' .list').first().update(lobbyList);
							ajaxcasino.endLoading('sort_' + category.uid + '_loading');
							casinoLobby._liveUpdate();
						}else{
							categoryWrap.insert(lobbyList);
							lobbyCategories.insert(categoryWrap);
							ajaxcasino.endLoading('lobbyCategoriesLoading');
						}
					});

					if(!gameSort){
						$('lobbyCategories').replace(lobbyCategories);
						casinoLobby._liveUpdate();
						casinoLobby._sortGames();
					}

				},
				onFailure: function() {
					ajaxcasino.endLoading(gameSort ? 'sort_' + category.uid + '_loading' : 'lobbyCategoriesLoading');
					return null;
				}
			});
		},
		/**
		 * Lobby: switching categories
		 */
		_switchMainTabs: function(self){
			if(!self.hasClassName('active')){

				var option = self.up().className;
				var id = option.replace('opt-', '');
				if(lobbyHistory) lobbyHistory.setValue(0, id);

				self.up('ul').adjacent('.active').invoke('removeClassName', 'active');
				self.addClassName('active');
				lobbyjar.put("lobby-tab", option);

				var tabs = ['all-games', 'videoslots', 'slots', 'tablegames', 'videopokers', 'othergames'];
				var currentTab = tabs[id-1];

				// webtrends : Tabs click
				dcsMultiTrack('DCS.dcsuri','link-click/casino-lobby/' + currentTab,'WT.ti','link-click/casino-lobby/' + currentTab,'WT.z_link_page','casino/play','WT.z_link_type','play','WT.z_link_place','casino-lobby','WT.z_link_name','','WT.z_link_event','clicked','WT.si_x','','WT.si_n','','WT.z_error_page','','WT.z_error_type','','WT.z_error_message','','WT.z_login','','WT.z_register','','WT.z_sorting','','WT.z_tab', currentTab);

				if($$('#lobbyCategories .category').length > 2){
					$('lobby').className = '';
					$('lobby').addClassName(option);
				}else{
					$('lobby').className = '';
					$('lobby').addClassName(currentTab);
					casinoLobby._ajaxCall(currentTab, false);
				}

			}
		},
		/**
		 * Lobby: sorting games
		 */
		_sortGames: function(){
			$$('#lobby .category select, div.minilobby .category select').invoke('observe', 'change', function(el){
				var id = this.up('.category').id;
				var type = this.getValue();
				var option = id + '_' + type;

				if(lobbyjar.get("lobby-sort") != null){
					var options = lobbyjar.get("lobby-sort").split(',');
					var edit = false;
					for(var i = 0; i < options.length; i++){
						if(options[i].substr(0, options[i].length-2) == option.substr(0, option.length-2)){
							edit = true;
							if(type == 1)
								options.splice(i, 1);
							else
								options[i] = option;
						}
					}
					if(type != 1 && !edit) options.push(option);
					option = options.join(",");
				}
				var catName = id.replace('lobby', '');

				// webtrends : Sorting tag
				dcsMultiTrack('DCS.dcsuri','sort-change/casino-lobby/'+catName + '-' + type,'WT.ti','sort-change/casino-lobby/'+catName + '-' + type,'WT.z_link_page','casino/play','WT.z_link_type','play','WT.z_link_place','casino-lobby','WT.z_link_name','','WT.z_link_event','clicked','WT.si_x','','WT.si_n','','WT.z_error_page','','WT.z_error_type','','WT.z_error_message','','WT.z_login','','WT.z_register','','WT.z_sorting',catName + '-' + type,'WT.z_tab','');

				casinoLobby._ajaxCall(catName, type);
				lobbyjar.put("lobby-sort", option);
			});
		},
		/**
		 * Lobby: switching tabs
		 */
		_switchWinnersTabs: function(){
			$$('#lobbyWinners li.empty').each(function(el){
				casinoLobby._loadJackpotsTab();
				el.removeClassName('empty');
			});
			$$('#lobbyWinners li.hide').each(function(el){
				var el2 = el.siblings().first();
				[el, el2].invoke('toggleClassName', 'hide');
				new Effect.Appear(el2.down('table'), {duration: 0.5, from: 1.0, to: 0});
				new Effect.Appear(el.down('table'), {duration: 0.5, from: 0, to: 1.0});
			});
		},
		/**
		 * Lobby: load winners tab from xml
		 */
		_loadWinnersTab: function(){
			ajaxcasino.setLoading($('lobbyWinners'), 'lobbyWinners_loading');

			new Ajax.Request('/' + casinoLobby.translations.locale + '/xml/currentOverview.xml.jsp' , {
				method: 'get',
				asynchronous: false,
				onSuccess: function(response) {
					var resp = response.responseXML.getElementsByTagName("latestwins")[0];
					var winNodes = resp.getElementsByTagName("win");
					var winnersWrapper = $$('#lobbyWinners li:nth-child(1)')[0];
					var winnersList = '';

					for (var i = 0; i < winNodes.length; i++) {
						if(i > 6) break;
						winnersList += '<tr class="' + (i % 2 == 0 ? 'even' : 'odd') + '">' +
							'<td class="col-1"><img src="/images/iso-flags/' + winNodes[i].getAttribute("countrycode") + '.gif" alt="' +winNodes[i].getAttribute("countrycode") + '" /></td>' +
							'<td class="col-2">' + (winNodes[i].getAttribute("name").length > 15 ? winNodes[i].getAttribute("name").substring(0, 15) : winNodes[i].getAttribute("name")) + '</td>' +
							'<td class="col-3"><a href="' + winNodes[i].getAttribute("link") + '">' + winNodes[i].getAttribute("game") + '</a></td>' +
							'<td class="col-4">&euro; ' + winNodes[i].getAttribute("value") + '</td>' +
						'</tr>';
					}
					Element.insert(winnersWrapper, '<table cellpadding="0" cellspacing="0"><tbody>' + winnersList + '</tbody></table>');
					ajaxcasino.endLoading('lobbyWinners_loading');
				},
				onFailure: function() {
					ajaxcasino.endLoading('lobbyWinners_loading');
					return null;
				}
			});
		},
		/**
		 * Lobby: load jackpot tab from json
		 */
		_loadJackpotsTab: function(){
			ajaxcasino.setLoading($('lobbyWinners'), 'lobbyWinners_loading');

			new Ajax.Request('/' + casinoLobby.translations.locale + '/json/newjackpots/' , {
				method: 'get',
				asynchronous: false,
				onSuccess: function(response) {
                    var respJSON = response.responseText.evalJSON();
                    var resp = respJSON.gameGroupsWithJackpots;
    
					var jackpotsWrapper = $$('#lobbyWinners li:nth-child(2)')[0];
					var jackpotsList = '';

                    // sort by value
					resp.sort(function(a, b) {
						var x = a.jackpotValue;
						var y = b.jackpotValue;
						return ((x > y) ? -1 : ((x < y) ? 1 : 0));
					});

					resp.each(function(jackpot, i){
						if(i > 4) return;
						jackpotsList += '<tr class="' + (i % 2 == 0 ? 'even' : 'odd') + '">' +
							'<td class="col-5"><a href="' + casinoLobby._makeGameURL(jackpot.formatedName, null, null, jackpot.games[0].uid, null) + '">' + jackpot.name+ '</a></td>' +
							'<td class="col-6">&euro; ' + casinoLobby._formatValue(jackpot.jackpotValue) + '</td>' +
						'</tr>';
					});
					Element.insert(jackpotsWrapper, '<table cellpadding="0" cellspacing="0"><tbody>' + jackpotsList + '</tbody></table>');
					ajaxcasino.endLoading('lobbyWinners_loading');
				},
				onFailure: function() {
					ajaxcasino.endLoading('lobbyWinners_loading');
					return null;
				}
			});	
		},
		/**
		 * Lobby: format jackpot value
		 */
		_formatValue: function(nStr){
			nStr += '';
			x = nStr.split('.');
			x1 = x[0];
			x2 = x.length > 1 ? '.' + x[1] : '';
			var rgx = /(\d+)(\d{3})/;
			while (rgx.test(x1)) 
				x1 = x1.replace(rgx, '$1' + ',' + '$2');

			return x1 + x2;
		},
		/**
		 * Lobby: create (nice) game url 
		 */
        _makeGameURL: function(name, group, dnm, game, system){
            var gameURL = '/' + casinoLobby.translations.locale + '/casino-games';
            gameURL += '/' + casinoLobby.translations.links[(group == null ? 'allgames' : group)] + '/' + name + (dnm == null ? '' : '/' + dnm);

            return gameURL;  
        },
		/**
		 * Lobby: update functions after making actions on the lobby
		 */
		_liveUpdate: function(){
			casinoLobby._toggleDenomination();
			casinoLobby._tooltips();
            $$('#lobbyCategories a.popup, div.minilobby a.popup, #sideGames a.popup').invoke('observe', 'click', function(e){
				Event.stop(e);
                casinoLobby._popup(this);
            });
			//this._sortGames();
		},
		/**
		 * Gamepage: show modal box with game rules
		 */
		_gameRules: function(){
            Modalbox.show($('gameRules'), {
                title: '',
                overlayClose: true,
                height: 420,
                width: 600
            });
        },
		/**
		 * Gamepage: make json call and insert game data into selectbox
		 */
		_populateGameGroup: function(){
            var selector = $('gameSelector');
            if (selector !== null) {
	            if(selector.hasClassName('loaded'))
	                return;
	
				ajaxcasino.setLoading(selector, 'gameSelector_loading');
				new Ajax.Request('/' + casinoLobby.translations.locale + '/json/newlobby/' , {
					method: 'get',
					asynchronous: false,
					onSuccess: function(response) {
						var respJSON = response.responseText.evalJSON();
	                    var option = undefined, optgroup = undefined, dnmValues = 0, dnmList = undefined, showDnm = '', category = undefined;
	                    var gameSelect = new Element('select');
	                    var gameInfo = new Element('div', {id: 'gameGroupInfo'});
	                    var dnmList = new Element('ul');
	                    var miniGames = new Element('optgroup', {label: casinoLobby.translations.minigames});
	                    Element.insert(gameSelect, miniGames);
	
						var catsort = [];
						casinoLobby.order.each(function(uid){
							respJSON.categories.each(function(cat, c){
								if(cat.uid == uid) catsort.push(c);
							});
						});
	
						catsort.each(function(c, i){
							category = respJSON.categories[c];
	                        // remove resource errors
	                        if(category.name[0] == '<' || category.id == 5)
	                            return;
	
							// alphabetic sorting
							category.gameGroups.sort(function(a, b) {
								var x = a.name.toLowerCase();
								var y = b.name.toLowerCase();
								return ((x < y) ? -1 : ((x > y) ? 1 : 0));
							});
	
	                        optgroup = new Element('optgroup', {label: category.name});
							category.gameGroups.each(function(group, index){
	                            // remove resource errors
	                            if(group.name[0] == '<')
	                                return;
	                            dnmList = new Element('ul', {id: 'sel_' + dnmValues});
	                            group.games.each(function(dnm, dIndex){
	                                Element.insert(dnmList, '<li><a ' + (dnm.popup ? ' class="popup dim_' + dnm.width + '_' + dnm.height + '"' : '') + ' href="' + casinoLobby._makeGameURL(group.formatedName, group.categoryUid, (dIndex == 0 ? null : dnm.formatedGameText), dnm.uid, dnm.systemUid) + '">' + dnm.gameText + '</a></li>');
	                            });
	                            
	                            option = new Element('option', {value: dnmValues}).update(group.name);
	                            gameInfo.insert(dnmList);
	
	                            if(group.uid == casinoLobby.options.groupUid) {
	                                option.selected = 'true';
	                                showDnm = 'sel_' + dnmValues;
	                            }
	                            Element.insert((group.games[0].popup ? miniGames : optgroup), option);
	                            dnmValues++;
							});
	                        Element.insert(gameSelect, optgroup);
						});
	                    
	                    gameSelect.observe('change', function(e){
	                        var element = $('sel_' + this.getValue());
	                        element.siblings().each(function(sibling){
	                            if(sibling.hasClassName('active')) sibling.removeClassName('active');
	                        });
	                        element.addClassName('active');
	                        element.select('.popup').invoke('observe', 'click', function(e){
	                            Event.stop(e);
	                            casinoLobby._popup(this);
	                            //window.location = '/' + casinoLobby.translations.locale + '/casino-games';
	                        });
	                        var open = element.select('a');
	                        if(open.length == 1){
	                            if(open[0].hasClassName('popup'))
	                                casinoLobby._popup(open[0]);
	                            else
	                                window.location = open[0].href;
	                        }
	                    });
	                    selector.update('');
	                    selector.insert(gameSelect);
	                    selector.insert(gameInfo);
	                    selector.addClassName('loaded');
	                    
	                    $(showDnm).addClassName('active');
	                    ajaxcasino.endLoading('gameSelector_loading');
					},
					onFailure: function() {
						ajaxcasino.endLoading('gameSelector_loading');
						return null;
					}
				});	
            }
		},
		/**
		 * Gamepage: initialize
		 */
        gamepage: function(){
			// scroll & offset ? $('freePlay').scrollTo();
            //populateGameGroup();
			if(document.viewport.getHeight() < 650 && $('gameWrapper'))
				new Effect.ScrollTo('contentWrapper', { duration: 0.5, offset: 105 });

			['username', 'password'].each(function(el){
				if($(el)) Element.observe(el, 'focus', function(){ this.value = ''; });
			});

            var btnMaximize = $('gIcon-maximise');
            if(btnMaximize){
                btnMaximize.observe('click', function(e){
                    Event.stop(e);
					if(casinoLobby.options.popup != undefined)
						casinoLobby.options.popup.close();

					var fullHeight = screen.height - 100;
					var fullWidth =  Math.round((fullHeight *$('divGame').getWidth() ) / $('divGame').getHeight());

                    var frameURL = window.location.href.replace('/casino-games/', '/fullscreen/');
                    casinoLobby.options.popup = window.open(frameURL, 'CasinoEuro', 'width=' + fullWidth + ', height=' + fullHeight + ', resizable=no,scrollbars=no,toolbar=0,menubar=0,location=0,resizable=0,directories=0,status=0');
					casinoLobby.options.popup.focus();
                    window.location = '/' + casinoLobby.translations.locale + '/casino-games';
                });
            }

            var rulesBtn = $('gIcon-info');
            if(rulesBtn){
                $(rulesBtn).observe('click', function(e){
                    Event.stop(e);
                    casinoLobby._gameRules();
                });
            }

            var liveChat = $('liveChat');
            if(liveChat){
                $(liveChat).observe('click', function(e){
                    Event.stop(e);
                    window.open(this.href, 'LiveChat', 'width=800,height=600,resizable=yes');
                });
            }

            var gamePassword = $('gamePassword');
            if(gamePassword){
                gamePassword.observe('click', function(e){
                    Event.stop(e);
                    Modalbox.show('/' + casinoLobby.translations.locale + '/game/password.jsp', {
                        title: '',
                        overlayClose: true,
                        height: 420,
                        width: 600
                    });
                });
            }

            var flagsContainer = $('gameFlags');
            if(flagsContainer){
                flagsContainer.select('.active')[0].observe('click', function(e){
                    Event.stop(e);
                    if(flagsContainer.hasClassName('hover'))
                        flagsContainer.removeClassName('hover');
                    else
                        flagsContainer.addClassName('hover');
                });
                Element.observe(document.body, 'click', function(e){
                    if(flagsContainer.hasClassName('hover'))
                        flagsContainer.removeClassName('hover');
                });
            }

            //var selector = $('gameSelector');
            //if(selector) selector.observe('mouseover', this._populateGameGroup);
			casinoLobby._populateGameGroup();
            
            $$('#gameThumbs a.popup').invoke('observe', 'click', function(e){
				Event.stop(e);
                casinoLobby._popup(this);
            });
            
            // listen for the quickDeposit:closed event and reload game balance 
            document.observe('quickDeposit:closed', function() {
            	$$('#gameBox embed').each(function(g){
            		
            		if (g.reloadbalance != null) {
            			g.reloadbalance();
            		}
            	});
            	
            	
            });
		},
		/**
		 * Lobby: initialize
		 */
		init: function() {
			// main tabs
			$$('#lobbyTabs li:not([class="live-casino"]) a').invoke('observe', 'click', function(e){
				Event.stop(e);
				casinoLobby._switchMainTabs(this);
			});

			// automatic tabs switching interval = 5sec
			var autoSwitch = setInterval(casinoLobby._switchWinnersTabs, 5000);

			// winners/jackpots tab click
			$$('#lobbyWinners li > a').invoke('observe', 'click', function(e){
				Event.stop(e);
				if(this.up().hasClassName('hide')){
					casinoLobby._switchWinnersTabs();
					clearInterval(autoSwitch);
					//setTimeout(autoSwitch, 10000);
				}
			});

			// init
			this._liveUpdate();
			this._sortGames();
			this._loadWinnersTab();
		}
	}
}();