﻿function IsSecuredConn() {
	return (window.location.href.indexOf("https://") != -1);
}

function GetHttpOrHttps() {
	if (IsSecuredConn()) return "https"; else return "http";
}

function GetPlCredits(bDollar, bRounded, callback) {
	if (global.bInitialized) {
		$.ajax({
			type: "POST",
			url: global.siteURL + "/Services/Misc.asmx/GetCredits",
			data: "{'idPlayer':'" + global.idPlayer + "', 'bDollar':'" + bDollar + "', 'bRounded':'" + bRounded + "', 'idCustomer' : '" + global.idCustomer + "'}",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function (msg) {
				callback(msg.d);
			},
			error: function (err) {
			}
		});
	}
}

function GetPlMoney(bDollar, bRounded, callback) {
    if (global.bInitialized) {
        $.ajax({
            type: "POST",
            url: global.siteURL + "/Services/Misc.asmx/GetMoney",
            data: "{'idPlayer':'" + global.idPlayer + "', 'bDollar':'" + bDollar + "', 'bRounded':'" + bRounded + "', 'idCustomer' : '" + global.idCustomer + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                callback(msg.d);
            },
            error: function (err) {
            }
        });
    }
}


function GetPlAffPoints(callback) {
	if (global.bInitialized) {
		$.ajax({
			type: "POST",
			url: global.siteURL + "/Services/Misc.asmx/GetAffPoints",
			data: "{'idPlayer':'" + global.idPlayer + "', 'idCustomer' : '" + global.idCustomer + "'}",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function (msg) {
				callback(msg.d);
			},
			error: function (err) {
			}
		});
	}
}

function GetPlFreePoints(callback) {
	if (global.bInitialized) {
		$.ajax({
			type: "POST",
			data: "{'idPlayer':'" + global.idPlayer + "','idCustomer' : '" + global.idCustomer + "'}",
			url: global.siteURL + "/Services/Misc.asmx/GetFreePoints",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function (msg) {
				callback(msg.d);
			}
		});
	}
}

function GetCurrencies(callback) {
	if (global.bInitialized) {
		$.ajax({
			type: "POST",
			data: "{}",
			url: global.siteURL + "/Services/Misc.asmx/GetCurrencies",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function (msg) {
				callback(msg.d);
			}
		});
	}
}

function GetWinners(callback, sType, nTopN, nLengthTrim) {
	if (global.bInitialized) {
		$.ajax({
			type: "POST",
			data: "{'idCustomer' : '" + global.idCustomer + "', 'sType' : '" + sType + "','nTopN' : '" + nTopN + "'}",
			url: global.siteURL + "/Services/Misc.asmx/GetGameWinners",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function (msg) {
				callback($.evalJSON(msg.d), nLengthTrim);
			}
		});
	}
}

function PlKeepAlive(callback) {
	if (global.bInitialized) {
		$.ajax({
			type: "POST",
			data: "{}",
			url: global.siteURL + "/Services/Misc.asmx/KeepAlive",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function (msg) {
				if (msg.d != "True") {
					callback();
				}
			}
		});
	}
}

function LogOut() {
	if (global.bInitialized) {
		$.ajax({
			type: "POST",
			data: "{}",
			url: global.siteURL + "/Services/Misc.asmx/Logout",
			async: false,
			contentType: "application/json; charset=utf-8",
			dataType: "json"
		});
	}
}

function LogFlashError(context) {
	if (global.bInitialized) {
		$.ajax({
			type: "POST",
			url: global.siteURL + "/Services/Misc.asmx/LogClientError",
			data: "{'contextKey':'" + context + "'}",
			contentType: "application/json; charset=utf-8",
			dataType: "json"
		});
	}
}

function PlValidateNick(context, callback) {
	if (global.bInitialized) {
		$.ajax({
			type: "POST",
			url: global.siteURL + "/Services/Misc.asmx/ValidateNickname",
			data: "{'contextKey':'" + context + "'}",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function (msg) {
				callback(msg.d);
			}
		});
	}
}

function GetPlayLink(idType, idDef, idPackage) {
	if (global.bInitialized) {
		var res = $.ajax({
			type: "POST",
			url: global.siteURL + "/Services/Misc.asmx/GetPlayLink",
			data: "{'idType':'" + idType + "', 'idDef':'" + idDef + "', 'idPackage':'" + idPackage + "', 'idCustomer':'" + global.idCustomer + "'}",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			async: false
		});

		return $.evalJSON($.evalJSON(res.responseText).d);
	}
	else {
		return "";
	}
}

function GetPlayersInRooms(callback) {
	if (global.bInitialized) {
		$.ajax({
			type: "POST",
			url: global.siteURL + "/Services/Misc.asmx/GetPlayers",
			data: "{}",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function (msg) {
				var result = $.evalJSON(msg.d);
				callback(result.ListRooms, result.ListPlayers);
			}
		});
	}
}

function GetPlNotes(idPlayer, callback) {
	if (global.bInitialized) {
		$.ajax({
			type: "POST",
			url: global.siteURL + "/Services/NotesReader.asmx/ReadAll",
			data: "{'idPlayer':'" + idPlayer + "'}",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function (msg) {
				callback(msg.d);
			}
		});
	}
}

function GetPlSounds(idPlayer, callback) {
	if (global.bInitialized) {
		$.ajax({
			type: "POST",
			url: global.siteURL + "/Services/SoundReader.asmx/Read",
			data: "{'idPlayer':'" + idPlayer + "'}",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function (msg) {
				callback(msg.d);
			}
		});
	}
}

function GetJpWinners(idAccount, idCurrency, idLang, idGameType, idDef, idPackage, nJackpotCounter, callback) {
	if (global.bInitialized) {
		$.ajax({
			type: "POST",
			url: global.siteURL + "/Services/GamesInfo.asmx/GetJackpotWinners",
			data: "{'idAccount':'" + idAccount + "', 'idCurrency':'" + idCurrency + "', 'idLang':'" + idLang + "', 'idGameType':'" + idGameType + "', 'idDef':'" + idDef + "', 'idPackage':'" + idPackage + "', 'nJackpotCounter':'" + nJackpotCounter + "', 'idCustomer':'" + global.idCustomer + "'}",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function (msg) {
				var result = $.evalJSON(msg.d);
				callback(result.Count, result.List);
			}
		});
	}
}

function AddToFav() {
	if (document.all) {
		window.external.AddFavorite(global.siteResolvedURL, global.appName);
	}
	else if (window.sidebar) {
		window.sidebar.addPanel(global.appName, global.siteResolvedURL, "");
	}
	else if (window.external) {
		window.external.AddFavorite(global.siteResolvedURL, global.appName);
	}
}

/////////////////////////////////////////////////////////////////
//// Buttons JS
/////////////////////////////////////////////////////////////////
function over(img) {
	var suffix = "ov";
	var c = img.src;
	var pos = c.lastIndexOf(".");
	img.src = c.substring(0, pos - suffix.length) + suffix + c.substring(pos);
}

function out(img) {
	var suffix = "ot";
	var c = img.src;
	var pos = c.lastIndexOf(".");
	img.src = c.substring(0, pos - suffix.length) + suffix + c.substring(pos);
}

function overTop(anchor) {
	var suffix = "ov";
	var c = anchor.parentNode.className;
	anchor.className = c.substr(0, c.length - suffix.length) + suffix;
	anchor.parentNode.className = anchor.className;
}

function outTop(anchor) {
	var suffix = "ot";
	var c = anchor.className;
	anchor.className = c.substr(0, c.length - suffix.length) + suffix;
	anchor.parentNode.className = anchor.className;
}

/////////////////////////////////////////////////////////////////
//// Common JS
/////////////////////////////////////////////////////////////////
function attachGlobalEvent(type, func) {
	if (typeof window.addEventListener != 'undefined') {
		//.. gecko, safari, konqueror and standard
		window.addEventListener(type, func, false);
	}
	else if (typeof document.addEventListener != 'undefined') {
		//.. opera 7
		document.addEventListener(type, func, false);
	}
	else if (typeof window.attachEvent != 'undefined') {
		//.. win/ie
		window.attachEvent('on' + type, func);
	}
}

function getTarget(e) {
	var target;

	if (window.event) {
		target = window.event.srcElement;
	}
	else if (e) {
		target = e.target;
	}

	return target;
}

function getEvent(e) {
	var evt;

	if (window.event) {
		evt = window.event;
	}
	else if (e) {
		evt = e;
	}

	return evt;
}

g_abResourceSent = new Array(false, false, false, false, false);

function submitOnce(idResource, theForm) {
	if (idResource > 5) {
		// Too big resource number, but better allow form send
		return true;
	}

	if (!(g_abResourceSent[idResource])) {
		g_abResourceSent[idResource] = true;

		if (typeof (theForm.btnToDisable) == 'object') {
			// The image used as buttons can't be disabled
			theForm.btnToDisable.disabled = true;
		}

		return true;
	}
	else {
		return false;
	}
}


function disableAllButtons(idResource, button) {
	//Note: Be aware when applying this function together with function submitOnce on one page because they both make use of array g_abResourceSent.

	if (idResource > g_abResourceSent.length - 1) {
		// Too big resource number, but better allow form send
		return true;
	}

	if ((typeof (Page_ClientValidate) == 'function') && !Page_ClientValidate()) {
		return false;
	}

	if (!(g_abResourceSent[idResource])) {
		theForm = document.forms[idResource];

		for (var i = 0; i < theForm.elements.length; i++) {
			elm = theForm.elements[i];
			if ((elm.tagName == 'INPUT') && (elm.type == 'submit')) {
				elm.disabled = true;
			}
		}

		g_abResourceSent[idResource] = true;

		return true;
	}
	else {
		return false;
	}
}



function clickOnce(button) {
	var IsPageValid = true
	if (typeof (Page_ClientValidate) == 'function') {
		IsPageValid = Page_ClientValidate();
	}

	if (IsPageValid) {
		button.click();
		button.value = " Please wait, submitting ... "
		button.disabled = true;
	}
}



function message(txt) {
	alert(txt);
	return false
}



function setSelectDefault(formID, elmName, defaultValue) {
	for (var i = 0; i < document.forms[formID].elements[elmName].length; i++)
		if (document.forms[0].elements[elmName].options[i].value == defaultValue)
			document.forms[0].elements[elmName].options[i].selected = true;
}



function NewWindowRes(mypage, myname, w, h, scroll, resizable) {
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	var win = null;
	winprops = 'height=' + h + ',width=' + w + ',top=' + wint + ',left=' + winl + ',scrollbars=' + scroll + ',resizable=' + resizable;
	win = window.open(mypage, myname, winprops)

	if (parseInt(navigator.appVersion) >= 4) {
		win.window.focus();
	}
}

function NewWindow(mypage, myname, w, h, scroll) {
	NewWindowRes(mypage, myname, w, h, scroll, 'yes');
}

function popUp(strURL, strHeight, strWidth) {
	strOptions = "height=" + strHeight + ",width=" + strWidth + ",location=yes,status=yes,scrollbars=yes,resizable=yes";
	newWin = window.open(strURL, 'newWin', strOptions);
	newWin.focus();
}


function checkOne(theFormElement, message) {
	if (theFormElement.value == "") {
		theFormElement.focus();
		alert(message);
		return false;
	}
	else return true;
}


function trimText(item, maxWidth) {
	var text = item.text();

	while (item.width() > maxWidth) {	   
		text = text.substring(0, text.length - 2);
		item.text(text + "...");
	}
}


function checkForm(theForm) {
	var theElements = new Array(11)
	theElements[0] = 'BIFirstName'
	theElements[1] = 'BILastName'
	theElements[2] = 'BICountry'
	theElements[3] = 'BIState'
	theElements[4] = 'BICity'
	theElements[5] = 'BIZip'
	theElements[6] = 'BIEmail'
	theElements[7] = 'BIPhone'
	theElements[8] = 'BIAddress'
	theElements[9] = 'cardnumber'
	theElements[10] = 'BICCHolder'
	var messages = new Array(11)
	messages[0] = 'First Name'
	messages[1] = 'Last Name'
	messages[2] = 'Country'
	messages[3] = 'State'
	messages[4] = 'City'
	messages[5] = 'Zip'
	messages[6] = 'E-mail'
	messages[7] = 'Phone'
	messages[8] = 'Address'
	messages[9] = 'Credit Card No'
	messages[10] = 'Card Holder'
	for (var i = 0; i < theElements.length; i++) return checkOne(theForm.elements[theElements[i]], 'Please enter your ' + messages[i]);
	return true;
}


function ShowBonus(lstID, bonusID) {
	var bonus = document.getElementById(lstID);
	if (bonus != null) {
		var aVals = bonus.value.split('|');
		var txt = aVals[1];
		document.getElementById(bonusID).innerHTML = txt;
	}
}

//using in MyCitadel
function openLink(url) {
	msgWindow = window.open(url)
	msgWindow.window.opener = null
	document.getElementById("ErrorMessage").style.visibility = "hidden"
	document.getElementById("InfoMessage").style.visibility = "hidden"
}


function dumpObject(object, depth, max) {
	depth = depth || 0;
	max = max || 2;

	if (depth > max)
		return false;

	var indent = '';
	for (var i = 0; i < depth; i++) indent += '  ';

	var output = '';
	for (var key in object) {
		output += '\n' + indent + key + ': ';
		switch (typeof object[key]) {
			case 'object':
				output += dumpObject(object[key], depth + 1, max);
				break;

			case 'function':
				output += 'function';
				break;

			default:
				output += object[key];
				break;
		}
	}

	return output;
}


var oldStamp = 0;


function UpdateMoney(msg, stamp) {
	var daubletts = document.getElementById('daublettsField');
	if (daubletts) {
		if (oldStamp < stamp) {
			oldStamp = stamp
			daubletts.innerHTML = msg;
		}
	}
}

/////////////////////////////////////////////////////////////////
//// Flash JS
/////////////////////////////////////////////////////////////////
var childWins;
var registered;

function GetMovie(movieName) {
	if (document[movieName]) {
		return document[movieName];
	}

	return window[movieName];
}

function OpenChild(url, name) {
	if (childWins == undefined) {
		childWins = new Array();
	}

	var childWin = null;
	var w = 800;
	var h = 600;

	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;

	var winprops = 'height=' + h + ',width=' + w + ',top=' + wint + ',left=' + winl + ',scrollbars=no,resizable=yes,status=no,toolbar=no,menubar=no,location=no';

	if (null != name) {
		if (childWins[name] && !childWins[name].closed) {
			if (parseInt(navigator.appVersion) >= 4) {
				childWins[name].window.focus();
			}
		}
		else {
			childWin = window.open(url, name, winprops);

			if (parseInt(navigator.appVersion) >= 4) {
				childWin.window.focus();
			}

			childWins[name] = childWin;
		}
	}
	else {
		window.open(url, name, winprops);
	}
}

function OpenGameByFlash(idType, idDef, idPackage) {
	if (global.idPlayer != 0) {
		var json = GetPlayLink(idType, idDef, idPackage);

		OpenChild(json.Url, json.WindowName);
	}
	else {
		window.location.href = global.siteResolvedURL + 'Login.aspx';
	}
}

function CloseChild(name) {
	var childWin = childWins[name];
	if (childWin && childWin.open && !childWin.closed) childWin.close();
}

function RegisterForUpdate(windowname) {
	if (registered == undefined) {
		registered = new Array();
	}
	registered[windowname] = childWins[windowname];
}

function OpenWindow(strUrl, winObj, winName) {
	try {
		if (strUrl != "") {
			if (winObj && !winObj.closed) {
				winObj.location.href = strUrl;
				winObj.focus();
			}
			else {
				var w = 900;
				var h = 900;

				var winl = (screen.width - w) / 2;
				var wint = (screen.height - h) / 2;

				var sProps = 'height=' + h + ',width=' + w + ',top=' + wint + ',left=' + winl + ',scrollbars=yes,resizable=yes,status=yes,toolbar=yes,menubar=yes,location=yes';

				winObj = window.open(strUrl, winName, sProps);
				winObj.focus();

				if (global.bFlashMaximized) {
					winObj.moveTo(0, 0);
					winObj.resizeTo(screen.width, screen.height);
				}
			}
		}
	}
	catch (exc) {
		var err = '(Javascript) OpenUrl error:\n' + dumpObject(exc);

		// LogClientError( err );
	}
}

// Form Posting
function PostToUrl(path, params, method) {
	method = method || "post"; // Set method to post by default, if not specified.

	var form = document.createElement("form");
	form.setAttribute("method", method);
	form.setAttribute("action", path);

	for (var key in params) {
		var hiddenField = document.createElement("input");
		hiddenField.setAttribute("type", "hidden");
		hiddenField.setAttribute("name", key);
		hiddenField.setAttribute("value", params[key]);

		form.appendChild(hiddenField);
	}

	document.body.appendChild(form);
	form.submit();
}

function TryLogin(user, pass) {
	var url = global.siteResolvedURL + "Login.aspx";

	if (window.location.toString().toLowerCase().indexOf("login.aspx") == -1) {
		if (global.bSecured) {
			url = url.replace("http:", "https:");
		}
	}

	PostToUrl(url, { "Username": user, "Password": pass });

	return false;
}

// Player Management
var playerCreditsTimer = -1;
var playerCreditsContainer;

function LoadCredits(container) {
	if (global.bIsPlLogged) {
		playerCreditsContainer = container;
		$("#" + container).html("Loading...");
		GetPlCredits(true, false, OnCreditsReceived);
	}
}

function LoadPlMoney(container) {
    if (global.bIsPlLogged) {
        playerCreditsContainer = container;
        $("#" + container).html("Loading...");
        GetPlMoney(true, false, OnMoneyReceived);
    }
}

function LoadLoyaltyPoints(container) {
	if (global.bIsPlLogged) {
		$("#" + container).html("Loading...");
		GetPlAffPoints(function (res) {
			$("#" + container).html(res);
		});
	}
}

function OnMoneyReceived(money) {
    if (money != "") {
        // Successfull call, continue getting credits
        if (playerCreditsTimer == -1) {
            // First call, start timer
            playerCreditsTimer = self.setInterval(function () {
                GetPlMoney(true, false, OnMoneyReceived);
            }, global.tsMoney);
        }
        // Update money
        $("#" + playerCreditsContainer).html(money);
    } else {
        // Stop timer
        if (playerCreditsTimer != -1) {
            window.clearInterval(playerCreditsTimer);
        }
        
		$("#" + playerCreditsContainer).html("N/A");

		if (global.bIsPlLogged) {
			window.location.reload(true);
		}
    }
}

function OnCreditsReceived(credits) {
	if (credits != "") {
		// Successfull call, continue getting credits
		if (playerCreditsTimer == -1) {
			// First call, start timer
			playerCreditsTimer = self.setInterval(function () {
				GetPlCredits(true, false, OnCreditsReceived);
			}, global.tsMoney);
		}
		// Update money
		$("#" + playerCreditsContainer).html(credits);
	} else {
		// Stop timer
		if (playerCreditsTimer != -1) {
			window.clearInterval(playerCreditsTimer);
		}
		$("#" + playerCreditsContainer).html("N/A");
	}
}

function UpdatePlayedGames(container) {
	if (global.bIsPlLogged) {
		var cookies = document.cookie;

		if (cookies.indexOf(global.Latest5Cookie) != -1) {

			var startpos = cookies.indexOf(global.Latest5Cookie) + global.Latest5Cookie.length + 1;
			var endpos = cookies.indexOf(";", startpos) - 1;

			if (endpos == -2) endpos = cookies.length;

			var games = unescape(cookies.substring(startpos, endpos)).split(",");

			$("#" + container).html("");

			$.each(eval(games), function (i, el) {
				var html = $("[name=" + el + "]").parent().html();
				if (html != null) {
					$("#" + container).append('<li>' + html + '</li>');
				}
			});
		}
	}
}

function LoadHallsFlash() {
	var id = "halls_movie";

	AC_FL_RunContent(
		'codebase', GetHttpOrHttps() + '://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0',
		'width', '100%',
		'height', '100%',
		'src', global.siteLocalURL + 'Client/' + global.culture + '/HallsMenu?CurrencyID=' + global.idCurrency + '&LanguageID=' + global.idLang + '&customerid=' + global.idCustomer + '&URL=' + global.siteURLClear,
		'quality', 'high',
		'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
		'align', 'middle',
		'play', 'true',
		'loop', 'true',
		'scale', 'showall',
		'wmode', 'Transparent',
		'devicefont', 'false',
		'id', id,
		'bgcolor', '#ffffff',
		'name', id,
		'menu', 'true',
		'allowFullScreen', 'false',
		'allowScriptAccess', 'allowAll',
		'movie', global.siteLocalURL + 'Client/' + global.culture + '/HallsMenu?CurrencyID=' + global.idCurrency + '&LanguageID=' + global.idLang + '&customerid=' + global.idCustomer + '&URL=' + global.siteURLClear,
		'salign', 'lt');

	window[id] = document.getElementById(id);
}

function MM_reloadPage(init) {  //reloads the window if Nav4 resized
	if (init == true) with (navigator) {
		if ((appName == "Netscape") && (parseInt(appVersion) == 4)) {
			document.MM_pgW = innerWidth; document.MM_pgH = innerHeight; onresize = MM_reloadPage;
		} 
	}
	else if (innerWidth != document.MM_pgW || innerHeight != document.MM_pgH) location.reload();
}
MM_reloadPage(true);

function MM_swapImgRestore() { //v3.0
	var i, x, a = document.MM_sr; for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++) x.src = x.oSrc;
}

function MM_findObj(n, d) { //v4.01
	var p, i, x; if (!d) d = document; if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
		d = parent.frames[n.substring(p + 1)].document; n = n.substring(0, p);
	}
	if (!(x = d[n]) && d.all) x = d.all[n]; for (i = 0; !x && i < d.forms.length; i++) x = d.forms[i][n];
	for (i = 0; !x && d.layers && i < d.layers.length; i++) x = MM_findObj(n, d.layers[i].document);
	if (!x && d.getElementById) x = d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
	var i, j = 0, x, a = MM_swapImage.arguments; document.MM_sr = new Array; for (i = 0; i < (a.length - 2); i += 3)
		if ((x = MM_findObj(a[i])) != null) { document.MM_sr[j++] = x; if (!x.oSrc) x.oSrc = x.src; x.src = a[i + 2]; }
}

function formatMoney(credits, currency) {

	return convertIsoToSign(currency.IsoCode) + " " + addCommas((credits.Amount.toFixed(2) / currency.Fractions).toFixed(2));
}

function formatMoneyAmount(amount, currency) {
	return convertIsoToSign(currency.IsoCode) + " " + addCommas((amount / currency.Fractions).toFixed(2));
}

function convertIsoToSign(iso) {
	var sign = "";

	switch (iso) {
		case "USD": sign = "$"; break;
		case "EUR": sign = "&euro;"; break;
	}

	return sign;
}

function addCommas(str) {
	str += '';
	x = str.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;
}
