﻿
var CICFramework = {};
CICFramework.includedJavascript = new Array();
CICFramework.contentDivisionArray = new Array();

var CasinoProcess = '';

if (typeof String.prototype.trim !== 'function') {
    String.prototype.trim = function () {
        return this.replace(/^\s+|\s+$/g, '');
    }
}


function hasClass(ele, cls) {
    return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}

function removeClass(ele, cls) {
    if (hasClass(ele, cls)) {
        var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
        ele.className = ele.className.replace(reg, '');
    }
}

function handleError(message) {
    alert("Error occured : " + message);
}

function handleException(ex, source, sourceSub) {
    alert("Exception occured : " + source + " - " + sourceSub + ".\n" + ex.message);
}

function parseJSON(JSON, methodname) {
    var Source = 'Main';
    if (methodname != null) {
        Source = methodname;
    }
    try {
        return eval("(" + JSON + ")");
        //return YAHOO.lang.JSON.parse(JSON);
    }
    catch (ex) {
        handleException(ex, "parseJSON", Source);
    }
    return null;
}

var displayContent = function (data, loadIn, postLoad, extendedData) {
    try {

        document.getElementById(loadIn).innerHTML = data;
        try {
            //alert(postLoad);
            eval(postLoad);
        }
        catch (ex) {
            handleException(ex, "displayContent", "Postload");
        }
    }
    catch (ex) {
        handleException(ex, "displayContent", "Main");
    }
}

var loadPage = function (data, loadIn, postLoad, extendedData, historyObject) {
    //alert(data);
    var pageObj = parseJSON(data);
    if (pageObj) {
        if (pageObj.status == "OK") {
            //Page title
            try {
                document.title = "CIC Configuration Panel - " + pageObj.pagename;
            }
            catch (ex) {
                handleError("Page title update failed.\nSource: [loadPage]");
            }
            /*History management
            if (historyObject) {
            historyObject.pageName = pageObj.pagename;
            $.history(historyObject);
            //Threadbar management
            saveThreadbarInfo(historyObject);
            }*/
            //Page preload
            try {
                //alert(pageObj.pagepreload);
                if (pageObj.pagepreload) {
                    eval(pageObj.pagepreload);
                }
            }
            catch (ex) {
                handleError("Page preload failed.\nSource: [loadPage]\nTried: " + pageObj.pagepreload + "\nError:" + ex.message);
            }
            //Process needed Javascript includes
            if (pageObj.javascriptincludes) {
                for (var i = 0; i < pageObj.javascriptincludes.length; i++) {
                    includeJavascript(pageObj.javascriptincludes[i].javascriptincludepath, false);
                }
            }
            //Process individual loads for this page
            if (pageObj.content) {
                for (var j = 0; j < pageObj.content.length; j++) {
                    //Display loadIn
                    manageDisplayWindow(pageObj.content[j].layoutdestination, "show");
                    //Process content item
                    if (pageObj.content[j].componenttypeid == 1) {
                        var frameworkData = "framework_componentid=" + pageObj.content[j].componentid + "&framework_componenttypeid=" + pageObj.content[j].componenttypeid;
                        if (extendedData) {
                            frameworkData += "&" + extendedData;
                        }
                        //alert(frameworkData);
                        ajaxRequest(pageObj.content[j].componenturl, frameworkData, pageObj.content[j].componentpreload, pageObj.content[j].componentpostload, displayContent, pageObj.content[j].layoutdestination, null);
                    }
                    else if (pageObj.content[j].componenttypeid == 2) {
                        //alert("Grid component load definition needed...");
                        createGrid(pageObj.content[j].componentid, pageObj.content[j].layoutdestination, pageObj.content[j].componentname, pageObj.content[j].componenttitle);
                    }
                    else if (pageObj.content[j].componenttypeid == 3) {
                        alert("Form component load definition needed...");
                    }
                    else if (pageObj.content[j].componenttypeid == 4) {
                        displayContent(pageObj.content[j].componentcmscontent, pageObj.content[j].layoutdestination, pageObj.content[j].componentpostload, frameworkData);
                    }
                    else {
                        handleError("Component type load definition not found.\nSource: [loadPage]");
                    }
                }
            }
        }
        else {
            handleError("AJAX page load reported the following status:\n" + pageObj.status);
        }
    }
    else {
        handleError("AJAX page load returned no data.");
    }
}

var executeAction = function (data, loadIn, postLoad, extendedData) {
    //alert(data);
    var actionObj = parseJSON(data);
    if (actionObj) {
        if (actionObj.status == "OK") {
            //Acttion preload
            try {
                if (actionObj.actionpreloadjs) {
                    eval(actionObj.actionpreloadjs);
                }
            }
            catch (ex) {
                handleError("Action preload failed.\nSource: [executeAction]\nTried: " + actionObj.actionpreloadjs + "\nError:" + ex.message);
            }
            //Page load
            try {
                if (actionObj.uniquepageid) {
                    getPage(actionObj.uniquepageid, extendedData, actionObj.skiphistorywrite);
                }
            }
            catch (ex) {
                handleError("Action page load failed.\nSource: [executeAction]\nError:" + ex.message);
            }
        }
        else {
            handleError("AJAX page load reported the following status:\n" + actionObj.status);
        }
    }
    else {
        handleError("AJAX action load returned no data.");
    }
}

function getAction(actionname, componentid, extendedData) {
    //Fetch action
    //alert("actionname:" + actionname + "\ncomponentid:" + componentid + "\nextendedData:" + extendedData);
    var page = "/frameworkjsonprovider.aspx";
    var data = "action=getactionjson&actionname=" + actionname + "&componentid=" + componentid;
    ajaxRequest(page, data, null, null, executeAction, null, extendedData);
}

function getPage(id, extendedData, skipHistoryWrite) {
    //alert('hi')
    if (id) {
        //Clearing variables
        //ClearVariables();
        //alert("getPage:" + id);
        var historyObject = null;
        //alert(skipHistoryWrite);
        if (!(skipHistoryWrite)) {
            historyObject = { "uniqueid": id, "extendedData": extendedData }
            //alert("saving history id : " + historyObject.uniqueid + "\nwith data : " + historyObject.extendedData);
        }
        var page = "/frameworkjsonprovider.aspx";
        var data = "action=getpagejson&uniqueid=" + id;
        ajaxRequest(page, data, null, null, loadPage, null, extendedData, historyObject);
    }
}

//////////////////////////////////////////////////////////////////////////////////////////////
//THREADBAR HANDLING
//////////////////////////////////////////////////////////////////////////////////////////////
var threadBarContents = new Array();

function saveThreadbarInfo(historyObject) {
    //Add new object
    threadBarContents.push(historyObject);
    //Remove first item if length > 4
    if (threadBarContents.length > 4) {
        threadBarContents.shift();
    }
    updateThreadbarDisplay();
}

function updateThreadbarDisplay() {
    //alert("updating threadbar...");
    window.setTimeout(function () {
        try {
            var outputContent = "";
            for (var i = 0; i < threadBarContents.length; i++) {
                //alert(threadBarContents[i].pageName);
                outputContent += "<div class=\"float_left\"><a id=\"" + threadBarContents[i].uniqueid + "\" class=\"button_threadbar threadbarajax\" href=\"/home\"><span>" + threadBarContents[i].pageName + "</span></a></div>";
            }
            outputContent += "<div class=\"theplug\"></div>";
            $(document.getElementById("threadbarContainer")).html(outputContent);
            initialiseThreadbarAjax();
        }
        catch (ex) {
            handleException(ex, "updateThreadbarDisplay", "Timeout");
        }
    }, 0);
}

//////////////////////////////////////////////////////////////////////////////////////////////
//FORM INPUT HANDLING
//////////////////////////////////////////////////////////////////////////////////////////////
/*
A generalised form submitting function that returns the contents of a form in URL querystring
jQuery serialize() method could be a replacement for this.
*/
function extractFormData(formToProcess) {
    var theform;
    if (formToProcess) {
        theform = document.getElementById(formToProcess);
    }
    else {
        theform = null;
    }

    var queryString = "";
    var addString = "";
    if (theform) {
        try {
            for (var i = 0; i < theform.elements.length; i++) {
                if (theform.elements[i].name != '__VIEWSTATE' && theform.elements[i].name != '__dnnVariable') {
                    if (queryString == "") {
                        addString = "";
                    }
                    else {
                        addString = "&";
                    }
                    if (theform.elements[i].type == "radio") {
                        if (theform.elements[i].checked) {
                            addString += theform.elements[i].name + "=" + encodeURIComponent(theform.elements[i].value);
                        }
                    }
                    else {
                        if (theform.elements[i].type == "checkbox") {
                            if (theform.elements[i].checked) {
                                addString += theform.elements[i].name + "=" + 1;
                            }
                            else {
                                addString += theform.elements[i].name + "=" + 0;
                            }
                        }
                        else {
                            if (theform.elements[i].type == "select-multiple") {
                                for (j = 0; j < theform.elements[i].options.length; j++) {
                                    if (theform.elements[i].options[j].selected) {
                                        if (addString != "" && addString != "&") {
                                            addString += "&";
                                        }
                                        addString += theform.elements[i].name + "=" + encodeURIComponent(theform.elements[i].options[j].value);
                                    }
                                }
                            }
                            else {
                                //Meaning : Hidden, Text or Single-Select : All treated equally without discrimination... :-)
                                if (typeof (theform.elements[i].value) != 'undefined' && theform.elements[i].value != null) {
                                    if (theform.elements[i].type != 'button') {
                                        //alert(theform.elements[i].type + ': ' + theform.elements[i].id + ': '  + theform.elements[i].value);
                                        addString += theform.elements[i].name + "=" + encodeURIComponent(theform.elements[i].value);
                                    }
                                }
                            }
                        }
                    }
                    if (addString != "&") {
                        queryString += addString;
                    }
                }
            }
        }
        catch (ex) {
            handleError("Error occured processing input form '" + formToProcess + "'.\nSource: [fetchInputFormData].\nDetail: " + ex.message);
        }
    }
    else {
        //alert("Invalid input form specified.");
    }
    //alert(queryString);
    theform = null;
    return queryString;
}

//////////////////////////////////////////////////////////////////////////////////////////////
//DYNAMIC JAVASCRIPT INCLUSION
//////////////////////////////////////////////////////////////////////////////////////////////
function initialiseLoadedJavascript(loadedScripts) {
    try {
        var scriptObj = parseJSON(loadedScripts);
        if (scriptObj.scripts) {
            for (var i = 0; i < scriptObj.scripts.length; i++) {
                includeJavascript(scriptObj.scripts[i], true);
            }
        }
    }
    catch (ex) {
        handleError("Error occured processing initially loaded Javascript .\nSource: [initialiseLoadedJavascript].\nDetail: " + ex.message);
    }
}

function checkIncludedJavascript(scriptSource) {
    if (CICFramework.includedJavascript) {
        for (var i = 0; i < CICFramework.includedJavascript.length; i++) {
            if (CICFramework.includedJavascript[i] == scriptSource) {
                return true;
            }
        }
    }
    return false;
}

function includeJavascript(scriptSource, addToCollectionWithoutIncluding) {
    if (scriptSource.toString().length > 0) {
        if (!(checkIncludedJavascript(scriptSource))) {
            //Include this script
            CICFramework.includedJavascript.push(scriptSource);
            if (!(addToCollectionWithoutIncluding)) {
                var script = document.createElement("script");
                script.type = "text/javascript";
                script.src = scriptSource;
                document.getElementsByTagName("head")[0].appendChild(script);
                //alert('Loaded "' + scriptSource +'".');
            }
        }
        else {
            //alert('Script "' + scriptSource +'" is already loaded. Skipping...');
        }
    }
    else {
        handleError("No Javascript file was specified to include.\nSource: [includeJavascript]");
    }
}

//////////////////////////////////////////////////////////////////////////////////////////////
//WINDOW MANAGEMENT
//////////////////////////////////////////////////////////////////////////////////////////////
/*
General display management function
*/
function manageDisplayWindow(objToProcess, manageModifier) {
    var thediv = document.getElementById(objToProcess);
    if (thediv) {
        if (manageModifier == "show") {
            thediv.style.display = "block";
        }
        if (manageModifier == "hide") {
            thediv.style.display = "none";
        }
        if (manageModifier == "close") {
            thediv.innerText = "";
            manageDisplayWindow(objToProcess, "hide");
        }
        if (manageModifier == "toggle") {
            if (thediv.style.display == "none") {
                thediv.style.display = "block";
            }
            else {
                thediv.style.display = "none";
            }
        }
    }
    else {
        handleError("Division '" + objToProcess + "' was not found in the page.\nSource: [manageDisplayWindow]");
    }
    //thediv = null;
}

function initialiseContent(contentArray) {
    //alert(contentArray);
    try {
        CICFramework.contentDivisionArray = parseJSON(contentArray);
    }
    catch (ex) {
        handleException(ex, "initialiseContent", "Main")
    }
}
/*
A function to hide and clear the regular content display.
*/
function contentHider() {
    //Clear content divisions
    try {
        var useArray = CICFramework.contentDivisionArray;
        for (var i = 0; i < useArray.length; i++) {
            if (useArray[i].division == 'bottomcontent') {
                if (useArray[i].allowcontenthide) {
                    manageDisplayWindow(useArray[i].division, "close");
                }
            }
        }
    }
    catch (ex) {
        handleError("Error occured while hiding content.\nSource: [contentHider].\nDetail: " + ex.message);
    }
}

function numbersonly(e) {
    //evt = e || window.event;

    var unicode; //= evt.which || evt.keyCode;

    unicode = (window.event) ? event.keyCode : e.which;
    //alert(unicode);

    if (unicode != 8 && unicode != 13) { //if the key isn't the backspace key (which we should allow)
        if (unicode > 31 && (unicode < 48 || unicode > 57))//if not a number
            return false; //disable key press
    }
}

function floatnumbersonly(e) {
    var unicode; //= evt.which || evt.keyCode;

    unicode = (window.event) ? event.keyCode : e.which;

    if (unicode != 8 && unicode != 13) { //if the key isn't the backspace key (which we should allow)
        if ((unicode < 48 || unicode > 57) && (unicode > 31) && (unicode != 46)) //if not a number
            return false; //disable key press
    }
}
function fncInputNumericValuesOnly() {
    if (!(event.keyCode == 45 || event.keyCode == 46 || event.keyCode == 48 || event.keyCode == 49 || event.keyCode == 50 || event.keyCode == 51 || event.keyCode == 52 || event.keyCode == 53 || event.keyCode == 54 || event.keyCode == 55 || event.keyCode == 56 || event.keyCode == 57)) {
        event.returnValue = false;
    }
}

function isEnterKey(e) {
    var unicode; //= evt.which || evt.keyCode;

    unicode = (window.event) ? event.keyCode : e.which;
    if (unicode == 13) {
        return true;
    }
    else {
        return false;
    }
}


function Left(str, n) {
    if (n <= 0)
        return "";
    else if (n > String(str).length)
        return str;
    else
        return String(str).substring(0, n);
}

function Right(str, n) {
    if (n <= 0)
        return "";
    else if (n > String(str).length)
        return str;
    else {
        var iLen = String(str).length;
        return String(str).substring(iLen, iLen - n);
    }
}

function SearchList(ObjInput, ListBox, e) {
    if (isEnterKey(e) == true) {
        var ObjList = document.getElementById(ListBox);
        if (ObjInput.value != '') {

            var SearchIn = '';
            var SearchArr;
            var SearchInArr;
            var Match = false;
            var SearchText = ObjInput.value.toUpperCase();
            var OptionsLen = ObjList.options.length;
            var OptionStart = 0;

            if (eval(ObjList.selectedIndex) == OptionsLen) {
                OptionStart = 0;
            }
            else if (ObjList.selectedIndex > -1) {
                OptionStart = eval((ObjList.selectedIndex) + 1);
            }

            for (var h = 0; h < OptionsLen; h++) {
                ObjList.options[h].selected = false;
            }

            for (var k = OptionStart; k < OptionsLen; k++) {
                SearchIn = ObjList.options[k].text.toUpperCase();

                SearchInArr = SearchIn.split(/\s/g)
                //SearchArr = SearchText.split(/\s/g)
                for (j = 0; j < SearchInArr.length; j++) {
                    //for (p=0;p<SearchArr.length;p++)
                    //{
                    //alert(SearchInArr[j]);
                    var SearchingList = SearchInArr[j].trim();
                    if (SearchingList == SearchText.trim()) {
                        ObjList.options[k].selected = true;
                        Match = true;
                        break;
                    }
                    else {
                        var patt = eval('/' + SearchText.trim() + '/g');
                        //alert(patt);
                        if (SearchingList.match(patt)) {
                            ObjList.options[k].selected = true;
                            Match = true;
                            break;
                        }
                    }
                    //}
                    if (Match)
                        break;
                }
                if (Match == false) {
                    SearchInArr = SearchIn.split(/->/g)
                    for (j = 0; j < SearchInArr.length; j++) {
                        //for (p=0;p<SearchArr.length;p++)
                        //{
                        var SearchingList = SearchInArr[j].trim();
                        if (SearchingList == SearchText.trim()) {
                            ObjList.options[k].selected = true;
                            Match = true;
                            break;
                        }
                        else {
                            var patt = eval('/' + SearchText.trim() + '/g');
                            //alert(patt);
                            if (SearchingList.match(patt)) {
                                ObjList.options[k].selected = true;
                                Match = true;
                                break;
                            }
                        }
                        //}
                        if (Match)
                            break;
                    }
                }
                if (Match)
                    break;
            }
        }
    }
    return false;
}
function ClearOptions(len, doc) {
    for (var i = len - 1; i >= 0; i--) {
        if (doc.options[i].value != 0) {
            doc.remove(i);
        }
    }
}

function MoveListItems(lstAvailable, lstSelected, All) {
    if (All == false) {
        $('#' + lstAvailable + ' option:selected').remove().appendTo('#' + lstSelected)
    }
    else {
        $('#' + lstAvailable + ' option').remove().appendTo('#' + lstSelected)
    }
}

function RemoveFromList(Lst, Items) {
    var Removed = Items.split(',');
    var j;
    var x;
    for (j = 0; j < Removed.length; j++) {
        for (x = 0; x < Lst.options.length; x++) {
            if (Lst.options[x] != null && Lst.options[x].value == Removed[j]) {
                Lst.options[x] = null;
            }
        }
    }
}
function ClearVariables() {
    cal1 = "";
    cal = "";
    cal2 = "";
}

function escapeHTML(str) {
    var div = document.createElement('div');
    var text = document.createTextNode(str);
    div.appendChild(text);
    return div.innerHTML;
}

function IsEmpty(ObjText, Msg, AlertDiv) {
    if ($('#' + ObjText).val().length == 0) {
        if (Msg != null) {
            $('#' + AlertDiv).html(Msg);
            $('#' + ObjText).focus();
        }
        return true;
    }
    else {
        return false;
    }
}

function ValidateUserLogin() {

    var LoginStatus = 'False';

    var page = '/desktopmodules/bluestar.dottybingo.includes/includesprocess.aspx';
    var pagedata = 'action=ValidateLogin';

    var result = $.ajax({
        url: page,
        global: false,
        type: "POST",
        async: false,
        data: pagedata
    }
    ).responseText;

    var JSONRet = parseJSON(result);
    if (JSONRet) {
        if (JSONRet.status == 'OK') {
            LoginStatus = JSONRet.Login;
        }
        else {
            alert(JSONRet.ReturnVal);
        }
    }

    return LoginStatus;
}

function logOff() {
    document.getElementById('frmHeader').submit();
    return false;
}

function getClientWidth() {
    return document.compatMode == 'CSS1Compat' && !window.opera ? document.documentElement.clientWidth : document.body.clientWidth;
}

function getClientHeight() {
    return document.compatMode == 'CSS1Compat' && !window.opera ? document.documentElement.clientHeight : document.body.clientHeight;
}

var win;
var PageJSON;

function PreviewPage(mode, roomid, parentpage) {
    
    var url = '';
    
    var PageCulture = $('#PageCulture').val();

    if (mode == 'Banking') {

        var URL = '/desktopmodules/reload.aspx';
        mywin = openPopupWindow(URL, mode, 750, 500);
        GetReloadJSON('LaunchBanking');
        setTimeout("SubmitForm('" + mode + "', '" + roomid + "');", 5000);
    }
    else if (mode == 'PlayerHistory') {
        var URL = '/desktopmodules/reload.aspx';
        OpenRadWindow(URL, 450, 670, true, false, false, true);
        GetReloadJSON('LaunchHistory');
        setTimeout("SubmitForm('" + mode + "');", 2000);
    }
    else if (mode == 'PlayerGameHistory') {
        var URL = '/desktopmodules/reload.aspx';
        OpenRadWindow(URL, 450, 670, true, false, false, true);
        GetReloadJSON('LaunchGameHistory');
        setTimeout("SubmitForm('" + mode + "');", 2000);
    }
    else if (mode == 'ForgotPassword') {
        var URL = '/forgot-password.aspx'
        //openPopupWindow(URL, mode, 1080, 600, false);
        //CloseThickBox();
        //setTimeout("OpenThickBox('Forgot Password? | Dotty Bingo', '" + URL + "')", 3000);
        //CloseAndOpen('Forgot Password? | Dotty Bingo', URL);
        //alert(roomid);
        if (roomid != null) {
            if (roomid == 'newwindow') {
                OpenRadWindow(URL, 620, 1030, false, false, false, true);
            }
            else {
                CloseAndOpenRadWindow(URL, 620, 1030, true, true, false, true);
            }
        }
        else {
            CloseAndOpenRadWindow(URL, 620, 1030, true, true, false, true);
        }
    }
    else if (mode == 'Terms') {
        var URL = '/popupterms.aspx';
        if (PageCulture != 'en-GB') {
            URL = '/popupterms-' + PageCulture + '.aspx';
        }
        OpenRadWindow(URL, 620, 1030, false, false, false, true);
    }
    else if (mode == 'OneClickAlert') {
        //var URL = '/bingoalert.aspx?Identifier=' + roomid + '&TB_iframe=true&height=340&width=600';
        //var URL = '/desktopmodules/bluestar.dottybingo.includes/images/contactus.jpg';
        //openPopupWindow(URL, mode, 575, 270, false);
        //OpenThickBox('Alert | Dotty Bingo', URL);
        var url = '/oneclickalert.aspx?Identifier=' + roomid + '&parentpage=' + parentpage;
        //alert(url);
        OpenRadWindow(url, 365, 630, true, false, false, true);
    }
    else if (mode == 'OneClickAdvert') {
        var url = roomid;
        
        var winH = 0;
        var winW = 0;

        if ($.browser.mozilla == true) {
            winH = 367;
            winW = 540;
        }
        else if ($.browser.msie == true) {
            winH = 335;
            winW = 565;
        }
        else if ($.browser.safari == true) {
            winH = 370;
            winW = 554;
        }

        OpenRadWindow(url, winH, winW, false, false, false, true);
    }
    else if (mode == 'PlayerLoyaltyInfo') {

        var URL = '/desktopmodules/reload.aspx';
        mywin = openPopupWindow(URL, mode, 750, 500);
        GetReloadJSON('LaunchLoyaltyInfo');
        setTimeout("SubmitForm('" + mode + "', '" + roomid + "');", 5000);
    }
}

function GetReloadJSON(mode) {

    var data, formdata, RetPage;
    var PageCulture = $('#PageCulture').val();
    var CurrentUser = $('#CurrentUser').val();

    var AfterSave = function (responseText, loadIn, postLoad, extendedData) {
        var result = responseText;
        //alert(result);
        if (result != '') {
            PageJSON = parseJSON(result);
        }
    }
    data = 'PageCulture=' + PageCulture + '&action=' + mode + '&UserName=' + CurrentUser;
    //alert(data);   
    ajaxRequest('/desktopmodules/bluestar.OneClick.Registration/registrationprocess.aspx', data, null, null, AfterSave, 'msgLoading', false);
}

function SubmitForm(mode, submode) {

    var JSONRet = PageJSON;

    if (mode == 'PlayerHistory') {
        parent.AppLaunchWindow.document.getElementById('serverid').value = JSONRet.serverid;
        parent.AppLaunchWindow.document.getElementById('username').value = JSONRet.username;
        parent.AppLaunchWindow.document.getElementById('loginname').value = JSONRet.username;
        parent.AppLaunchWindow.document.getElementById('password').value = JSONRet.password;
        parent.AppLaunchWindow.document.getElementById('clienttype').value = JSONRet.clienttype;
        parent.AppLaunchWindow.document.getElementById('ul').value = JSONRet.ul;
        parent.AppLaunchWindow.document.getElementById('cookie').value = JSONRet.cookie;
        parent.AppLaunchWindow.document.getElementById('applicationid').value = JSONRet.applicationid;
        parent.AppLaunchWindow.document.getElementById('frmReload').action = JSONRet.reloadlink;
        parent.AppLaunchWindow.document.getElementById('frmReload').submit();
    }
    else if (mode == 'PlayerGameHistory') {
        parent.AppLaunchWindow.document.getElementById('serverid').value = JSONRet.serverid;
        parent.AppLaunchWindow.document.getElementById('username').value = JSONRet.username;
        parent.AppLaunchWindow.document.getElementById('loginname').value = JSONRet.username;
        parent.AppLaunchWindow.document.getElementById('password').value = JSONRet.password;
        parent.AppLaunchWindow.document.getElementById('clienttype').value = JSONRet.clienttype;
        parent.AppLaunchWindow.document.getElementById('ul').value = JSONRet.ul;
        parent.AppLaunchWindow.document.getElementById('cookie').value = JSONRet.cookie;
        parent.AppLaunchWindow.document.getElementById('applicationid').value = JSONRet.applicationid;
        parent.AppLaunchWindow.document.getElementById('frmReload').action = JSONRet.reloadlink;
        parent.AppLaunchWindow.document.getElementById('frmReload').submit();
    }
    else if (mode == 'Banking') {
        mywin.document.frmReload.serverid.value = JSONRet.serverid;
        mywin.document.frmReload.username.value = JSONRet.username;
        mywin.document.frmReload.loginname.value = JSONRet.username;
        mywin.document.frmReload.password.value = JSONRet.password;
        mywin.document.frmReload.clienttype.value = JSONRet.clienttype;
        mywin.document.frmReload.ul.value = JSONRet.ul;
        mywin.document.frmReload.ssologintype.value = JSONRet.ssologintype;
        mywin.document.frmReload.lang.value = JSONRet.lang;
        mywin.document.frmReload.cookie.value = JSONRet.cookie;
        mywin.document.frmReload.usertype.value = JSONRet.accounttype;
        mywin.document.frmReload.accounttype.value = JSONRet.lang;
        mywin.document.frmReload.applicationid.value = JSONRet.applicationid;
        mywin.document.frmReload.action = JSONRet.reloadlink;
        mywin.document.frmReload.submit();

        if (submode != null) {
            if (submode != '' && submode != 'undefined' && submode != 'null') {
                window.location = submode;
            }
        }
    }
    else if (mode == 'PlayerLoyaltyInfo') {
        mywin.document.frmLoyaltyInfo.casinoid.value = JSONRet.casinoid;
        mywin.document.frmLoyaltyInfo.id.value = JSONRet.id;
        mywin.document.frmLoyaltyInfo.password.value = JSONRet.password;
        mywin.document.frmLoyaltyInfo.clienttype.value = JSONRet.clienttype;
        mywin.document.frmLoyaltyInfo.ul.value = JSONRet.ul;
        mywin.document.frmLoyaltyInfo.usertype.value = JSONRet.usertype;
        mywin.document.frmLoyaltyInfo.action = JSONRet.reloadlink;
        mywin.document.frmLoyaltyInfo.submit();
        if (submode != null) {
            if (submode != '' && submode != 'undefined' && submode != 'null') {
                window.location = submode;
            }
        }

    }
}

function PreviewBanking(url, data, mode) {
    if (mode == '' || mode == null) {
        mode = 'oneclick';
    }
    var Link = url + '?' + data + '&TB_iframe=true&height=340&width=600';
    //OpenThickBox('Online Casino | Banking', Link, null, null);
    openPopupWindow(Link, mode, 750, 500);
}

var myPopupWindow = '';
var mywin;

function openPopupWindow(url, name, w, h, scroll) {
    // Fudge factors for window decoration space.
    // In my tests these work well on all platforms & browsers.
    w += 32;
    h += 96;
    wleft = (screen.width - w) / 2;
    wtop = 10; //(screen.height - h) / 2;
    // IE5 and other old browsers might allow a window that is
    // partially offscreen or wider than the screen. Fix that.
    // (Newer browsers fix this for us, but let's be thorough.)
    var ScrollBar = 'no';

    if (scroll == true && scroll != null) {
        ScrollBar = 'yes';
    }
    if (wleft < 0) {
        w = screen.width;
        wleft = 0;
    }
    if (wtop < 0) {
        h = screen.height;
        wtop = 0;
    }

    var win = window.open(url,
    name,
    'width=' + w + ', height=' + h + ', ' +
    'left=' + wleft + ', top=' + wtop + ', ' +
    'location=0, menubar=0, ' +
    'status=0, toolbar=0, scrollbars=' + ScrollBar + ', resizable=0');
    // Just in case width and height are ignored
    // win.resizeTo(w, h);
    // Just in case left and top are ignored
    //win.moveTo(wleft, wtop);
    //win.focus();
    return win;
}

function encodeUrl(url) {
    if (url.indexOf("?") > 0) {
        encodedParams = "?";
        parts = url.split("?");
        params = parts[1].split("&");
        for (i = 0; i < params.length; i++) {
            if (i > 0) {
                encodedParams += "&";
            }
            if (params[i].indexOf("=") > 0) //Avoid null values
            {
                p = params[i].split("=");
                encodedParams += (p[0] + "=" + escape(encodeURI(p[1])));
            }
            else {
                encodedParams += params[i];
            }
        }
        url = parts[0] + encodedParams;
    }
    return url;
}

function insComma(data) {

    var count = 0;
    var i = 0;
    var tmpStr = "";
    var comma = ",";

    for (i = data.length - 1; i >= 0; i--) {
        if (count == 3) {
            tmpStr += comma; count = 1;
        }
        else {
            count++;
        }
        tmpStr += data.charAt(i);
    }
    return (tmpStr);
}

function CommaFormatted(amount) {
    var delimiter = ","; // replace comma if desired
    var a = amount.split('.', 2)
    var d = a[1];
    var i = parseInt(a[0]);
    if (isNaN(i)) { return ''; }
    var minus = '';
    if (i < 0) { minus = '-'; }
    i = Math.abs(i);
    var n = new String(i);
    var a = [];
    while (n.length > 3) {
        var nn = n.substr(n.length - 3);
        a.unshift(nn);
        n = n.substr(0, n.length - 3);
    }
    if (n.length > 0) { a.unshift(n); }
    n = a.join(delimiter);
    if (d.length < 1) { amount = n; }
    else { amount = n + '.' + d; }
    amount = minus + amount;
    return amount;
}

function num2currency(field, currencyCharCode, pageculture) {

    if (typeof (currencyCharCode) == 'undefined') {
        currencyCharCode = '0';
    }

    var tmp1 = "";
    var cents = "";
    var dollars = "";
    var dec = -1;
    var num, i, j;
    var currsymbol = '';

    num = "";

    num = "" + (Math.round(field * 100) / 100);
    dec = num.indexOf(".");
    cents = ((dec > 0) ? num.substring(dec, num.length) : ".00");

    if (cents.length == 2) {
        cents += "0";
    }

    dollars = "" + parseInt(num);

    if (dollars < 0) {
        dollars = "0";
        cents = ".00";
    }

    tmp1 = insComma(dollars);

    if (currencyCharCode !== '0') {
        if (currencyCharCode.indexOf("&") > 0) {
            num = "";
            var currencyCodeSplit = currencyCharCode.split('&');
            for (j = 0; j < currencyCodeSplit.length; j++) {
                num = num + String.fromCharCode(parseInt(currencyCodeSplit[j]));
            }
        }
        else {
            if (currencyCharCode.indexOf(",") > 0) {
                num = "";
                var CharCodeArr = currencyCharCode.split(',');
                for (var k = 0; k < CharCodeArr.length; k++) {
                    num = num + String.fromCharCode(parseInt(CharCodeArr[k]));
                }
                num = num + " ";
            }
            else {
                if (pageculture == null) {
                    num = String.fromCharCode(currencyCharCode) + " ";
                }
                 else {
                     if (pageculture == 'sv-SE') {
                         num = "";
                         currsymbol = " " + String.fromCharCode(currencyCharCode);
                         //alert(currsymbol);
                     }
                }
            }
        }
    }
    else {
        num = "";
    }

    //alert(num);
    //alert(tmp1);

    for (i = tmp1.length - 1; i >= 0; i--) {
        num += tmp1.charAt(i);
    }

    num += cents;
    num = num + currsymbol;

    return num;
}

function ShowHideGameImage(ObjImage) {

    var LoginStatus = $('#CurrentUserLoggedIn').val();

    if ($('#' + ObjImage)) {
        if (LoginStatus == 'True') {
            $('#' + ObjImage).attr('src', '/DesktopModules/Bluestar.DottyBingo.Includes/Images/ui/btn_play_slots.png');
        }
        else {
            $('#' + ObjImage).attr('src', '/DesktopModules/Bluestar.DottyBingo.Includes/Images/ui/btn_joinnow_small.png');
        }
    }
}

function ShowHideFaqImageDiv(Objli, ObjDiv) {

    var DivObject = $('#' + ObjDiv);

    if (document.getElementById(Objli)) {
        if (DivObject.is(":visible")) {
            DivObject.hide('slow');
            $('#' + Objli).css('background-position', '1px 5px');
            $('#' + Objli).css("backgroundImage", "url('/DesktopModules/Bluestar.DottyBingo.Includes/Images/ui/bullet_expandable_close.gif')");
        }
        else {
            DivObject.show('slow');
            $('#' + Objli).css('background-position', '1px 8px');
            $('#' + Objli).css("backgroundImage", "url('/DesktopModules/Bluestar.DottyBingo.Includes/Images/ui/bullet_expandable_open.gif')");
        }
    }
}

function ShowHideGameButton(ObjDiv, ButtonType) {
    var Banking = "'Banking'";
    var gameid = null;
    var LoginStatus = $('#CurrentUserLoggedIn').val();
    if ($('#' + ObjDiv)) {
        if (ButtonType == 'large') {
            if (LoginStatus == 'True') {
                if (ObjDiv == 'btnCommunity') {
                    gameid = "'NoWorries'";
                }
                $('#' + ObjDiv).html('<a href="javascript:void(0);" onclick="javascript:OpenLobby(' + gameid + ');"><img alt="Play Game" src="/DesktopModules/Bluestar.DottyBingo.Includes/Images/ui/btn_play.png" /></a>');
            }
            else {
                $('#' + ObjDiv).html('<a href="javascript:void(0);" onclick="javascript:OpenLobby();"><img alt="Play Game" src="/DesktopModules/Bluestar.DottyBingo.Includes/Images/ui/btn_joinnow.png" /></a>');
            }
        }
        else {
            if (LoginStatus == 'True') {
                $('#' + ObjDiv).html('<a href="javascript:void(0);" onclick="javascript:OpenLobby();"><img alt="Play Game" src="/DesktopModules/Bluestar.DottyBingo.Includes/Images/ui/btn_play_slots.png" /></a>');
            }
            else {
                $('#' + ObjDiv).html('<a href="javascript:void(0);" onclick="javascript:OpenLobby();"><img alt="Play Game" src="/DesktopModules/Bluestar.DottyBingo.Includes/Images/ui/btn_joinnow_small.png" /></a>');
            }
        }
    }
}

function ChangeRowColor(ObjTable) {
    var Count = 0;
    $("#" + ObjTable + " tr").each(function () {
        if ((Count % 2) == 0) {
            $(this).find("td").css('background-color', '#FFFFFF');
        } else {
            $(this).find("td").css('background-color', '#EFEFEF');
        }
        Count++;
    });
}

function DownloadFile(mode) {
    var URL = '';
    var WindowName = ''
    if (mode == 'flash') {
        URL = 'http://get.adobe.com/flashplayer/completion/?installer=Flash_Player_10.2_for_Windows_-_Other_Browsers';
        WindowName = 'Window - Flash';
        window.open(URL);
    }
}

function RefreshBingoBanner() {
    if ($('#divbingoadvert').length > 0) {
        $('.bingoadvert').cycle({
            fx: 'fade' // choose your transition type, ex: fade, scrollUp, shuffle, etc...
        });
    }
}

function DisableRightClick(event) {
    //For mouse right click 
    if (event.button == 2) {
        //alert("Right Clicking not allowed!");
        return false;
    }
}

function DisableCtrlKey(e) {
    var code = (document.all) ? event.keyCode : e.which;
    var message = "Ctrl key functionality is disabled!";
    // look for CTRL key press
    if (parseInt(code) == 17) {
        alert(message);
        window.event.returnValue = false;
    }
}

var mins = 0;
var secs = 0;

function TimeCountDown(ObjDiv, TimeVal, CallMethod) {

    var NewVal = Right(TimeVal, 4);
    var MinVal = Left(NewVal, 2);
    var SecVal = Right(NewVal, 3);

    mins = 1 * tmins(MinVal); // change minutes here
    secs = 0 + tsecs(SecVal); // change seconds here (always add an additional second to your total)
    //alert(secs);
    return redo(ObjDiv, CallMethod);
}

function tmins(obj) {
    for (var i = 0; i < obj.length; i++) {
        if (obj.substring(i, i + 1) == ":")
            break;
    }
    return (obj.substring(0, i));
}

function tsecs(obj) {
    for (var i = 0; i < obj.length; i++) {
        if (obj.substring(i, i + 1) == ":")
            break;
    }
    return (obj.substring(i + 1, obj.length));
}

function dis(mins, secs) {
    var disp;
    if (mins <= 9) {
        disp = " 0";
    } else {
        disp = " ";
    }
    disp += mins + ":";
    if (secs <= 9) {
        disp += "0" + secs;
    } else {
        disp += secs;
    }
    disp = "00:" + disp.replace(' ', '');
    return (disp);
}

function redo(ObjDiv, CallMethod) {
    var NewTime = '';
    secs--;
    if (secs == -1) {
        secs = 59;
        mins--;
    }

    NewTime = dis(mins, secs);
    $('#' + ObjDiv).attr('innerHTML', '&nbsp;<span>' + NewTime + '</span>');

    if ((mins == 0) && (secs == 0)) {
        eval(CallMethod);
    } else {
        cd = setTimeout("redo('" + ObjDiv + "', '" + CallMethod + "')", 1000);
    }
}

function CloseAndOpenRadWindow(url, height, width, ismodel, confirmclose, autosize, autocenter) {

    var oWindow = GetRadWindow();

    oWindow.setUrl(url);
    oWindow.setSize(width, height);
    if (ismodel != null) {
        oWindow.set_modal(ismodel);
    }
    if (autocenter != null) {
        if (autocenter == true) {
            oWindow.center();
        }
    }
}

function CloseRadWindowAndRedirectParent(url, WindowName) {
    CloseRadWindow(WindowName);
    parent.window.location = url;
}

function CloseRadWindow(WindowName) {
    
    var RadWindowName = 'AppLaunchWindow';

    if (WindowName != null) { RadWindowName = WindowName; }

    var manager = GetRadWindow().GetWindowManager();
    var oWnd = manager.getWindowByName(RadWindowName);
    OnClientClose(oWnd);
    oWnd.DestroyOnClose = true;
    oWnd.close();
}

function OpenMGSChat(lang) {
    var Width = 600;
    var Height = 400;
    var ChatUrl = 'https://pcmchat3.valueactive.eu/MgsChatWindow.aspx?MGS_PCM_CasinoId=1888&MGS_PCM_SessionLanguage=' + lang + '&MGS_PCM_Resource=RoxyPalaceWebsite';
    OpenRadWindow(ChatUrl, Height, Width, false, false, false, true);
}

function OpenRadWindow(url, height, width, ismodel, confirmclose, autosize, autocenter, IsTitleBar, IsStatusBar, IsbtnClose, WindowName) {
    //alert(url);
    var RadWindowName = 'AppLaunchWindow';

    if (WindowName != null) {RadWindowName = WindowName;}

    var manager = GetRadWindowManager();
    var ObjPopupWindow = manager.getWindowByName(RadWindowName);
    ObjPopupWindow.setUrl(url);
    ObjPopupWindow.DestroyOnClose = true;
    ObjPopupWindow.add_close(OnClientClose);

    if (ismodel != null) {
        ObjPopupWindow.set_modal(ismodel);
    }
    if (confirmclose != null) {
        if (confirmclose == true) {
            ObjPopupWindow.add_beforeClose(onBeforeClose);
        }
    }


    if (autosize != null) {
        if (autosize == true) {
            ObjPopupWindow.SetWidth(document.body.scrollWidth + 4);
            ObjPopupWindow.SetHeight(document.body.scrollHeight + 70);
        }
        else {
            ObjPopupWindow.setSize(width, height);
        }
    }
    else {
        ObjPopupWindow.setSize(width, height);
    }

    if (autocenter != null) {
        if (autocenter == true) {
            ObjPopupWindow.center();
        }
    }

    //ObjPopupWindow.set_animation(Telerik.Web.UI.WindowAnimation.FlyIn);

    if (IsTitleBar != null) {
        ObjPopupWindow.set_visibleTitlebar(false);
    }
    
    if (IsStatusBar != null) {
        ObjPopupWindow.set_visibleStatusbar(false);
    }

    if (IsbtnClose == null) { IsbtnClose = true; }

    if (IsbtnClose == true) {
        ObjPopupWindow.set_behaviors(Telerik.Web.UI.WindowBehaviors.Move + Telerik.Web.UI.WindowBehaviors.Close);
    }
    
    ObjPopupWindow.show();
}

function onBeforeClose(oWnd, args) {
    function callbckFunction(confirmResult) {
        if (confirmResult) {// confirmResult == true
            // Close this RadWindow

            // First remove the handler in order to avoid recursion
            oWnd.remove_beforeClose(onBeforeClose);

            // Close the window
            oWnd.close();

            // Reattach the handles after the window is closed.
            // RECOMMENDATION: If the DestroyOnClose="true" property is set in in the RadWindow's declaration,
            // then remove this line of the code:
            oWnd.add_beforeClose(onBeforeClose);
        }
    }

    // Cancel closing
    args.set_cancel(true);

    // Show a rad confirmation dialog
    radconfirm("Are you sure you want to close this window?", callbckFunction, 360, 130, null, "Dotty Bingo Alert!");
}

function GetRadWindow() {
    var oWindow = null;
    if (window.radWindow) oWindow = window.radWindow;
    else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow;
    return oWindow;
}

function OnClientClose(oWnd) {
    oWnd.setUrl("/reload.aspx"); // Sets url to blank 
    oWnd.remove_close(OnClientClose); //remove the close handler - it will be set again on the next opening 
}

function OnClientPageLoad(sender, args) {
    setTimeout(function () {

        sender.set_status("Welcome to roxypalace.com!!!");
    }, 0);
}

function GetCurrentHostURL(PageCulture) {
   var HostUrl = window.location.protocol.replace(/\:/g, '')  + "://" + window.location.host;
   return HostUrl;
}

function RefreshBalance() {
    var data, formdata, RetPage;
    var PageCulture = $('#PageCulture').val();

    var AfterSave = function (responseText, loadIn, postLoad, extendedData) {
        var result = responseText;
        //alert(result);
        if (result != '') {
            var RetPage = parseJSON(result);
            if (RetPage.status == 'OK') {
                if (RetPage.fstatus == 'True') {
                    $('#dnn_rpPlayerBalance_cmdPlayerBalanceToggle').text('Balance ' + CommaFormatted(RetPage.totalbalance.replace(/\s/g, "")));
                    $('#dnn_rpPlayerBalance_lblCashBalance').html(RetPage.playercurrency + ' ' + CommaFormatted(RetPage.cashbalance.replace(/\s/g, "")));
                    $('#dnn_rpPlayerBalance_lblBonusBalance').html(RetPage.playercurrency + ' ' + CommaFormatted(RetPage.bonusbalance.replace(/\s/g, "")));
                    $('#dnn_rpPlayerBalance_lblTotalBalance').html(RetPage.playercurrency + ' ' + CommaFormatted(RetPage.totalbalance.replace(/\s/g, "")));
                }
            }
        }
    }
    data = 'action=GetPlayerBalance';
    //alert(data);   
    ajaxRequest('/desktopmodules/bluestar.OneClick.Includes/includeprocess.aspx', data, null, null, AfterSave, 'msgLoading', null);

}

var NewGUIID = '';
function GenerateGUID() {
    
    var method = 'POST';
    var data = 'action=GetGUID';
    var page = '/desktopmodules/bluestar.OneClick.Includes/includeprocess.aspx';

    var result = AjaxReturnRequest(page, data, method);
    if (result != '') {
        var RetPage = parseJSON(result);
        if (RetPage.status == 'OK') {
            NewGUIID = RetPage.GUID;
            //alert('chk1: ' + NewGUIID);
        }
    }

    return NewGUIID;
}

var CallAgain = false;
function RefreshCasinoBalance() {
    CallAgain = false;
    var data, formdata, RetPage;
    var PageCulture = $('#PageCulture').val();

    var AfterSave = function (responseText, loadIn, postLoad, extendedData) {
        var result = responseText;
        //alert(result);
        if (result != '') {
            var RetPage = parseJSON(result);
            if (RetPage.status == 'OK') {
                if (RetPage.fstatus == 'True') {
                    var BalanceTitle = $('#dnn_rpPlayerBalance_cmdPlayerBalanceToggle').text();
                    var bArr = BalanceTitle.split(' ');
                    //$('.bsPlayerBalance a').html(bArr[0] + ' ' + RetPage.totalbalance.replace(' ',''));
                    //var BalanceVal = RetPage.totalbalance.toString();
                    //alert(BalanceVal.replace(/\s/g, ""));
                    $('#dnn_rpPlayerBalance_lblPlayerBalanceContent').html(RetPage.playercurrency + ' ' + CommaFormatted(RetPage.totalbalance.replace(/\s/g, "")));
                    $('#dnn_rpPlayerBalance_lblCashBalance').html(RetPage.playercurrency + ' ' + CommaFormatted(RetPage.cashbalance.replace(/\s/g, "")));
                    $('#dnn_rpPlayerBalance_lblBonusBalance').html(RetPage.playercurrency + ' ' + CommaFormatted(RetPage.bonusbalance.replace(/\s/g, "")));
                    $('#dnn_rpPlayerBalance_lblTotalBalance').html(RetPage.playercurrency + ' ' + CommaFormatted(RetPage.totalbalance.replace(/\s/g, "")));
                    CallAgain = true;
                }
                if (CallAgain == true) {
                    setTimeout("RefreshCasinoBalance()", 3000);
                }
            }
        }
    }
    data = 'action=GetPlayerCasinoBalance';
    //alert(data);   
    ajaxRequest('/desktopmodules/bluestar.OneClick.Includes/includeprocess.aspx', data, null, null, AfterSave, null, null);

}

function RefreshPlayerLoyaltyInfo() {
    CallAgain = false;
    var data, formdata, RetPage;
    var PageCulture = $('#PageCulture').val();

    var AfterSave = function (responseText, loadIn, postLoad, extendedData) {
        var result = responseText;
        //alert(result);
        if (result != '') {
            var RetPage = parseJSON(result);
            if (RetPage.status == 'OK') {
                if (RetPage.fstatus == 'True') {
                    $('#dnn_rpPlayerBalance_lblLoyaltyTierBalance').html(RetPage.tiername.replace(/\s/g, ""));
                    $('#dnn_rpPlayerBalance_lblNextTierBalance').html(RetPage.pointstonexttier.replace(/\s/g, ""));
                    $('#dnn_rpPlayerBalance_lblLoyaltyBalanceContent').html(RetPage.loyaltybalance.replace(/\s/g, ""));
                    CallAgain = true;
                }
                if (CallAgain == true) {
                    setTimeout("RefreshPlayerLoyaltyInfo()", 3000);
                }
            }
        }
    }
    data = 'action=GetPlayerLoyaltyBalance';
    //alert(data);   
    ajaxRequest('/desktopmodules/bluestar.OneClick.Includes/includeprocess.aspx', data, null, null, AfterSave, null, null);

}

function formatCurrency(num) {
    num = isNaN(num) || num === '' || num === null ? 0.00 : num;
    return parseFloat(num).toFixed(2);
}

function NavigatePlayNow(url) {
    PreviewPage('Banking', url);
}

function NavigatePlayBanner(NavUrl, isFlash) {
    if (isFlash == true) {
        window.opener.location = NavUrl;
        window.close();
    }
    else {
        window.open(NavUrl, "DownloadCasino", "width=100,height=100, location=0, menubar=0, status=0, toolbar=0, scrollbars=no, resizable=0");
    }
}

function NavigateMyAccount(NavUrl) {
    window.opener.location = NavUrl;
    window.close();
}

function NavigateLogout(NavUrl, mode) {

    var data, RetPage;
    var Url = 'http://' + NavUrl;
    
    CasinoProcess = $('#CasinoMode').val();

    var AfterLogout = function (responseText, loadIn, postLoad, extendedData) {
        var result = responseText;
        //alert(result);
        if (result != '') {
            var RetPage = parseJSON(result);
            if (RetPage.status == 'OK') {
                if (CasinoProcess == 'Normal') {
                    if (mode == 'Normal') {
                        window.location = Url;
                    }
                    else {
                        window.opener.location = Url;
                        window.close();
                    }
                }
                else if (CasinoProcess == 'LC') {
                    window.location = '/live-casino.aspx';
                }
            }
        }
    }

    data = 'action=Logout';
    //alert(data);   
    ajaxRequest('/desktopmodules/bluestar.OneClick.Includes/includeprocess.aspx', data, null, null, AfterLogout, null, null);
}

function NavigateSupport(radwindow) {

    if (radwindow != null && radwindow != 'undefined'){
        if (radwindow == true){
            CloseRadWindow();
        }
    }

    var HostUrl = window.location.host;
    var PageCulture = $('#PageCulture').val();
    var PageUrl = '';
    if (PageCulture == 'en-GB') {
        PageUrl = '/contact-us.aspx';
    }
    else if (PageCulture == 'es-ES') {
        PageUrl = '/Contáctenos.aspx';
    }
    else if (PageCulture == 'sv-SE') {
        PageUrl = '/kontakta-oss.aspx';
    }
    else if (PageCulture == 'de-DE') {
        PageUrl = '/Kontakt.aspx';
    }
    else if (PageCulture == 'nl-NL') {
        PageUrl = '/Contact-Met.aspx';
    }
    else if (PageCulture == 'da-DK') {
        PageUrl = '/Kontakt-os.aspx';
    }
    else {
        PageUrl = '/contact-us.aspx';
    }
    //PageUrl = 'http://' + HostUrl + PageUrl;
    window.location = PageUrl;
}

function TrackJoinNow() {
    var data, RetPage;
    var Url = window.location.href;
    
    var AfterTracking = function (responseText, loadIn, postLoad, extendedData) {
        var result = responseText;
        //alert(result);
        if (result != '') {
            var RetPage = parseJSON(result);
            if (RetPage.status == 'OK') {
                //alert('Join Now Tracked!');
            }
        }
    }
    data = 'action=TrackJoinNow&refurl=' + Url;
    //alert(data);   
    ajaxRequest('/desktopmodules/bluestar.OneClick.Includes/includeprocess.aspx', data, null, null, AfterTracking, null, null);
}

function addCss(cssCode) {
    var styleElement = document.createElement("style");
    styleElement.type = "text/css";
    if (styleElement.styleSheet) {
        styleElement.styleSheet.cssText = cssCode;
    } else {
        styleElement.appendChild(document.createTextNode(cssCode));
    }
    document.getElementsByTagName("head")[0].appendChild(styleElement);
}

function LCTrackJoinNow(IsLoggedIn, NavigateLink, GameID, Engame) {
    var data, RetPage;
    var Url = '';
    var PageCulture = $('#PageCulture').val();
    
    var HostUrl = '';
    HostUrl = GetCurrentHostURL(PageCulture);

    if (PageCulture == 'en-GB') {
        Url = '/player-login.aspx?returnurl=' + NavigateLink + '&gameid=' + GameID + '&engame=' + Engame;
    }
    else {
        Url = '/player-login-' + PageCulture + '.aspx?returnurl=' + NavigateLink + '&gameid=' + GameID + '&engame=' + Engame;
    }

    

//    var AfterTracking = function (responseText, loadIn, postLoad, extendedData) {
//        var result = responseText;
//        //alert(result);
//        if (result != '') {
//            var RetPage = parseJSON(result);
//            if (RetPage.status == 'OK') {
//                //alert('Join Now Tracked!');
//            }
//        }
//    }
//    data = 'action=TrackJoinNow&refurl=' + Url;
//    //alert(data);   
//    ajaxRequest('/desktopmodules/bluestar.OneClick.Includes/includeprocess.aspx', data, null, null, AfterTracking, null, null);
}

function TrackDownloadCasino() {
    var data, RetPage;
    var Url = window.location.href;

    var AfterTracking = function (responseText, loadIn, postLoad, extendedData) {
        var result = responseText;
        //alert(result);
        if (result != '') {
            var RetPage = parseJSON(result);
            if (RetPage.status == 'OK') {
                //alert('Join Now Tracked!');
            }
        }
    }
    data = 'action=TrackDownloadCasino&refurl=' + Url;
    //alert(data);   
    ajaxRequest('/desktopmodules/bluestar.OneClick.Includes/includeprocess.aspx', data, null, null, AfterTracking, null, null);
}


function PCMOutboundChatPost(Pagename, CasinoId, PlayerLoginName) {
    var data, RetPage;
    var Url = window.location.href;

    var AfterTracking = function (responseText, loadIn, postLoad, extendedData) {
        var result = responseText;
        //alert(result);
        if (result != '') {
            var RetPage = parseJSON(result);
            if (RetPage.status == 'OK') {
                //alert('Join Now Tracked!');
            }
        }
    }
    data = 'action=PCMOutboundChat&PageName=' + Pagename + '&CasinoID=' + CasinoId + '&PlayerLoginName=' + PlayerLoginName;
    //alert(data);   
    ajaxRequest('/desktopmodules/bluestar.OneClick.Includes/includeprocess.aspx', data, null, null, AfterTracking, null, null, null, true, null, 8000);

}

function InitializeMGSChatProcess() {

    var UserName = null;
    var sPath = window.location.pathname;
    var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
    var CasinoId = 1888;
    var PlayerLoginName = "";
    var SystemType = 5;
    var TrackingGUIID = $('#TrackingGuid').val();
    var SessionType = null;
    var SessionId = null;
    var AutoLogin = true;
    var TopPosition = null;
    var LeftPosition = null;
    var Resource = "";
    var DisableProxyPopUp = false;
    var PageCulture = Left($('#PageCulture').val(), 2); // document.getElementById('PageCulture').value = 10, ;
    var ProxyPageURL = GetCurrentHostURL(PageCulture) + '/desktopmodules/mgsnotification.aspx';
    var PSLLoginName = null;
         
    if (sPage == null || sPage == '') {
        sPage = 'home.aspx';
    }

    Resource = sPage;

    if ($('#dnn_rpCasinoPlayerName_lblPlayerUserName').length > 0) {
        UserName = $('#dnn_rpCasinoPlayerName_lblPlayerUserName').html();
    }

    PlayerLoginName = UserName;

    if (PlayerLoginName == null || PlayerLoginName == '') {
        SystemType = 3;
    }

    try {
        var PCMChatGUIID = '{' + TrackingGUIID + '}';
        MgsLiveChatControl.InitializeMgsLiveChatControl(CasinoId, PageCulture, PageCulture, PCMChatGUIID, PlayerLoginName, SystemType, SessionId, SessionType, AutoLogin, TopPosition, LeftPosition, Resource, DisableProxyPopUp, ProxyPageURL, PSLLoginName);
    }
    catch (Error) {
        alert(Error.message);
    }
}

function TrackClickedItems(TrackItemID) {
    var data, RetPage;

    var AfterTracking = function (responseText, loadIn, postLoad, extendedData) {
        var result = responseText;
        //alert(result);
        if (result != '') {
            var RetPage = parseJSON(result);
            if (RetPage.status == 'OK') {
                //alert('Join Now Tracked!');
            }
        }
    }
    data = 'action=TrackClickedItems&TrackItemID=' + TrackItemID
    //alert(data);   
    ajaxRequest('/desktopmodules/bluestar.OneClick.Includes/includeprocess.aspx', data, null, null, AfterTracking, null, null, null, true, null, 8000);

}

function NavigateMainSiteNav(CasinoMode) {

    var CasinoUrl = '';

    switch (CasinoMode) {
        case 'Normal':
            CasinoUrl = '/';
            break;
        case 'LiveCasino':
            CasinoUrl = '/live-casino.aspx';
            break;
    }
    //alert(CasinoUrl);
    window.parent.location.replace(CasinoUrl);
}
