// ****************************************************************************
// Constants:
// ****************************************************************************
var is_ie = (navigator.userAgent.indexOf('MSIE') >= 0) ? 1 : 0;
var is_ie5 = (navigator.appVersion.indexOf("MSIE 5.5")!=-1) ? 1 : 0;
var is_opera = ((navigator.userAgent.indexOf("Opera6")!=-1)||(navigator.userAgent.indexOf("Opera/6")!=-1)) ? 1 : 0;
var is_netscape = (navigator.userAgent.indexOf('Netscape') >= 0) ? 1 : 0;
var sessionTimeOut = 5;
var bFlag = false;
var popUpPreview = null;

// ****************************************************************************
// Game Translations
// ****************************************************************************
// Service which fetches the labels from the translation file.
function loadGameLabels() 
{
	var responseHandler = new LabelsHandler()
	var ajaxService = new AjaxService(responseHandler);
	ajaxService.GetRequest("/config/translation/games/gameLabels.xml");
	ajaxService = null;
	responseHandler = null;
}

// ****************************************************************************
// Makes a heartbeat request
// ****************************************************************************

function keepSessionAlive() {    
    var options = {
        type: "POST",
        url: "/misc/games/webservices/sessionKeepAlive.ashx",
		data: '',
        success: function(responseCode) {
            if (responseCode == 1) 
                GameSessionServiceHandler();                
            else                 
                mainSessionLoggedOut();               
        },
        error: function() {
            mainSessionLoggedOut();            
        }
    }
        jQuery.ajax(options);
}

// Resets the keepalive when heartbeat response received.
function GameSessionServiceHandler() {
	this.inheritFrom = ResponseHandlerBase;
	this.inheritFrom();
	setTimeout("keepSessionAlive()", (60000 * sessionTimeOut));	
}

function initialiseKeepAlive() 
{
	setTimeout("keepSessionAlive()", (60000 * sessionTimeOut));
}

function mainSessionLoggedOut() {
    alert(service.labels.mainSessionLoggedOut);
    window.close();
}
// ****************************************************************************
// Functions for the launching games from the dropdown list
// ****************************************************************************
function generateGameHref(redirectHref, className, rel)
{
	if (className == 'popup') {
		if (rel != null) {
			var relSplit = rel.split(" ");
			var attributes = "width=" + relSplit[1] + ",height=" + relSplit[2] + ",resizable=yes,scrollbars=yes,status=no,location=no,toolbar=no";
			popUp(redirectHref, relSplit[0], attributes);
		}
	} else {						
		location.href = redirectHref;
	}	
}

function launchGameDropdown()//dropdown)
{
	var dropdown = document.getElementById("gameDropdown"); 
	var selectionOption = dropdown.options[dropdown.selectedIndex];	
	generateGameHref(selectionOption.value, selectionOption.className, selectionOption.getAttribute("rel"));	
}

// ****************************************************************************
// Add To Game Cookie
// ****************************************************************************
function addToMyGames(gameId, gameName) 
{
	var myGamesCookie = getCookie("myGames");
	var ar;
	var arTmp = new Array();
	var y = 0;
	
	if (myGamesCookie != null) {
		ar = myGamesCookie.split('/');				
		for (var x = 0; x < ar.length; x++) {
			if (ar[x] != gameId) {
				arTmp[y] = ar[x];
				y++;
			} else {
				return;
			}
		}				
	}
	arTmp[y] = gameId;
	
	myGamesCookie = arTmp.join('/');
	saveGamesCookie(myGamesCookie);
	
	// hide add to games link
	showPreview(false, 'addGameToMyGames');	
	
	alert( service.labels.myGamesAdded.replace("[PLACEHOLDER]", gameName) );
}

// ******************
// Add to Game Cookie - modified version of addToMyGames
// ******************
function addToMyGames2(gameId, gameName) 
{
	var myGamesCookie = getCookie("myGames");
	var ar;
	var arTmp = new Array();
	var y = 0;
	
	if (myGamesCookie != null) {
		ar = myGamesCookie.split('/');				
		for (var x = 0; x < ar.length; x++) {
			if (ar[x] != gameId) {
				arTmp[y] = ar[x];
				y++;
			} else {
				return;
			}
		}				
	}
	arTmp[y] = gameId;
	
	myGamesCookie = arTmp.join('/');
	saveGamesCookie(myGamesCookie);
	
	return true;
}

function removeFromMyGames(gameId, gameName) 
{
	if (confirm(service.labels.removalConfirmation)) {
		var myGamesCookie = getCookie("myGames");
		var ar;
		var arTmp = new Array();	
		var y = 0;

		if (myGamesCookie != null) {
			ar = myGamesCookie.split('/');
			for (var x = 0; x < ar.length; x++) {
				if (ar[x] != gameId) {
					arTmp[y] = ar[x];
					y++;
				}
			}
			myGamesCookie = arTmp.join('/');
			saveGamesCookie(myGamesCookie);		
		
			document.getElementById("gameRemovedMessage").innerHTML = service.labels.myGamesRemoved.replace("[PLACEHOLDER]", gameName);
			document.getElementById("game_" + gameId).innerHTML = "<img src='/s/images/games/remove.png' class='removed' alt='" + service.labels.removalAlt + "' />";
		}
	}
}

function showExitGame(isShown, divId, gameCode) {        
	showPreview(isShown, divId, gameCode);	
	
	if (isShown) {
		showPreview(false, 'showExitButton');
		showPreview(true, 'showPlayButton');
	} else {
		showPreview(true, 'showExitButton');
		showPreview(false, 'showPlayButton');
	}
	
	var myGamesCookie = getCookie("myGames");	
	if (myGamesCookie != null && myGamesCookie.length > 0) {
		showPreview(true, 'mygame');
		showPreview(false, 'nomygame');
	} else {
		showPreview(true, 'nomygame');
		showPreview(false, 'mygame');
	}
	
	var gameId = document.getElementById("gameId").innerHTML;
	if (myGamesCookie != null && myGamesCookie.length > 0) {
		if (myGamesCookie.indexOf(gameId) == -1) {
			showPreview(true, 'notInMyGames');
			showPreview(false, 'inMyGames');
		} else {
			showPreview(true, 'inMyGames');
			showPreview(false, 'notInMyGames');
		}
	}
}

function gameExists(gameId) {
	var myGamesCookie = getCookie("myGames");
	var ar; 
	
	if (myGamesCookie != null) {
		ar = myGamesCookie.split('/');	
	
		for (var x = 0; x < ar.length; x++) {
			if (ar[x] == gameId) {
				return true;
			}
		}
	}	
	return false;
}

function setUpPage() {
	if (document.getElementById("showExitButton")) {
		showPreview(true, 'showExitButton');
		showPreview(false, 'showPlayButton');
	}
	
	// see if game already in my games list
	var gameId = document.getElementById("gameId").innerHTML;
	if (gameExists(gameId)) {
		showPreview(false, 'addGameToMyGames');
	}	
}

function closePopUpPreview(divId) {
	showPreview(false, popUpPreview);
}
// ****************************************************************************
// Show / Hide Games Details in gameSearch.aspx:
// ****************************************************************************
function showPreview(isShown, divId, gameCode) {

	if(document.layers)
	{	
		if (isShown)
		{
			document.layers[divId].visibility = "show";
			document.layers[divId].display = "";
		}
		else {
		    unloadGamePlayer(gameCode);
		    
			document.layers[divId].visibility = "hide";
			document.layers[divId].display = "none";
		}		
	} 
	else if(document.getElementById) 
	{
		if (isShown)
		{
			document.getElementById(divId).style.visibility = "visible";
			document.getElementById(divId).style.display = "";
		}
		else {
		    unloadGamePlayer(gameCode);
		    
			document.getElementById(divId).style.visibility = "hidden";
			document.getElementById(divId).style.display = "none";
		}
	} 
	else 
	{
		if (document.all(divId).style.visibility == "visible")
		{
			document.all(divId).style.visibility = "visible";
			document.all(divId).style.display = "";
		}
		else {
		    unloadGamePlayer(gameCode);
		
			document.all(divId).style.visibility = "hidden";
			document.all(divId).style.display = "none";
		}
	}	
}

function unloadGamePlayer(gameCode) {
    
    var ifrmeSrc = document.getElementById(gameCode);
    if (ifrmeSrc != null)
        ifrmeSrc.src = "/t/games/gameHelp.aspx?gameCode=" + gameCode;
}

function showGamePreview(visible, elemId, elem2Id) {
	var elem = document.getElementById(elemId);
	var elem2 = document.getElementById(elem2Id);
	var scrollX = 0, scrollY = 0;
	
	if (popUpPreview != null) {
		showPreview(false, popUpPreview);		
	}
	
	if (visible) {	
		elem2.focus();
				
		elem.style.position = "absolute";
		elem.style.display = "block";
			
		if (document.body && typeof document.body.scrollTop != "undefined") {
			scrollX += document.body.scrollLeft;
			scrollY += document.body.scrollTop;
			
			if (document.body.parentNode.scrollTop && typeof document.body.parentNode.scrollTop != "undefined") 
			{
				scrollX += document.body.parentNode.scrollLeft;
				scrollY += document.body.parentNode.scrollTop;
			}
		} else if (typeof window.pageXOffset != "undefined") {
			scrollX += window.pageXOffset;
			scrollY += window.pageYOffset;
		}	

		var pos = getElementPosition(elem2);		
		var x = pos.left;
		var y = pos.top;
		
		elem.style.left = 25 + "%";
		elem.style.top = (y + document.documentElement.scrollTop) +  "px";
		elem.style.visibility = "visible";
		elem2.focus();
		popUpPreview = elemId;
	}
	else
	{
		elem.style.visibility = "hidden";
		elem.style.display = "none";
		elem.style.top = "";
		elem.style.left = "";
		popUpPreview = null;	
	}
}

function getElementPosition(elemId) {
	var offsetTrail = document.getElementById(elemId);
	var offsetLeft = 0;
	var offsetTop = 0;
	
	while (offsetTrail) 
	{
		offsetLeft += offsetTrail.offsetLeft;
		offsetTop += offsetTrail.offsetTop;
		offsetTrail = offsetTrail.offsetParemt;
	}
	
	return {left:offsetLeft, top:offsetTop};
}

function saveGamesCookie(value)
{
	document.cookie = "myGames=" + escape(value) + ";path=/;expires=Thu, 31-Dec-2099 23:59:59 GMT";
}

function displayPopupWindow(path, popUpName, attrs) {
	var tmp = location.href;
	var idx = tmp.indexOf("/t/");
	tmp = tmp.substring(0, idx);
	var path = tmp + path;

	var myWin = window.open(path, popUpName, attrs);
    checkWindowResize(attrs, myWin);	
}

function checkWindowResize(attrs, myWin) {    
	var attrArray = attrs.split(',');
	var w = attrArray[0].split('=');
	var h = attrArray[1].split('=');

	var width = Number(w[1]);
	var height = Number(h[1]) + 85;

	myWin.resizeTo(width, height);
}

//
// GRS
//

if (typeof(GRS) == "undefined" || GRS == null)
    var GRS = new Object();
	
if (!GRS.resizeGameIframe)	
	GRS.resizeGameIframe = function(width, height) {
		var sel = "#showGame iframe";
		$(sel).width(width);
		$(sel).height(height);
	};

	if (!GRS.bingoResize)
	    GRS.bingoResize = function() {
	        if (screen.height < 873) {
	            var height = screen.height - 200;
	            var width = 1010;
	            if (screen.width < width + 10)
	                width = screen.width - 10;

	            window.moveTo(0, 0);
	            GRS.resizeGameIframe(width, height);
	        }
	    };

if (!GRS.loadNeoGame)
	GRS.loadNeoGame = function(brandId, gameId, lang, curr, session, user, mode, width, height, showTicker, nick, affiliate, custom) {
		LoadGame(brandId, gameId, lang, curr, session, user, mode, width, height, showTicker, nick, affiliate, custom);
		window.onresize = null;
	};
