﻿/**
* This script does the following:
*
* install core JS
* choose the right client (AS2/AS3)
* inspect client parameters
* convert client parameters if necessary
* check flash flash player version
* output embedding HTML
* implementing facebook bar feature : showing ann hiding bar above client with proper resizing of casino div
**/

var requiredVersion3 = [10,0,22];//anything less than this = client doesn't run
var requiredVersion2 = [10,0,22];
var clientlang = 'en';
var isPaddyPower = false;
var documentDomain = '';
var isMini = false;
var jsbase = '';
var langbase = '';

var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
var isChrome = /chrome/.test( navigator.userAgent.toLowerCase() );

var addconn = true;
var usehttps = false;
var isChild = false;

//only these parameters will be accepted from PHP (case-sensitive!)
var acceptedParams = ["temptoken", "username", "obaffid", "obchannel", "nolobby", "ischild", "cashierdomain", "advertisercode", "banner", "profile", "referer", "creferer", "remoteip",
					"preview", "fimid", "_realonly", "_funonly", "safgame", "sidegame", "game", "useconn", "affiliates", "affiliateStreakLimit",
					"affiliateWinLimit", "affiliateWinningStreakMessage", "affiliateBigWinMessage", "affiliateBalanceZeroMessage",
					"affiliateAskMessage", "affiliateRedirectMode", "affiliateURLdl", "affiliateURLflash", "affiliateURLredirect",
					"affiliatePlayDurationLimit", "affiliatePlayDurationMessage", "affiliateNCStreakLimit", "affiliateNCStreakMessage",
					"affiliateRoundsPlayedLimit", "affiliateRoundsPlayedMessage", "affiliateZeroBalanceEnabled", "language", "miniGame",
					"wmode", "mode", "icenabled", "gameMode", "noblockerdetect", "livenetworkid", "ceventlistener", "attractscreen",
					"preferedmode", "cashierthrufim", "clienttype", "clientplatform", "skin",
					"paddypower", "documentdomain"];

//launching the client with any of these modules will force the use of AS2 client (case-sensitive!)
var gamecodes = ["lmpg","pbro", "bj_mp", "bj_pg", "pbj",
				"pbj_mh5", "pbj_mp", "pbj_pg", "bjsd_mp", "bjsd_pg", "p6dbj", "p6dbj_mh3", "p6dbj_mh5",
				"p6dbj_mp", "p6dbj_pg", "psdbj", "pon", "pon_mh3", "pon_mh5", "pon_mp", "pon_pg", "bjs", "bjhd", "bjhd_mh3", "bjhd_mh5",
				"bjhd_mp", "bjhd_pg", "bjuk", "bjuk_mh5", "bjuk_mp", "bjuk_pg", "baz", "bj21r", "bj21r_mh", "odp",
				"cw", "sb", "sb_mp", "sb_pg", "tcp", "cheaa", "pg", "wv", "str", "msm",
				"frwl", "ska", "gro", "ges", "mro",
				"bls", "sbls", "fbls", "rcd", "rps",
				"drts", "bowl", "head", "kn", "hr", "smw", "smj", "smpw", "smpj", "pc"];
				
var minigamecodes = ['mfdt', 'dtm', 'mfbr'];

var acceptedparams = [];
var clienttype = 3;
var locationBase = '';

/**
 *
 * @param {Object} base - if defined must end with '/'
 * @param {Object} parameters
 */
function initClient(base, parameters){
	if (String(document.location).split(":")[0] == "https") {
		usehttps = true;
	}

	var clientparameters = [];
	if (parameters == "get") {
		if (String(document.location).indexOf("?") != -1) {
			var paramstr;
			paramstr = String(document.location).split("?")[1];
			var paramsarr = paramstr.split("&");
			var l;
			var i;
			l = paramsarr.length;
			for (i=0; i<l; i++) {
				chunks = paramsarr[i].split("=");
				clientparameters.push(chunks[0]);
				clientparameters.push(chunks[1]);
			}
		}
		locationBase = findBase();
	}
	else if (parameters != null) {
		clientparameters = parameters;
	}

	if (base != '' && locationBase == '') {
		var basedomain = findDomain(base);
		
		var reqdomain = findDomain(String(document.location));
		
		var s = base.indexOf(basedomain);
		
		locationBase = base.substr(0, s) + reqdomain + base.substr(s + basedomain.length);
	}
	
	parseParameters(clientparameters);
	
	startClient();
	
}

function parseParameters( parameters ) {
	
	var definedmodule = "";
	var i;
	var ii;
	
	for (i = 0; i < parameters.length; i += 2) {
		if (parameters[i] == "game") {
			definedmodule = parameters[i + 1];
			break;
		}
	}
	
	/**
	 * Determine the client based on the provided module shortname.
	 * The default above is important. Else case is handled by the
	 * client either by not starting or launching lobby.
	 **/
	if (definedmodule != "") {
		for (i = 0; i < gamecodes.length; i++) {
			if (gamecodes[i] == definedmodule) {
				clienttype = 2;
			}
		}
	}
	var launchModule = '';
	for (i = 0; i < parameters.length; i += 2) {
		for (ii = 0; ii < acceptedParams.length; ii++) {
			if (acceptedParams[ii] == parameters[i]) {//parameter translation for backwards compatibility between AS2 and AS3
				if (parameters[i] == "game") {
					acceptedparams.push("fastlog");
					acceptedparams.push("1");
					acceptedparams.push("module");
					acceptedparams.push(parameters[i + 1]);
					launchModule = parameters[i + 1];
				}
				else if (parameters[i] == "mode") {
					if (parameters[i+1] == "") {
						continue;
					}
					acceptedparams.push("gameMode");
					acceptedparams.push(parameters[i + 1]);
				}
				else if (parameters[i] == "useconn" && parameters[i+1] == "0") {
					addconn = false;
				}
				else if (parameters[i] == "affiliates" && parameters[i + 1] == "1") {//affiliatesEnabled = 1 is missing!
					acceptedparams.push("affiliates");
					acceptedparams.push("1");
					acceptedparams.push("preferedmode");
					acceptedparams.push("offline");
					acceptedparams.push("nolobby");
					acceptedparams.push("1");
				}
				else if (parameters[i] == "language") {
					parameters[i + 1] = parameters[i + 1].toLowerCase();
					clientlang = parameters[i + 1].toLowerCase();
				}
				else if (parameters[i] == "ischild" && parameters[i + 1] == "1") {
					isChild = true;
				}
				else if (parameters[i] == "miniGame" && parameters[i + 1] == "1") {
					isMini = true;
					continue;
				}
				else if (parameters[i] == "_realonly" && parameters[i + 1] == "1") {
					if (clienttype == 3) {
						acceptedparams.push("mode");
						acceptedparams.push("real");
						continue;
					}//for AS2 append as is
				}
				else if (parameters[i] == "_funonly" && parameters[i + 1] == "1") {
					if (clienttype == 3) {
						acceptedparams.push("mode");
						acceptedparams.push("fun");
						continue;
					}//for AS2 append as is
				}
				else if (parameters[i] == "cashierthrufim" && parameters[i + 1] == "1") {
					if (clienttype == 2) {
						acceptedparams.push("_html_cashier");
						acceptedparams.push("1");
						continue;
					}//for AS3 append as is
				}
				else if (parameters[i] == "paddypower") {
					if (parameters[i + 1] == "1") {
						isPaddyPower = true;
					}
					continue;
				}
				else if (parameters[i] == "documentdomain") {
					documentDomain = parameters[i + 1];
					continue;
				}
				acceptedparams.push(parameters[i]);
				acceptedparams.push(parameters[i + 1]);
			}
		}
	}
	
	if (launchModule != '') {
		isMini = false;
		for (i=0; i<minigamecodes.length; i++) {
			if (launchModule == minigamecodes[i]) {
				isMini = true;
				break;
			}
		}
	}
	
	if (isMini) {
		acceptedparams.push("mini");
		acceptedparams.push("1");
		acceptedparams.push("miniGame");
		acceptedparams.push("1");
		acceptedparams.push("nolobby");
		acceptedparams.push("1");
	}
	
	if (clienttype == 3) {
		acceptedparams.push("browserid");
		acceptedparams.push(escape(navigator.userAgent));
	}
	
}

function startClient() {
	
	var i = 0;
	var versioncheck;
	var paramstr = "";
	var connparamstr = "";
	
	for (i = 0; i < acceptedparams.length; i += 2) {//assemble accepted parameters into necessary string
		paramstr += acceptedparams[i]+"="+acceptedparams[i+1]+"&";
	}
	
	if (clienttype == 3) {
		versioncheck = hasVersion(requiredVersion3);
	}
	else {
		versioncheck = hasVersion(requiredVersion2);
	}
	
	if (!locationBase)
	{
		locationBase = "";
	}
	jsbase = locationBase;
	locationBase += '[' + clientlang + ']/';

	if (!versioncheck) {//version check failed, cannnot launch the client
		if(isMini) {
			document.location = locationBase + "flashless_mini.html";
		}
		else {
			document.location = locationBase + "flashless.html";
		}
		
		return;
	}

	if (addconn && clienttype != 3) {
		lc1 = getRandomString();
		lc2 = getRandomString();
		
		paramstr += "inID=" + lc1 + "&outID=" + lc2 + "&";
		connparamstr = "inID=" + lc2 + "&outID=" + lc1 + "&";
	}
	
	var page = generateOutput(locationBase, paramstr, clienttype, connparamstr);
	
	if (isIE) {
		/**
		* If a refresh is made in IE, it will remember a lot of stuff, even
		* the memory of the client won't be wiped out. To prevent that, we
		* bulldoze.
		**/
		document.open();
		document.write(page);
		document.close();
		window.location.reload(true);
	}
	else {
		document.write(page);
	}
}

function generateOutput(base, params, clienttype, connparams) {
	var clientversion;
	var nextpage = "";

	nextpage += '<html style="height:100%;" >';
	nextpage += '<head>';
	nextpage += '<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-4" />';
	nextpage += '<title>::: Casino :::</title>';
	
	nextpage += '<!-- saved from url=(0013)about:internet -->';
	if (isPaddyPower) {
		nextpage += '<script type="text/javascript" src="'+jsbase+'paddypower.js"></script>';
	}
	nextpage += '<script type="text/javascript" src="'+jsbase+'casinoclient.js"></script>';
	nextpage += '<script type="text/javascript" src="'+jsbase+'facebookbar.js"></script>';
	if (isPaddyPower) {
		nextpage += '<script type="text/javascript">isPaddyPower='+isPaddyPower+';</script>';
	}
	
	if (documentDomain != "") {
		nextpage += '<script>document.domain = "' + documentDomain + '";</script>';
	}
	
	if (clienttype == 2) {
		clientversion = requiredVersion2;
		if (isMini) {
			client = "Casino_mini.swf";
		}
		else {
			client = "Casino.swf";
		}

		base = base+"as2/";
		nextpage += '<script type="text/javascript" src="'+base+'flashcasino.js"></script>';
	}
	else {
		clientversion = requiredVersion3;
		if(isMini) {
			client = "casino_mini_attr.swf";
		}
		else {
			client = "casino.swf";
		}
		
		nextpage += '<script type="text/javascript" src="'+jsbase+'CORE_Browser.js"></script>';
	}
	nextpage += '</head>';
	
	nextpage += '<body bgcolor="#000000" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0" style="height:100%;"';
		
	if (clienttype == 2) {
		nextpage += 'onunload="closeWindows(); ';
	}
	nextpage += '">';
	
	nextpage += '<div style="height:100%; width:100%;text-align: center;">'; // container start, text-align is for IE to center div contents
	
	nextpage += '<div id="fb_iframediv" style="height:0; width:0; margin: 0 auto;">';
	nextpage += '<iframe name="fb_iframe" id="fb_iframe", src="about:blank" border="0px" scrolling="no" frameborder="0" marginwidth="0" hspace="0" style="width:0; height:0;">';
	nextpage += '</iframe>';
	nextpage += '</div>';
		
	if (connparams != "") {
		nextpage += '<div id="conn">';
		nextpage += '<script language="JavaScript" type="text/javascript">document.write(\''+getClientString(base, "conn.swf", connparams, clientversion, 1)+'\');</script>';
		nextpage += '</div>';
	}
	
	nextpage += '<div id="fContent" style="height:100%; width:100%;">';
	
	if (clienttype == 3) {
		nextpage += '<script language="JavaScript" type="text/javascript">function callFunc(win, func, obj, arr) { return win[func](obj, arr); }</script>';
	}
	
	nextpage += '<script language="JavaScript" type="text/javascript">document.write(\''+getClientString(base, client, params, clientversion)+'\');</script>';
	nextpage += '</div>';
	
	nextpage += '<div id="casinosiframediv" style="display:none;"></div>';
	nextpage += '<div id="hurliframediv" style="display:none;"></div>';
	
	if (isPaddyPower == true) {
		nextpage += "<script>document.write(eval('getPaddyPowerDivStr()'));</script>";
	}
	
	nextpage += '</div>'; // container end
	
	nextpage += '</body>';
	nextpage += '</html>';
	return (nextpage);
}

/**
* This should be used to return the source to be written into a document to display the client
*
* @param base client´s base folder
* @param parameters array of key value pairs that should be forwarded to client
**/
function getClientString(base, client, params, clientversion, invisible) {
	var height;
	var width;

	if (invisible == "1") {
		height = "0";
		width = "0";
	}
	else {
		width = "100%";
		height = "100%";
	}

	var id;
	if (client == "conn.swf") {
		id = "conn";
	}
	else {
		id = "Casino";
	}
	
	var str = "";
	var wmode = getValueFromString("wmode", params);
	params = removeFromParams("wmode", params);

	if (isIE && isWin && !isOpera) {
		//add object tag
		str += '<OBJECT ';
		if (usehttps) {
			str += 'width="'+width+'" height="'+height+'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version='+clientversion[0]+','+clientversion[1]+','+clientversion[2]+',0" ';
		}
		else {
			str += 'width="'+width+'" height="'+height+'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version='+clientversion[0]+','+clientversion[1]+','+clientversion[2]+',0" ';
		}
		str += 'id="'+id+'">';
		str += '<PARAM NAME="movie" VALUE="'+base+client+"?"+params+'">';
		str += '<PARAM NAME="base" VALUE="'+base+'">';
		str += '<PARAM NAME="swliveconnect" VALUE="true">';
		str += '<PARAM NAME="menu" VALUE="false">';
		str += '<PARAM NAME="quality" VALUE="high">';
		str += '<PARAM NAME="bgcolor" VALUE="#000000">';
		str += '<PARAM NAME="allowScriptAccess" VALUE="always">';
		str += '<PARAM NAME="allowFullScreen" VALUE="true">';
		str += '<PARAM NAME="seamlessTabbing" VALUE="false">';
		if (wmode != "no_key") {
			str += '<PARAM NAME="wmode" VALUE="'+wmode+'">';
		}
		else {
			str += '<PARAM NAME="wmode" VALUE="window">';
		}
		//str += '<PARAM NAME="flashvars" VALUE="'+params+'">';
		str += '</OBJECT>';
	}
	else {
		str += '<EMBED ';
		str += 'align="top" ';
		str += 'width="'+width+'" ';
		str += 'height="'+height+'" ';
		if (usehttps) {
			str += 'pluginspace="https://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" ';
		}
		else {
			str += 'pluginspace="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" ';
		}
		str += 'name="'+id+'" ';
		str += 'id="'+id+'" ';
		str += 'src="'+base+client+"?"+params+'" ';
		str += 'base="'+base+'" ';
		str += 'swliveconnect="true" ';
		str += 'menu="false" ';
		str += 'quality="high" ';
		str += 'bgcolor="#000000" ';
		str += 'allowScriptAccess="always" ';
		str += 'allowFullScreen="true" ';
		if (wmode != "no_key") {
			str += 'wmode="'+wmode+'" ';
		}
		else {
			str += 'wmode="window" ';
		}
		str += 'type="application/x-shockwave-flash" > ';
		str += '</EMBED>';
	}
	return (str);
}

/**
* This will compare requiered version and current version of the flash player and
* return true, if current version is greater or equal to the required version
**/
function hasVersion(version) {
	var currentVersion = getPlayerVersion();
	var i;
	
	for (i=0; i<currentVersion.length; i++) {
		if (Number(currentVersion[i]) < Number(version[i])) {
			return (false);
		}
		else if (Number(currentVersion[i]) > Number(version[i])){
			return (true);
		}
	}
	
	return (true);
}

/**
* This will return the version of the ActiveX Flash Player, the returned version
* will be at least 7
**/
function getAXVersion() {
	var version;
	var axo;
	var e;

	try {
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {}
	if (!version) {
		version = [7,0,0,0];
	}
	else {
		version = version.split(" ")[1];
		version = version.split(",");
	}
	return version;
}

/**
* This will return the version of the Plugin Flash Player, the returned version
* will be at least 7
**/
function getPlayerVersion() {
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var version = [0,0,0,0];
	
	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var pluginDesc;
			if (navigator.plugins["Shockwave Flash 2.0"]) {
				pluginDesc = navigator.plugins["Shockwave Flash 2.0"].description;
			}
			else {
				pluginDesc = navigator.plugins["Shockwave Flash"].description;
			}
			//Shockwave Flash 10.0 r32
			//plugin majV.minorV rRevision
			var chunks = pluginDesc.split(" ");
			version = chunks[2].split(".");
			if (chunks[3] == "") {
				version.push(chunks[4]);
			}
			else {
				version.push(chunks[3]);
			}
			if (version[2][0] == "d") {
				version[2] = version[2].substring(1);
			} else if (version[2][0] == "r") {
				version[2] = version[2].substring(1);
				if (version[2].indexOf("d") > 0) {
					version[2] = version[2].substring(0, version[2].indexOf("d"));
				}
			}
		}
	}
	else if (isIE && isWin && !isOpera) {
		version = getAXVersion();
	}
	
	return version;
}

function getRandomString() {
	var letters = "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789";
	var str = "";
	var i;
	
	for (i=0; i<10; i++) {
		str += letters.charAt(Math.round(Math.random()*59));
	}
	
	return str;
}

function getValueFromString(needle, hay) {
	var chunks = hay.split("&");
	var keyvalue;
	var i;
	var l;
	chunks.pop();
	l = chunks.length;
	for (i=0; i<l; i++) {
		if (chunks[i].length > 2) {
			keyvalue = chunks[i].split("=");
			if (keyvalue[0] == needle) {
				return (keyvalue[1]);
			}
		}
	}
	return ("no_key");
}

function removeFromParams(key, params) {
	var chunks = params.split("&");
	var keyvalue;
	var i;

	for (i=0; i < chunks.length; i++) {
		if(chunks[i] == "") {
			chunks.splice(i, 1);
			i--;
			continue;
		}

		keyvalue = chunks[i].split("=");

		if (keyvalue[0] == key) {
			chunks.splice(i, 1);
			i--;
		}
	}

	return (chunks.join("&") + "&");
}

function findDomain(str) {
	var r;
	r = String(str.split("://")[1]);
	r = String(r.split("/")[0]);
	return (r);
}


function reloadIn(time) {
	setTimeout(doReload, time);
}

function doReload() {
	window.location.reload();
}
function callFunc(win, func, obj, arr) {//Core util
	return win[func](obj, arr);
}
function findBase() {
	var loc = ""+String(document.location);
	if (loc.indexOf("?") != -1) {
		loc = loc.substr(0, loc.indexOf("?"));
	}
	if (loc.lastIndexOf("/") != -1 && loc.lastIndexOf("/") > 8) {
		loc = loc.substr(0, loc.lastIndexOf("/")+1);
	}
	if (usehttps && loc.substr(0,5) == "http:") {
		loc = "https"+loc.substr(4);
	}
	else if (!usehttps && loc.substr(0,5) == "https") {
		loc = "http"+loc.substr(5);
	}
	return loc;
}
