var BASEURL='https://C.environment.playbridgedoctor.com/';//////////////////////////////////////////////////////////////////////////////// // Globals //////////////////////////////////////////////////////////////////////////////// var ZERO = 0; var ONE = 1; var NOVALUE = -1; // Variables for managing live game users display var showLivePlayerAlerts = window.localStorage.getItem('showLivePlayerAlerts') === '1'; var lobbyUserList = [], waitingUserList = [], playingUserList = []; var prevTotalLobby = [], prevTotalWaiting = []; //////////////////////////////////////////////// //// multi-play vars //////////////////////////////////////////////// var bHasMenu = true; var iUserID = NOVALUE; var userid; //this is used in the game, need to move it var cookies = { EmailAddress: "", Pass: "", Token: "", Existing: "" }; var myclient = NOVALUE; var sPlayerName = ""; var sRole = ""; var role = 'royal'; //needed for game var sBidSys = null; var existing = !!PagesGetCookie('Existing') || null; var sSlectedPage = "Main"; // var sSelectedPage = "Main"; var mydomain = getUrlVars()["site"]; if (mydomain == undefined) { mydomain = 'bridgedoctor'; } if (typeof domain !== "undefined") { if (domain == '_60secondbridge') { mydomain = '_60secondbridge'; } } var sixtysecUser; var sixtysecBidSys; if (mydomain == '_60secondbridge') { sixtysecUser = username; sixtysecBidSys = getUrlVars()["bidsys"]; sixtysecGame = getUrlVars()["game"]; sixtysecVal = getUrlVars()["val"]; sixtysecType = getUrlVars()["type"]; } // Load the firebase scripts and configure // Using this custom method rather than $.getScript because it caches the file, making subsequent requests a lot faster jQuery.cachedScript = function( url, options) { // Allow user to set any option except for dataType, cache, and url options = $.extend( options || {}, { dataType: "script", cache: true, url: url }); // Use $.ajax() since it is more flexible than $.getScript // Return the jqXHR object so we can chain callbacks return jQuery.ajax( options ); }; loadFirebase(); loadSweetAlert(); loadToastr(); // get variables from the url function getUrlVars() { var vars = {}; var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, key, value) { vars[key] = value; }); return vars; } //////////////////////////////////////////////////////////////////////////////// // onload //////////////////////////////////////////////////////////////////////////////// jQuery(document).ready(function() { function CheckBrowser() { var ua = navigator.userAgent, tem, M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || []; if (/trident/i.test(M[1])) { tem = /\brv[ :]+(\d+)/g.exec(ua) || []; return { name: 'IE', version: (tem[1] || '') }; } if (M[1] === 'Chrome') { tem = ua.match(/\bOPR\/(\d+)/) if (tem != null) { return { name: 'Opera', version: tem[1] }; } } M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?']; if ((tem = ua.match(/version\/(\d+)/i)) != null) { M.splice(1, 1, tem[1]); } return { name: M[0], version: M[1] }; } var b = CheckBrowser(); if (mydomain == '_60secondbridge') { sPlayerName = sixtysecUser; iUserID = 1; sBidSys = sixtysecBidSys; sRole = 'ok'; userid = iUserID; //bad, but need this for now in the game if (sRole == 'ok') { role = 'royal'; } else { role = sRole; } var sPage = "
Please wait a moment...
...
.
"; if (sixtysecGame == 'hands') { $('#stage').html(sPage); goToGame({ "myclient": 0, "uname": sPlayerName, "BidSys": sBidSys, "Game": "hands", "Val": 0 }); } else if (sixtysecGame == 'set') { GoMainMenu(); } else { var game, val, hand, type; game = sixtysecGame; val = sixtysecVal; hand = '1'; type = 'any'; if (sixtysecType != undefined) { type = sixtysecType; } if (game == 'learn') { game = 'coffee'; } $('#stage').html(sPage); goToGame({ "myclient": 0, "uname": sPlayerName, "BidSys": sBidSys, "Game": game, "Val": val, "Bn": hand, "Type": type }); } } else { if (b.name == 'MSIE' && b.version < 10) { var sPage = '
\

Oh, no!

\

It looks like you are using an old version of Internet Explorer. Because of vulnerabilities in the browser, certain older versions of IE are no longer supported by our website. To read why, click here

\

We recommend that you use a more robust and secure web browser like the Google Chrome web browser.

\ \

To get Google Chrome free click here

\
\
\ Contact Us\
'; $('#stage').html(sPage); } else { // Attempt login with values from the cookie CheckLogin('user', PagesGetCookie('EmailAddress'), PagesGetCookie('Pass'), 'Login', PagesGetCookie('Token'), function () { // Regardless of the outcome, go to the main menu GoMainMenu(); }); } } }); //////////////////////////////////////////////////////////////////////////////// // clicks //////////////////////////////////////////////////////////////////////////////// // leave site $(document).on("click", "#LogOut", function() { cleanCookie(); sPlayerName = ""; sSelectedPage = "Main"; SignInPage("Main"); }); // click to go sign up page $(document).on("click", "#SignUp", function() { SignUpPage(); }); // click to go forgot page $(document).on("click", "#ForgotPass", function() { ForgotPasswordPage(); }); // hit sign in page sign in btn $(document).on("submit", "#loginForm", function(e) { e.preventDefault(); if ($('#LoginEmail').val() == "") { $('#LoginError').html('Please enter a username'); } else if ($('#LoginPass').val() == "") { $('#LoginError').html('Please enter a password'); } else { var ele = $(this); var sBtn = ele.data('filtro'); CheckLogin('user', $('#LoginEmail').val(), $('#LoginPass').val(), 'Login'); } }); // check email information $(document).on("click", "#ForgotPassSubmit", function() { $('#LoginError').html(""); $('#LoginResult').html(""); var bError = false; var sErrorMsg = ""; // check email if ($('#Email').val() == "") { sErrorMsg = "Enter an Email Address"; bError = true; } else { sEmail = $('#Email').val(); } // check error if (bError == false) { CheckLogin('user', sEmail, 'pass', 'Forgot'); } else { $('#LoginError').html(sErrorMsg); } }); // check sign up information $(document).on("click", "#NewUserSubmit", function() { var bError = false; var sErrorMsg = ""; var sUserName; // check password if ($('#PassCheck').val() == "") { sErrorMsg = "Enter a password."; bError = true; } else { if ($('#PassCheck').val() == $('#CreatePass').val()) { sPass = $('#CreatePass').val(); } else { sErrorMsg = "Passwords don't match"; bError = true; } } // check user name if ($('#UserName').val() == "") { sErrorMsg = "Enter User Name"; bError = true; } else { sUserName = $('#UserName').val(); } // check email if ($('#Email').val() == "") { sErrorMsg = "Enter an Email Address"; bError = true; } else { sEmail = $('#Email').val(); } // check error if (bError == false) { $('#LoginError').html(""); CheckLogin(sUserName, sEmail, sPass, 'Register'); } else { $('#LoginError').html(sErrorMsg); } }); // hit first button to get into something $(document).on("click", "#FrontPage", function() { var ele = $(this); console.log("filtro " + ele.data('filtro')); sSelectedPage = ele.data('filtro'); //not quite right because if change user it doesn't update if (sPlayerName != "" && mydomain == '_60secondbridge') { gotoPage(); } else if (sPlayerName != "" && PagesGetCookie('Pass') != "") { gotoPage(); } else if (PagesGetCookie('EmailAddress') != "") { CheckLogin('user', PagesGetCookie('EmailAddress'), PagesGetCookie('Pass'), 'Login', PagesGetCookie('Token')); } else { SignInPage('sBtn'); } }); $(document).on("click", ".playbutton", function() { var linkid = $(this).attr('id'); var game, val, hand, type; var linkArr = linkid.split('/'); game = linkArr[0]; val = linkArr[1]; hand = linkArr[2]; type = linkArr[3]; if (game == 'learn') { game = 'coffee'; } var sPage = "
Please wait a moment...
...
.
"; $('#stage').html(sPage); goToGame({ "myclient": 0, "uname": sPlayerName, "BidSys": sBidSys, "Game": game, "Val": val, "Bn": hand, "Type": type }); }); // Find user for imitate $(document).on('click', '#findUser', function () { findUser(); }); // Search for specific email address $(document).on('click', '#findFromEmail', function () { var url = BASEURL + 'php/findUser.php'; var sData='Email=' + $('#email').val() + '&Token=' + PagesGetCookie('Token'); jQuery.ajax({ type: "POST", url: url, data: sData, success: function (data) { data = JSON.parse(data); if (data.error) { alert('Server encountered a problem'); return; } var $result = $('#result'); if (data.length === 0) { $result.text('No results found'); return; } var results = ''; data.forEach(function (row) { results += ''; }); results += '
IdEmail
' + row.id + '' + row.email + '' + '
'; $result.html(results); } }) }); $(document).on('click', '.imitate-user', function () { var userId = $(this).data('user-id'); var email = $(this).data('user-email'); var url = BASEURL + 'php/imitateUser.php'; var sData='UserId=' + userId + '&Token=' + PagesGetCookie('Token'); jQuery.ajax({ type: "POST", url: url, data: sData, success: function (data) { data = JSON.parse(data); if (!data.token) { alert('Server encountered a problem'); return; } PagesSetCookie('EmailAddress', email, 100); PagesSetCookie('Token', data.token, 100); PagesSetCookie('Pass', 'fakedata', 100); window.location.reload(); } }) }); //////////////////////////////////////////////////////////////////////////////// // Ajax //////////////////////////////////////////////////////////////////////////////// // check log in info function CheckLogin(sUser, sEmail, sPass, Action, sToken, cb) { var url = BASEURL + "php/Login.php"; var sData = 'Action=' + Action + '&User=' + sUser + '&Email=' + encodeURIComponent(sEmail) + '&Pass=' + sPass + '&mydomain=' + mydomain + '&'; sData += sToken ? 'Token=' + sToken + '&' : ''; jQuery.ajax({ type: "POST", url: url, data: sData, success: function(data) { try { var dataObj = JSON.parse(data); // Only set the cookie once you've successfully logged in if(["MSG", "FAIL"].indexOf(dataObj.CONFIRMATION) > -1 || Action == 'Forgot') { cleanCookie() } else { PagesSetCookie('EmailAddress', sEmail, 100); PagesSetCookie('Pass', sPass, 100); PagesSetCookie('Token', dataObj.Token, 100); // Set the Existing value in the cookies so it can used next time the page loads PagesSetCookie('Existing', dataObj.Existing, 100); // Also set in-memory variables for use by the application sPlayerName = dataObj.PlayerName; iUserID = dataObj.UserID; sBidSys = dataObj.BidSys; existing = dataObj.Existing; sRole = dataObj.Role; userid = iUserID; //bad, but need this for now in the game email = dataObj.Email; if (sRole == 'ok') { role = 'royal'; } else { role = sRole; } logEvents.login(sPlayerName || PagesGetCookie('EmailAddress'), sRole) } } catch (e) { // continue } if (cb) cb(data) else PhpReply(data); }, error: function(errorThrown) { PagesUnsetCookie('EmailAddress'); PagesUnsetCookie('Pass'); PagesUnsetCookie('Token'); //jQuery('#currently').html("Error connecting to server, sorry. Please try again later: " + errorThrown); }, cache: false }); } // get print from php page function PhpReply(jd) { var Obj = jQuery.parseJSON(jd); if (Obj.CONFIRMATION == 'OK') { gotoPage(); } else if (Obj.CONFIRMATION == 'RESULT') { //SignInPage('sBtn') only for forgot $('#LoginResult').html(Obj.MSG); } else if (Obj.CONFIRMATION == 'MSG') { if (Obj.ACTION == 'Register') { SignUpPage(); } else { SignInPage('sBtn') } $('#LoginError').html(Obj.MSG); } else if (Obj.CONFIRMATION == 'FAIL') { //SignInPage('sBtn') if (Obj.ACTION == 'Register') { SignUpPage(); } else { SignInPage('sBtn') } $('#LoginError').html(Obj.MSG); } else { SignInPage('sBtn') $('#LoginError').html('Connection error'); } } var mode; function gotoPage() { mode = null; logEvents.visitPage(sPlayerName || PagesGetCookie('EmailAddress'), sSelectedPage,sRole); switch (sSelectedPage) { case "Practice": mode = 'practice'; if (sRole !== 'ok') { var handcounts = JSON.parse(window.localStorage.getItem('handcounts')); if (!handcounts) { handcounts = [new Date()] } else { handcounts = filterHandcountsAndAddDeal(handcounts); } if (handcounts.length > 1) { displayDailyLimitReached(); return; } window.localStorage.setItem('handcounts', JSON.stringify(handcounts)); } var sPage = "
Please wait a moment...
...
.
"; sPage += generateLiveGameUsersHtml(); $('#stage').html(sPage); goToGame({ "myclient": 0, "uname": sPlayerName, "BidSys": sBidSys, "Game": "hands", "Val": 0 }); break; case "Compete": var sPage = "
Please wait a moment...
...
.
"; sPage += generateLiveGameUsersHtml(); $('#stage').html(sPage); mode = 'compete' goToGame({ "myclient": 0, "uname": sPlayerName, "BidSys": sBidSys, "Game": "set", "Val": 1 }); break; case "Learn": //Forum({type:'post',linkid:1}); Forum({ type: 'postlist', linkid: 'questions' }); break; case "Ask": Forum({ type: 'post', linkid: 37 }); break; case "Videos": Forum({ type: 'post', linkid: 1226 }); break; case "Results": Results(); break; case "Live": Forum({ type: 'post', linkid: 1 }); break; case "Profile": ProfilePage(sRole); break; case "Main": GoMainMenu(); break; default: GoMainMenu(); break; } } //////////////////////////////////////////////////////////////////////////////// // Pages //////////////////////////////////////////////////////////////////////////////// function GoMainMenu() { // Only log if the user has aleady logged in and is therefore returning to the page // if (sPlayerName) { // logEvents.visitPage(sPlayerName, 'MainGrid',sRole); // } var sPage; var logintext; // just for display // if (sPlayerName != '') { //already logged in otherwise no sPlayerName logintext = 'Welcome back, ' + sPlayerName + ' (Log out)'; } else if (PagesGetCookie('EmailAddress') != "" && PagesGetCookie('Pass') != '') { //not logged in yet but has cookie logintext = 'Welcome back, ' + PagesGetCookie('EmailAddress') + ' (Log out)'; } else { //not logged in, no cookie logintext = 'Login  /  Register'; } // If this user is an admin, then add a Imitate User link if (PagesGetCookie('EmailAddress') === 'admin') { logintext += 'Imitate' } ////////////////////// if (mydomain == 'bridgedoctor') { sPage = '
\
\ ' + logintext + '\
\
\ \
\
\ Contact Us FAQs\
\
'; } else if (mydomain == '_60secondbridge') { sPage = '
\
\ Welcome back, ' + sixtysecUser + '\
\
\ \
\
\
'; } $('#stage').html(sPage); } // sign into account page function SignInPage(sBtn) { if (PagesGetCookie('EmailAddress') != "") { var sTempEmail = PagesGetCookie('EmailAddress'); var sTempPass = PagesGetCookie('Pass'); } else { var sTempEmail = ""; var sTempPass = ""; } var sPage = '
\
\ \ \
\
Close
\
'; $('#stage').html(sPage); } // first page for non-users function SignUpPage() { var sPage = '
\
\ \ \
\
Close
\
'; $('#stage').html(sPage); } // Forgot Password function ForgotPasswordPage() { var sPage = '
\
\ \ \
\
Close
\
'; $('#stage').html(sPage); } // Find user function findUser () { var sPage = '
\ \ \
' $('#stage').html(sPage); } //////////////////////////////////////////////////////////////////////////////// // Cookies //////////////////////////////////////////////////////////////////////////////// function PagesSetCookie(c_name, value, exdays) { cookies[c_name] = value; var exdate = new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString()); document.cookie = c_name + "=" + c_value; } function PagesUnsetCookie(c_name) { cookies[c_name] = ""; setCookie(c_name, "", -1); } function PagesGetCookie(c_name) { if (cookies[c_name] != "") { return cookies[c_name]; } var i, x, y, ARRcookies = document.cookie.split(";"); for (i = 0; i < ARRcookies.length; i++) { x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("=")); y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1); x = x.replace(/^\s+|\s+$/g, ""); if (x == c_name) { return unescape(y); } } return ""; } function setCookie(name, value, daysUntilExpiry) { var expiryDate = new Date(); var expiryInMilliseconds = daysUntilExpiry * 24 * 60 * 60 * 1000; expiryDate.setTime(expiryDate.getTime() + expiryInMilliseconds); var expires = "expires=" + expiryDate.toUTCString(); document.cookie = name + "=" + value + ";" + expires + ";path=/"; } function loadFirebase() { $.cachedScript('https://www.gstatic.com/firebasejs/4.2.0/firebase.js') .then(function() { // Initialize Firebase var config={ apiKey: "AIzaSyDVsoM7sJyNMkk64E6lnnZy9FKlpbU-dxc", authDomain: "live-bridge1.firebaseapp.com", databaseURL: "https://live-bridge1.firebaseio.com", storageBucket: "live-bridge1.appspot.com", messagingSenderId: "386488900970" };; firebase.initializeApp(config); }) } function loadAsyncStyleSheets(url) { var head = document.getElementsByTagName('head')[0]; var link = document.createElement('link'); var rel = document.createAttribute('rel'); var href = document.createAttribute('href'); rel.value = 'stylesheet'; href.value = url; link.setAttributeNode(rel); link.setAttributeNode(href); head.appendChild(link); } function loadSweetAlert() { $.cachedScript('https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js'); loadAsyncStyleSheets('https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css'); } function loadToastr() { $.cachedScript('//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js'); loadAsyncStyleSheets('//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css'); } function generateLiveGameUsersHtml() { var html = '
' + '
Do you want to be alerted every time a user joins the live game?
' + '' + '' + '' + '' + '
' + '
' + '' + '' + '' + '
 
' + '
'; // Initial attempt to see if Firebase is instantiated listenToFirebase(); initialiseToastr(); $(document).on('click', 'input[name=alertLiveGameUsers]:radio', function() { if ($('#radio_yes:checked').length) { window.localStorage.setItem('showLivePlayerAlerts', '1') } else { window.localStorage.setItem('showLivePlayerAlerts', '0') } showLivePlayerAlerts = window.localStorage.getItem('showLivePlayerAlerts') === '1'; }); return html } function listenToFirebase() { window.setTimeout(function () { if (firebase) { firebase.database().ref('chat/lobby-users').on('value', managerUsers.bind(this, lobbyUserList, '#lobby_users')); firebase.database().ref('chat/waiting-users').on('value', managerUsers.bind(this, waitingUserList, '#waiting_users')); firebase.database().ref('chat/playing-users').on('value', managerUsers.bind(this, playingUserList, '#playing_users')); } else { listenToFirebase(); } }, 1000); } function initialiseToastr() { window.setTimeout(function () { if (toastr) { toastr.options = { "closeButton": false, "debug": false, "newestOnTop": false, "progressBar": false, "positionClass": "toast-bottom-full-width", "preventDuplicates": false, "onclick": null, "showDuration": "300", "hideDuration": "1000", "timeOut": "3000", "extendedTimeOut": "1000", "showEasing": "swing", "hideEasing": "linear", "showMethod": "fadeIn", "hideMethod": "fadeOut" } } else { initialiseToastr() } }, 1000); } function filterHandcountsAndAddDeal(handcounts) { var ONE_HOUR = 60 * 60 * 1000; var yesterday = new Date((new Date()) - (ONE_HOUR * 24)); yesterday.setHours(23, 59, 59, 999); handcounts = handcounts.filter(function(handdate) { return (yesterday - new Date(handdate)) < 0}); handcounts.push(new Date()); return handcounts; } function displayDailyLimitReached() { var message = 'Replay this hand from different seats or upgrade to a premium membership to enjoy unlimited practice hands, unlimited competion hands, participate in forums and play live bridge online'; if (swal) { swal({ title: "Today's Hand Limit Reached", text: message, type: "warning", html: true, confirmButtonColor: "green", confirmButtonText: "Upgrade Me", showCancelButton: true, cancelButtonText: 'Maybe Later', closeOnConfirm: true }, function (confirm) { if (confirm) { window.location.href = "https://C.environment.playbridgedoctor.com/php/fastspring-billing-bol.php?customer_ref=" + sPlayerName } } ); } else { alert(message); } } function managerUsers(listVar, selector, snapshot) { var difference; selector = selector || '#waiting_users'; listVar.length = 0; const usersObj = snapshot.val(); for (var user in usersObj) { listVar.push(usersObj[user].name) } if (listVar == lobbyUserList) { // Check which user list we've been passed, and concat it with the other // Determine if to show a toastr alert difference = listVar.filter(function(x) { return prevTotalLobby.indexOf(x) == -1 }); if (difference.length && showLivePlayerAlerts) { toastr['info']('User' + (difference.length > 1 ? 's ' : ' ') + difference.join(', ') + (difference.length > 1 ? ' are' : ' is') + ' waiting in the Lobby') } // Clone the array prevTotalLobby = listVar.slice(0); } else if (listVar === waitingUserList) { difference = listVar.filter(function(x) { return prevTotalWaiting.indexOf(x) == -1 }); if (difference.length && showLivePlayerAlerts) { toastr['info']('User' + (difference.length > 1 ? 's ' : ' ') + difference.join(', ') + (difference.length > 1 ? ' are' : ' is') + ' waiting in a room') } // Clone the array prevTotalWaiting = listVar.slice(0); } var html = ''; $(selector).html(html); } var logEvents = { login: function(username, subscriberStatus) { ga('send', { hitType: 'event', eventCategory: 'login', eventAction: username, eventLabel: subscriberStatus }); }, visitPage: function(username, sectionName, subscriberStatus) { ga('send', { hitType: 'event', eventCategory: sectionName, eventAction: username, eventLabel: subscriberStatus }); } } function cleanCookie() { PagesUnsetCookie('Pass'); PagesUnsetCookie('Token'); PagesUnsetCookie('EmailAddress'); } // hijack events function getHandCounts() { var handcounts = JSON.parse(window.localStorage.getItem('handcounts')); if (!handcounts) { handcounts = [new Date()] } else { handcounts = filterHandcountsAndAddDeal(handcounts); } window.localStorage.setItem('handcounts', JSON.stringify(handcounts)); return handcounts } $(document).off('click', '.gamelink'); $(document).on('click', '.gamelink', function(e) { var linkid; linkid = $(this).attr('id'); if (sRole !== 'ok' && linkid === 'confirm_deal') { e.stopImmediatePropagation() if (mode === 'practice') { var handcounts = getHandCounts(); if (handcounts.length <= 1) { myGame.onBtnClicked(linkid); return; } } displayDailyLimitReached(); } }); $(document).on('click', '.bidbtn', function (e) { var linkid; linkid = $(this).attr('id'); if (sRole !== 'ok' && linkid === 'ContactText') { e.stopImmediatePropagation() if (mode === 'practice') { var handcounts = getHandCounts(); if (handcounts.length <= 1) { myGame.WheelBidClicked(); } else { displayDailyLimitReached(); } } else { displayDailyLimitReached(); } } })