/**
* 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 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 = false;
var usehttps = false;
var isChild = false;

var blockerDetectionEnabled = true;
var blockerCookieId = "playtech.casino.blocker.detection.done";
var blockerTimerId;
var blockerWindow;


//only these parameters will be accepted from PHP (case-sensitive!)
var acceptedParams = ["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", "language", "miniGame", "wmode",
					"mode", "icenabled", "gameMode", "noblockerdetect"];

//launching the client with any of these modules will force the use of AS2 client (case-sensitive!)
var gamecodes = ["bjl", "7bal", "plba", "vbal", "rbal", "lmpg", "ropl", "rol", "rodzl", "sbl", "mbj", "mcm", 
				"pbro", "rouk", "mro", "ro3d", "cr", "bjz", "peb", "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_mh3", "bjuk_mh5", "bjuk_mp", "bjuk_pg", "baz", "bj21r", "bj21r_mh", "odp",
				"cw", "sb", "sb_mp", "sb_pg", "tcp", "tqp", "cheaa", "rd", "rd_mp", "rd_pg", "pg", "wv", "str", "bj21d", "bj21d_mh3",
				"bj21d_mp", "bj21d_pg", "ct", "hk", "sib", "ssl", "potr", "tp", "gc", "tr", "op", "cm", "er", "psl", "gbs", "ms", "sc",
				"gos", "fmn", "gs", "wsffr", "cifr", "ck2", "grel", "mds", "wfm", "tms", "hb", "dt", "dlm", "msm", "ssr", "drs", "qop",
				"frwl", "ska", "fow", "wan", "gro", "ges", "tfm", "gt", "ml", "jb", "jbz", "fbr", "lm", "c7", "foy", "ek", "fm", "ub",
				"al", "hh", "nk", "sf", "ts", "rnr", "ah", "ta", "sof", "td", "bt", "pl", "bl", "ma", "8bs", "dw4", "af4", "af25",
				"jb10", "dw", "af", "jp", "hljb", "mj", "tob", "bls", "sbls", "fbls", "rcd", "rps", "dctw", "pso",
				"ghl", "ghlj", "drts", "bowl", "head", "kn", "fosl", "hr", "smw", "smj", "smpw", "smpj", "pc"];

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;
	}

	if (base != '') {
		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(parameters);
	
	if ( !isChild && blockerDetectionEnabled && !isBlockerDetectionDone() ) {
		startClientWithDetection();
	} else {
		startClient();
	}
	
}

/**
 * Detect if popup opening is blocked by user browser native blockers.
 * Native blockers are for example in IE 7: Tools -> Popup Blocker, FF 3:  Tools -> Options -> Content tab -> Block pop-up windows.
 * "Popup opening" is meaning using window.open() call from script without user direct interaction
 * (user interaction would be e.g. clicking on link and using window.open call from click listener).
 *
 * Check is done using preemptive window.open() call. When popups are blocked, then window is not opened
 * and code can make further actions based on that fact. Downside is that when popups are not blocked, user sees
 * for a little period of time empty popup-testing window, which is closed right away. To remedy, popup-testing
 * window will be made with exact dimensions of client window under it. Please note that blurring window is not an option
 * (to hide it behind main window), it will activate only after window is fully opened and even slows process down a bit.
 *
 * [!] In IE it is impossible to make popup-test window without statusbar and locationbar. 
 * This causes popup-test window being with different dimensions than original window.
 * 
 * [!] In Chrome it is not possible to make opening test using conventional means of checking if test window is opened.
 * When popup blocker is on, Chrome opens the popup, loads the page, and parses all the Javascript on the "blocked popup". 
 * It just doesn't display the popup to the user. In Chrome src code it is called ConstrainedWindow.
 * 
 * For Chrome timeout + innerHeight reading scheme is used:
 * 		[1] make regular popup test with test-window
 * 		[2] set timeout to read test-window innerHeight value after some time (to ensure that page is fully loaded)
 * 		[3] if innerHeight value is still 0, it is strong indicator that popup was blocked
 * 		[!] note that until test-window is loaded, innerHeight value is always 0, no matter if blocked or not 
 * 
 * [!] When window.open() call is specifying position of window (top, left), all negative values are
 * retranslated either into some default values or 0 depending on browser;
 *
 * If popups are not blocked, write result into browser cookie and do not check any more (read always cookie contents before check).
 * If popups are blocked, set client parameter and show client alert right after client loading.
 * 
 * Test for IE6+, FF3+, Safari, Chrome
 * [!] Chrome has cookie writing disabled while testing from local filesystem
 * [!] IE doesn't block popups from localhost, even when blocker turned on, but blocks from local filesystem
 * 		[1] clear cache and cookies, set browser blocker on and start client;
 * 			verify that blocker alert appears in client
 * 		[2] set browser blocker off and start client;
 			verify that blocker alert doesn't appear and cookie "playtech.casino.blocker.detection.done" is written
 * 		[3] just after completing [2] set browser blocker on and start client;
 * 			verify that cookie is checked and thus no alert is appearing in client.
 * 
 */
function startClientWithDetection() {
	
	if (isChrome) {
		detectChromePopupBlocker();
	}
	else {
		detectPopupBlocker();		
		startClient();
	}
	
}

function addBlockerDetectedParam() {

	acceptedparams.push("popupblockerdetected");
	acceptedparams.push("1");
	
}

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;
			}
		}
	}
	
	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("module");
					acceptedparams.push(parameters[i+1]);
				}
				else if (parameters[i] == "useconn") {
					addconn = true;
				}
				else if (parameters[i] == "affiliates" && parameters[i+1] == "1") {//affiliatesEnabled = 1 is missing!
					acceptedparams.push("affiliates");
					acceptedparams.push("1");
					acceptedparams.push("mode");
					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] == "noblockerdetect" && parameters[i + 1] == "1") {
					blockerDetectionEnabled = false;
				}
				else if (parameters[i] == "ischild" && parameters[i + 1] == "1") {
					isChild = true;
				} 
				else if (parameters[i] == "miniGame" && parameters[i + 1] == "1") {
					isMini = true;
					
					if(clienttype == 3) {
						acceptedparams.push("mini");
						acceptedparams.push("1");
						continue;
					}//for AS2 append as is
				}

				acceptedparams.push(parameters[i]);
				acceptedparams.push(parameters[i+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 -->';
	nextpage += '<script type="text/javascript" src="'+jsbase+'casinoclient.js"></script>';
	nextpage += '<script type="text/javascript" src="'+jsbase+'facebookbar.js"></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.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>';
	
	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 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="Casino">';
		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="allowScriptAccess" VALUE="always">';
		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="Casino" ';
		str += 'src="'+base+client+"?"+params+'" ';
		str += 'base="'+base+'" ';
		str += 'swliveconnect="true" ';
		str += 'menu="false" ';
		str += 'quality="high" ';
		str += 'allowScriptAccess="always" ';
		if (wmode != "no_key") {
			str += 'wmode="'+wmode+'" ';
		}
		else {
			str += 'wmode="window" ';
		}
		//str += 'flashvars="'+params+'" ';
		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);
		}
	}
	
	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 detectPopupBlocker( ) {

	createPopupDetectionWindow();
		
	//if popup blocked window
	if ( blockerWindow == null || blockerWindow.closed || typeof blockerWindow.closed == 'undefined' ) {		
		addBlockerDetectedParam();
	} else {
		setBlockerCookie();
    }
	if ( blockerWindow ) blockerWindow.close();
	
}

function detectChromePopupBlocker() {
	
	createPopupDetectionWindow();
	blockerTimerId = window.setTimeout( completeChromeDetection, 100);
	
}

function createPopupDetectionWindow(){
	
	// obtain properties of original window for being able to open window of exact same size
	var x = getWindowPosition( window ).x;
	var y = getWindowPosition( window ).y;
    var innerWidth = getInnerDimensions().width;
    var innerHeight = getInnerDimensions().height;

	var positionStr = "left=" + x +"," + "top=" + y +"," + "screenX=" + x +"," + "screenY=" + y +",";
	var dimensionStr = "height=" + innerHeight + "," + "width=" + innerWidth + ",";
	
	blockerWindow = window.open("about:blank","","location=no, status=no, menubar=no, resizable=no, scrollbars=no, toolbar=no," + dimensionStr + positionStr);
	
}

function completeChromeDetection() {
	
	clearTimeout( blockerTimerId );
	
	if ( blockerWindow.innerHeight == 0 ) {		
		addBlockerDetectedParam();		
	} else {
		setBlockerCookie();
    }
		
	if ( blockerWindow ) blockerWindow.close();
	
	startClient();
	
}

function isBlockerDetectionDone() {
	
	var cookieValue = "0";

	if ( document.cookie.length > 0 ) {
		var cookieStart = document.cookie.indexOf(blockerCookieId + "=");
		if ( cookieStart != -1 ) {
			cookieStart = cookieStart + blockerCookieId.length + 1;
			var cookieEnd = document.cookie.indexOf( ";",cookieStart );
			if ( cookieEnd == -1 ) cookieEnd = document.cookie.length;
			cookieValue = document.cookie.substring( cookieStart,cookieEnd );			
		}
	}
	
	if (cookieValue == "1") {
		return true;
	} else {
		return false;
	}
	
}

function setBlockerCookie() {
	
	var expiryDate = new Date();
	expiryDate.setDate( expiryDate.getDate() + 365) ;
	document.cookie = blockerCookieId + "=1;expires=" + expiryDate.toGMTString();
	
}

function getWindowPosition( w ) {

    var position = {x:0, y:0};
    if ( typeof w.screenTop != 'undefined' ) {  // IE
        position.x = w.screenLeft;
        position.y = w.screenTop;
    } else if (typeof w.screenY != 'undefined') {
       position.x = w.screenX;
       position.y = w.screenY;
    }
    return position;

}

function getInnerDimensions() {

    var dimensions = {height:0, width:0};

	// standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
	if ( typeof window.innerWidth != 'undefined' ) {  // FF
		dimensions.width = window.innerWidth;
		dimensions.height = window.innerHeight;
	// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
	} else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) {
		dimensions.width = document.documentElement.clientWidth;
		dimensions.height = document.documentElement.clientHeight;
	// older versions of IE
	} else {
		dimensions.width = document.getElementsByTagName('body')[0].clientWidth;
		dimensions.height = document.getElementsByTagName('body')[0].clientHeight;
	}

	return dimensions;
	
}