﻿// Properties of the page
//
// Holds all the values needed to start the game
var gamedata = {};
//
// An object containing references to popup window handles
var windows = {};
//
// The url of this page
var url = String(self.document.location);
//
// The portion of the url up and including the last forward slash 
//(essentially truncates the file name from the url).
// This value is used to make subsequent calls to the server.
var baseUrl = url.substring(0,url.lastIndexOf("/")+1);
//
// Stores a message to be displayed when the game window is closed.
var closeGameWarningMessage;
//
// Indicates if the page should call into the framework to attempt to clean
// up open long ping connections when the game window is closing.
var longPingCleanUp = false;
//
// Set a handler to perform actions when the game window is closing.
onbeforeunload = handleOnBeforeUnload;
//
/////////////

// Called by the host page to load the game based on the query string parameters
function loadGame () {
    $(document).ajaxError( handleAjaxError );
    
	var qs = getQueryStringParams(window.location.search.substring(1));
    normalizeQueryStringParams(qs);

    if ( qs.t == undefined ) {
        window.location = window.location + "&t=" + new Date().getTime();
    } else {
        gamedata.expired = ( new Date().getTime() - qs.t > 30000 ) ? "1" : "0";
        gamedata.playerHandle = qs.playerHandle;
        gamedata.account = qs.account;
        gamedata.gameName = qs.gameName;
        gamedata.gameType = qs.gameType;
        gamedata.lang = qs.lang;
        gamedata.gameId = qs.gameId;
        gamedata.profileId = qs.profileId;
        gamedata.resumedGame = "-1";
        gamedata.deviceType = "web";
        gamedata.rc = qs.rc;
        if (qs.mp == "1") {
            // Add multiplayer information passed on the querystring to gamedata.
            gamedata.mp = 1;
            gamedata.subdomain = qs.subdomain;
            gamedata.tableId = qs.tableId;
            gamedata.tableName = qs.tableName;
            gamedata.channels = qs.channels;
        } else {
            gamedata.mp = 0;
        }
        getFrameworkDetails();
    }
}

// Called by the framework to reload the current game
function reloadGame () {
	loadResumeCheck();
}

// Calls the server to get information needed to start the game that is not available on the client side.
// Currently, the mode and displayName are passed back from the server.
function getFrameworkDetails () {
	var frameworkDetailsUrl = baseUrl + "dataservice?service=details&account="+gamedata.account+"&playerHandle="+gamedata.playerHandle+"&lang="+gamedata.lang;
    if ( gamedata.gameId != undefined ) {
        frameworkDetailsUrl += "&gameId="+gamedata.gameId;
    } else {
        frameworkDetailsUrl += "&profileId="+gamedata.profileId;
    }
	$.get( frameworkDetailsUrl, function ( detailsString ) {
        var details = getQueryStringParams(detailsString);
        gamedata.displayName = details.displayName;
        gamedata.mode = details.mode;
        gamedata.egiUrl = details.egiURL;
        if (gamedata.mp == "1" || gamedata.rc == "0") {
            // If multiplayer, skip resumecheck and start the game.
            startGame();
        } else {
            if (gamedata.resumedGame == "-1") {
                loadResumeCheck();
            } else if (gamedata.resumedGame == "1") {
                loadFramework();
            }
        }
    });
}

// Loads the resumecheck.swf
function loadResumeCheck () {
	var resumeCheckUrl = baseUrl + "resumecheck/resumecheck.swf";
	var so = new SWFObject(resumeCheckUrl, "resumecheck", "0", "0", "10", document.bgColor);
	so.addVariable("playerHandle",gamedata.playerHandle);
	so.addVariable("lang",gamedata.lang);
	so.addVariable("account",gamedata.account);
	so.addVariable("deviceType",gamedata.deviceType);
	so.addVariable("mode",gamedata.mode);
    so.addParam("menu", "false");
	so.write("resumecheckdiv");
}

// Called by resumecheck.swf when there are no games to resume
function startGame () {
	gamedata.resumedGame = "0";
    loadFramework();
}

// Called by resumecheck.swf when there is a game to resume
function resumeGame ( gameName, gameType, gameId, profileId ) {
	gamedata.resumedGame = "1";
	gamedata.gameName = gameName;
	gamedata.gameType = gameType;
	gamedata.gameId = gameId;
	gamedata.profileId = profileId;
	getFrameworkDetails();
}

// Called by resumecheck.swf when there is an error contacting the resume check servlet
function resumeCheckError ( message ) {
	document.getElementById("frameworkdiv").innerHTML = "<b>Resume Check Error: " + message + "</b>";
}

// Handles the data returned by the query for the framework url and loads the framework
function loadFramework () {
    // Set the page title. If it's not multiplayer, use the display name from the server. For mutliplayer, the lobby will pass the name to the page.
    document.title = ( gamedata.mp == 0 ) ? decodeURIComponent(gamedata.displayName).replace(/\+/g," ") : decodeURI(gamedata.tableName);

	switch ( gamedata.mode ) {
		case "casino1":
		case "casino2":
			gamedata.lang = convertLangCodeToOld( gamedata.lang );
			break;
		case "casino3":
			longPingCleanUp = true;
			var base = "flashcasino3";
			gamedata.lang = convertLangCodeToNew( gamedata.lang );
			break;
		case "casino4":
			var base = "flashcasino4";
			gamedata.lang = convertLangCodeToNew( gamedata.lang );
			break;
	}
	
	// Construct the url needed to load the correct framework.
	// The framework is retrieved by calling the dataservice which determines which swf (casino.swf, casinogdk.swf, framework.swf etc) to return.
	// Any variables that need to be passed ot the framework are appended to this call (details retrieved from server, parameters passed to this page etc).
	var frameworkLoaderUrl = baseUrl + "dataservice?service=framework";
	for ( var a in gamedata ) {
		if (gamedata[a] != undefined) frameworkLoaderUrl += ("&" + a + "=" + gamedata[a]);	
	}
	
	// Load the framework using the url constructed above.
	var so = new SWFObject(frameworkLoaderUrl, "framework", "100%", "100%", "10", document.bgColor);
	so.addParam("menu", "false");
	if ( base != undefined ) so.addParam("base", base);
	so.write("frameworkdiv");
	
	// Run the resizing method.
	resizeWindow( gamedata.mode );
}

// Methods called from the framework
//
function cashier ( url, windowWidth, windowHeight ) {	
	openWin( url, "bank", "toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=no,width="+windowWidth+",height="+windowHeight );
}

function gamingGuide ( url, windowWidth, windowHeight ) {
	openWin( url, "help", "toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=no,width="+ windowWidth +",height=" + windowHeight );
}

function myAccount ( url, windowWidth, windowHeight ) {
	openWin( url, "myAcct", "toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width="+ windowWidth +",height="+ windowHeight );
}

function realityCheck ( url, windowWidth, windowHeight ) {
	openWin( url, "realityCheck", "toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width="+ windowWidth +",height="+ windowHeight );
}

function openRealityCheckLink ( url ) {
	openWin( url, "rclink", "toolbar=yes,location=yes,directories=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes" );
}

function openRealityCheckRedirect ( url ) {
	openWin( url, "rcredirect", "toolbar=yes,location=yes,directories=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes" );
}

function gameStats( url, windowWidth, windowHeight ){
	openWin( url, "gamestats", "toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width="+ windowWidth +",height="+ windowHeight );
}

function enableCloseGameWarning ( message ) {
    closeGameWarningMessage = message;
}

function disableCloseGameWarning () {
    closeGameWarningMessage = null;
}
//
////////

// Utility Methods
//
// Given a queryString, parses out all the parameters into a hashmap
function getQueryStringParams( queryString ) {
	var qsParm = new Array();
	var parms = queryString.split('&');
	for (var i=0; i<parms.length; i++) {
		var pos = parms[i].indexOf('=');
		if (pos > 0) {
			var key = parms[i].substring(0,pos);
			var val = parms[i].substring(pos+1);
			qsParm[key] = val;
		}
	}

	return qsParm;	
}

// Checks the values parsed from the query string and standardizes any incoming values that are required.
function normalizeQueryStringParams( qsParm ) {
    if ( qsParm.lang == "cs" ) qsParm.lang = "cz";
    if ( qsParm.gameName == undefined && qsParm.theGameName != undefined ) qsParm.gameName = qsParm.theGameName;
    if ( qsParm.gameType == undefined && qsParm.theGameType != undefined ) qsParm.gameType = qsParm.theGameType;
    if ( qsParm.profileId == undefined && qsParm.theProfileId != undefined ) qsParm.profileId = qsParm.theGameType;
    if ( qsParm.gameId == undefined && qsParm.theGameId != undefined ) qsParm.gameId = qsParm.theGameId;
}


// Opens the given url in a new window or, if its already open, focuses it.
function openWin ( url, name, arguments ) {
	url = normalizeUrl( url );
	if(!windows[name] || windows[name].closed){
		windows[name] = window.open(url,name,arguments);
	}else{
		windows[name].focus();
	}
}

// Searches for certain values in the url and replaces them.
// Typically, this method is used before calling the url to standardize the values.
function normalizeUrl ( url ) {
	url = url.replace(/lang=zh-cn/i,"lang=cn");
	url = url.replace(/lang=zh-tw/i,"lang=tw");
	return url;
}

// Converts Casino 1 and 2 language codes to the new standard.
function convertLangCodeToNew ( lang ) {
	switch ( lang ) {
		case "zh-cn":
			return "cn";
			break;
		case "zh-tw":
			return "tw";
			break;
		default:
			return lang;
			break;
	}	
}

// Converts standard language codes to legacy format for Casino 1 and 2.
function convertLangCodeToOld ( lang ) {
	switch ( lang ) {
		case "cn":
			return "zh-cn";
			break;
		case "tw":
			return "zh-tw";
			break;
		default:
			return lang;
			break;
	}
}

// Attempts to resize the window between the legacy and new window sizes
function resizeWindow ( mode ) {
	var windowSize = getWindowSize();
	var windowIsStandard = (windowSize[0] == 980 && windowSize[1] == 735) || (windowSize[0] == 700 && windowSize[1] == 550);
	var windowIsWidescreen = (windowSize[0] == 1038 && windowSize[1] == 660) || (windowSize[0] == 865 && windowSize[1] == 550);
	var windowIsResized = !windowIsStandard && !windowIsWidescreen;

	if ( !windowIsResized ) {
		if ( (mode == "casino3" || mode == "casino4") && windowIsStandard ) {
			if ( screen.width >= 1280 ) {
				resizeWin(1038,660);
			} else {
				resizeWin(865,550);
			}
		} else if ( mode != "casino3" && mode != "casino4" && windowIsWidescreen ) {
			if ( screen.width >= 1280 ) {
				resizeWin(980,735);
			} else {
				resizeWin(700,550);
			}
		}
	}
}

// Utility method used by resizeWindow
function resizeWin (width,height) {
	var isNetscape = (navigator.appName=="Netscape")?true:false;
	iWidth = (isNetscape)?window.innerWidth:document.body.clientWidth;
	iHeight = (isNetscape)?window.innerHeight:document.body.clientHeight;
	iWidth = width - iWidth;
	iHeight = height - iHeight;
	window.resizeBy(iWidth, iHeight);
}

// Utility method used by resizeWindow
function getWindowSize () {
	var isNetscape = (navigator.appName=="Netscape")?true:false;
	iWidth = (isNetscape)?window.innerWidth:document.body.clientWidth;
	iHeight = (isNetscape)?window.innerHeight:document.body.clientHeight;
	return [iWidth,iHeight];
}

function handleOnBeforeUnload ( event ) {
    // If LongPingCleanUp is enabled (multiplayer), then call the function in the framework
    if ( longPingCleanUp ) {
        var movieId = "framework";
		var isIE = navigator.appName.indexOf("Microsoft") != -1;
		var flashMovie = (isIE) ? window[movieId] : document[movieId];
		if ( isIE ) {
			flashMovie.cleanUpConnections();
		}
    }

    // If the game has set a close game warning message, return it so that it is displayed.
    if ( closeGameWarningMessage != null ) {
        return closeGameWarningMessage;
    }
}
//
////////

function handleAjaxError (  event, xhr ) {
    var message = "Temporary difficulties, Please try again later or contact Support if problem persists.";
    switch ( gamedata.lang ) {
        case "ca":
            message = "Dificultats temporals. Torneu-ho a intentar més endavant o poseu-vos en contacte amb l'equip d'assistència tècnica si el problema persisteix.";
            break;
        case "cn":
            message = "暂时遭遇困难，请稍后再试，若问题仍存在，请联络技术支持。本游戏可续玩。";
            break;
        case "cz":
            message = "Přechodné potíže. Zkuste to prosím později nebo kontaktujte oddělení podpory zákazníků, pokud bude problém přetrvávat.";
            break;
        case "da":
            message = "Forbigående problemer. Forsøg venligst igen senere eller kontakt kundekundesupport, hvis problemet vedvarer.";
            break;
        case "de":
            message = "Vorübergehende Schwierigkeiten. Bitte versuchen Sie es später noch einmal. Falls das Problem weiterhin besteht, wenden Sie sich an den Kundendienst.";
            break;
        case "el":
            message = "Προσωρινές δυσκολίες. Προσπαθήστε ξανά αργότερα ή επικοινωνήστε με το Τμήμα Υποστήριξης εάν το πρόβλημα παραμένει.";
            break;
        case "en":
            message = "Temporary difficulties, Please try again later or contact Support if problem persists.";
            break;
        case "es":
            message = "Dificultades temporales. Inténtelo más tarde o si el problema persiste, póngase en contacto con el plantel de servicio al cliente.";
            break;
        case "fr":
            message = "Difficultés temporaires, veuillez réessayer plus tard ou contactez l'assistance si le problème persiste.";
            break;
        case "he":
            message = "Temporary difficulties, Please try again later or contact Support if problem persists.";
            break;
        case "hu":
            message = "Ideiglenes probléma. Próbálkozzon újra, vagy ha a probléma nem oldódik meg, jelezze Ügyfélszolgálatunknak.";
            break;
        case "it":
            message = "Si è verificato un errore. Riprova più tardi. Se il problema persiste, contatta il Supporto. La partita potrà essere ripresa.";
            break;
        case "ja":
            message = "一時的にエラーが生じました。後ほどお試し頂くか、サポートセンターにお問い合わせください。";
            break;
        case "ko":
            message = "일시적인 오류 . 나중에 다시 시도하시거나 이 문제가 계속 지속된다면 ' 고객 지원 ' 으로 문의 바랍니다 . 이 게임을 다시 할 수 있습니다 .";
            break;
        case "nl":
            message = "Tijdelijke problemen. Probeer het later opnieuw of neem contact op met de klantenservice indien het probleem zich blijft voordoen.";
            break;
        case "no":
            message = "Forbigående problemer. Vennligst prøv på nytt senere eller kontakt kundestøtte dersom problemet vedvarer. Du kan fortsette spillet.";
            break;
        case "pl":
            message = "Wystapily chwilowe problemy. Spróbuj ponownie pózniej lub skontaktuj sie z obsluga klienta, jesli problem sie utrzymuje.";
            break;
        case "pt":
            message = "Dificuldades temporárias. Tente mais tarde ou, se o problema persistir, contacte o Apoio.";
            break;
        case "ro":
            message = "Dificultati temporare. Încercati din nou mai târziu sau, daca problema persista, luati legatura cu echipa de asistenta.";
            break;
        case "ru":
            message = "Временная проблема. Повторите попытку позже или обратитесь в службу поддержки, если проблема не исчезнет.";
            break;
        case "sk":
            message = "Prechodné tažkosti. Skúste to, prosím, neskôr alebo kontaktujte oddelenie podpory zákazníkom, ak bude problém pretrvávat.";
            break;
        case "sv":
            message = "Tillfälliga svårigheter, försök igen eller ta kontakt med vår support om problemet kvarstår.";
            break;
        case "tr":
            message = "Geçici zorluklar, Lütfen daha sonra tekrar deneyin veya sorun devam ederse Destek hizmetleriyle iletisim kurun.";
            break;
        case "tw":
            message = "暫時遭遇困難，請稍後再試，若問題仍存在，請聯絡技術支援。本遊戲可續玩。";
            break;
    }
    $("body").html( message + " (Status: " + xhr.status + ")" ).addClass("error");
}



