﻿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 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: "{'sType' : '" + sType + "','nTopN' : '" + nTopN + "','nLengthTrim' : '" + nLengthTrim + "'}",
            url: global.siteURL + "/Services/Misc.asmx/GetWinners",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
            
            callback($.evalJSON(msg.d));
            }
        });
    }
}

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 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 c = img.src;
    var pos = c.lastIndexOf(".");
    img.src = c.substring(0, pos - 3) + "_ov" + c.substring(pos);
}

function out(img) {
    var c = img.src;
    var pos = c.lastIndexOf(".");
    img.src = c.substring(0, pos - 3) + "_ot" + c.substring(pos);
}

function overTop(anchor) {
    var c = anchor.parentNode.className;
    anchor.className = c.substr(0, c.length - 3) + "_ov";
    anchor.parentNode.className = anchor.className;
}

function outTop(anchor) {
    var c = anchor.className;
    anchor.className = c.substr(0, c.length - 3) + "_ot";
    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 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 (false && winObj && !winObj.closed) {// always in new window
                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 );
    }
}

function LoadJpMovie(idJp, idPackage, color) {
	id = GetJpMovieName(idJp, idPackage);

	var url = global.siteURL + '/Includes/Flash/WebPageJP?' +
	    'color=' + color +
	    '&currency=' + global.idCurrency +
	    '&idCustomer=' + global.idCustomer +
	    '&strNameSpace=' + 'http://tempuri.org/' +
	    '&idPackage=' + idPackage +
	    '&idJackpot=' + idJp +
	    '&urlPath=' + global.siteURL + '/Services/Misc.asmx';

	AC_FL_RunContent(
		'codebase', GetHttpOrHttps() + '://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0',
		'width', '100%',
		'height', '100%',
		'src', url,
		'quality', 'high',
		'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
		'align', 'middle',
		'play', 'true',
		'loop', 'true',
		'scale', 'exactfit',
		'wmode', 'Transparent',
		'devicefont', 'false',
		'id', id,
		'bgcolor', '#ffffff',
		'name', id,
		'menu', 'true',
		'allowFullScreen', 'false',
		'allowScriptAccess', 'allowAll',
		'movie', url,
		'salign', 'lt');

	// Save object
	window[id] = document.getElementById(id);
}

function GetJpMovieName(idJp, idPackage) {
	return "jackpot_" + idJp + "_" + idPackage;
}

// 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 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 (plCreditsTimer != -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 = $("#" + el).parent().html();
				if (html != null) {
					$("#" + container).append("<tr><td>" + html + "</td></tr>");
				}
			});
		}
	}
}

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', '460',
		'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);
}