/* almond 0.2.9 Copyright (c) 2011-2014, The Dojo Foundation All Rights Reserved. Available via the MIT or new BSD license. see: http://github.com/jrburke/almond for details */ var requirejs,require,define; (function(k){function t(a,b){var c,q,f,h,d,e,m,n,k,r=b&&b.split("/"),g=l.map,p=g&&g["*"]||{};if(a&&"."===a.charAt(0))if(b){r=r.slice(0,r.length-1);a=a.split("/");d=a.length-1;l.nodeIdCompat&&y.test(a[d])&&(a[d]=a[d].replace(y,""));a=r.concat(a);for(d=0;d' + '
' + '
' + '
Sayfa yükleniyor...
' + '
' + '
' + '' ) }; Templates.categoryTree = { // top items listTopItem : new Template( '' ), // a sub item listItem : new Template( '' ), bookmarkItem : new Template( '
  • '+ '
    ' + '
     
    ' + '#{label}' + '
  • ' ) }; var Store = Class.create({ initialize : function (options) { this.source = options.source || 'local'; this.name = options.name; this.loaded = false; if (this.source == 'local' && !Store.isAvailable('local')) { throw "no local storage!"; } }, load : function (callback, scope) { if (this.source == 'local') { var store = localStorage.getItem(this.name); this.data = (store && store.evalJSON()) || null; this.loaded = true; callback.bind( scope )(this.data, this); } else { // TODO: implement server side storage } }, save : function () { if (this.source == 'local') { localStorage.setItem(this.name, Object.toJSON(this.data)); } else { // TODO: implement server side storage } }, get : function () { if (!this.loaded) { return null; } return this.data; }, set : function (value) { if (!this.loaded) { return false; } this.data = value; }, reset : function() { this.set(null); this.save(); } }); // static methods Store.isAvailable = function (source) { source || (source = 'local'); if (source == 'local' && !localStorage) { return false; } return true; } // simple tab manager // options { // element : ul element // } TabManager = Class.create({ initialize : function(options) { var self = this; this.rootElement = $(options.element); this.tabs = []; this.rootElement.select('.tab').each( function(tab){ self.tabs[self.tabs.length] = $( self.getTargetFromLi(tab) ); tab.observe('click', self.onTabClick.bindAsEventListener(self, tab)); }); if (options.selected) { this.selectById(options.selected); } else { this.select( this.rootElement.select('.tab').first() ); } }, // select a tab by the content element id selectById : function (target) { this.select( this.rootElement.select('[href$=#' + target + ']').first().up('li') ); }, // select a tab by the tab selector element select : function ( tab ) { // hide all tabs except the selected one var target = this.getTargetFromLi(tab); for (var i = 0; i< this.tabs.length; i++) { if (this.tabs[i].id == target) { this.tabs[i].show(); } else { this.tabs[i].hide(); } } // mark selected var selectedTab = this.rootElement.select('.tab.selected').first(); if ( selectedTab ) { selectedTab.removeClassName('selected'); } tab.addClassName('selected'); }, onTabClick : function(ev, tab) { ev.stop(); this.select( tab ); }, getTargetFromLi: function ( li ) { return li.down('a').href.match(/#(.*)$/)[1]; } }); if (typeof Navigation == 'undefined') var Navigation = {Model : {}}; // VIEW/CONTROLLER: Navigation.LeftNav // Tab manager for bookmarks & category tree // Navigation.Model.LeftNav = Class.create( TabManager, { initialize : function ($super, options) { this.msgBus = $(document); this.enableBookmarks = Store.isAvailable('local'); if (!this.enableBookmarks) { $('bookmark_tab').remove(); $('category_bookmarks').remove(); } $super({ element: 'navigation_left_tabs' }); this.initMessagesListeners(); // gets data object for categories & bookmarks this.categoryData = Model.CategoryTree.getInstance(); // creates category view this.categoryTree = new Navigation.Model.CategoryTree({ categoryData : this.categoryData, initOptions : options, bookmarksEnabled : this.enableBookmarks }); if (this.enableBookmarks) { // create bookmarklist view this.bookmarkList = new Navigation.Model.BookmarkList({ categoryData : this.categoryData }); } }, load : function ( rawCategoryData ) { this.categoryData.load( rawCategoryData ); }, categoriesLoaded : function() { $$('#category_tab .count').first().update(' (' + this.categoryData.countCategories() + ')'); }, initMessagesListeners : function() { this.msgBus.observe('categoryTreeData:categoriesLoaded', this.categoriesLoaded.bindAsEventListener(this) ); this.msgBus.observe('ajaxNavigation:updateNavigation', function(msg) { var options = msg.memo; // loads from history if (options.fromHistory) { if (options.bookmark && this.enableBookmarks) { this.selectById('category_bookmarks'); this.bookmarkList.select( options.CID ); } else { this.selectById('category_tree'); this.categoryTree.selectByState(options); } } else { if (options.reset) this.categoryTree.reset(); } }.bind(this)); } }); // VIEW: CategoryTree // Category tree, expand, collapse & add bookmark // Navigation.Model.CategoryTree = Class.create({ initialize : function(options) { this.rootElement = $('category_tree'); this.msgBus = $(document); Object.extend (this, { bookmarksEnabled : options.bookmarksEnabled || false, data : options.categoryData || null, onLoadState : options.initOptions, dataLoaded : false, // GambitRouterComment // baseUrl : options.baseUrl || 'gambit.html' baseUrl : options.baseUrl || 'eventssportsbook.html' }); this.initMessagesListeners(); }, // fired when categories are loaded categoriesLoaded : function ( ) { this.notRendered = {}; // keeps a list of known categories that hasn't been rendered yet. this.dataLoaded = true; this.lazyRender(); //renders first level if (this.onLoadState) { this.selectByState(this.onLoadState); } }, // fired when bookmarks are loaded bookmarksLoaded : function (json) { }, // render the children of a node lazyRender : function (CID, parentElement) { var template = parentElement?Templates.categoryTree.listItem:Templates.categoryTree.listTopItem, self = this, lis = '', rawData = CID?this.data.getCategory(CID).children:this.data.getCategory(); parentElement = parentElement || this.rootElement; // create html for list items for (var i = 0, len = rawData.length; i < len; i++) { var bookmarkLinkHTML = ''; if (rawData[i].children.length) { this.notRendered[rawData[i].data.id] = true; } else if (this.bookmarksEnabled) { if ( this.data.isBookmarked(rawData[i].data.id) ){ bookmarkLinkHTML = ''; } else { bookmarkLinkHTML = ''; } } lis += template.evaluate({ CID : 'CID' + rawData[i].data.id, // GambitRouterComment // linkUrl : this.baseUrl + '#!events/' + rawData[i].data.id, linkUrl : this.baseUrl + '?category_id=' + rawData[i].data.id, label : rawData[i].data.label, liClass : (rawData[i].children.length?'':'empty'), bookmarkIcon : bookmarkLinkHTML }); } // render to dom only once parentElement.insert({'bottom' : lis }); // add event handlers parentElement.select('a').each(function(el){ el.observe('click', self.onItemClick.bindAsEventListener(self, el)); }); parentElement.select('.control').each(function(el){ el.observe('click', self.onControlClick.bindAsEventListener(self, el)); }); if ( this.bookmarksEnabled ) { parentElement.select('.bookmark').each(function(el){ el.observe('click', self.onBookmarkClick.bindAsEventListener(self, el)); }); } }, // reset: unselect all reset : function () { this.collapse(this.rootElement.select('li.current')); }, // select a node by state selectByState : function(state) { if (state) { if (!this.dataLoaded) { this.onLoadState = state; return; } if (state.CID) { // expands each node in the path to the selected node var path = this.data.getCategoryPath(state.CID); for (var i = path.length-1; i>=0 ; i--){ var target = $('CID' + path[i].data.id); this.expand( target ); } this.expand($('CID' + path[0].data.id)); } else if (state.dynamic) { this.expand($('category_tree_current_bets')); } else { this.reset(); } } else { this.reset(); } }, // expands (root and nodes) expand : function ( li ) { var CID = this.getCIDFromLi( li ), ul = li.down('ul'), self = this; // generate list html if necessary if (CID && this.notRendered[CID]) { this.lazyRender(CID, ul); delete this.notRendered[CID]; } // collapse all the expanded elements in tree (not needed for now) /*this.rootElement.select('li.expanded').each(function(li){ self.collapse(li); }); */ // remove class name 'current' from all nodes this.rootElement.select('li.current').invoke('removeClassName', 'current'); // add class name 'current' to a node until this one is a top node var li1 = li; while (!li1.hasClassName('top')) { li1.addClassName('current'); li1 = li1.up('li'); } // now add it to itself (top node) li1.addClassName('current'); // expand this li and all the parents for (li; li; li = li.up('li.collapsed')) { li.removeClassName('collapsed'); li.addClassName('current'); // to see the open one if ( li.select('li').length ){ li.addClassName('expanded'); } }; }, // collapses (root and nodes) collapse : function ( li ) { //li.removeClassName('expanded').addClassName('collapsed'); this.rootElement.select('li.current').invoke('removeClassName', 'current'); //except the top father if it's not itself if (!li.hasClassName('top')) li.up('li.top').addClassName('current'); // collapse this li and all the parents /*for (li; li; li = li.down('li.expanded')) { li.removeClassName('expanded'); if ( li.select('li').length ){ li.addClassName('collapsed'); } };*/ li.removeClassName('expanded').addClassName('collapsed'); }, //expand / collapses (root and nodes) toggle : function ( li ) { if (li.hasClassName('collapsed')) { this.expand( li ); } else { this.collapse( li ); } }, // event handlers onItemClick : function (ev, element) { var li = element.up('li'); this.expand(li); }, onControlClick : function (ev, element) { ev.stop(); var li = element.up('li'); this.toggle( li ); }, onBookmarkClick : function (ev, element) { var li = element.up('li'); this.data.toggleBookmark( this.getCIDFromLi(li) ); }, bookmarksChanged : function (ev) { var changes = ev.memo; // check if changes affects rendered items if ( changes.removed ) { for (var i = 0; i < changes.removed.length; i++) { var el = this.rootElement.select('#CID' + changes.removed[i] + ' .bookmark').first(); el && el.removeClassName('enabled'); } } if ( changes.added ) { for (var i = 0; i < changes.added.length; i++) { var el = this.rootElement.select('#CID' + changes.added[i] + ' .bookmark').first(); el && el.addClassName('enabled'); } } if ( changes.removedAll ) { this.rootElement.select('.bookmark').each(function(el){ el.removeClassName('enabled'); }); } }, initMessagesListeners : function() { this.msgBus.observe('categoryTreeData:categoriesLoaded', this.categoriesLoaded.bindAsEventListener(this) ); this.msgBus.observe('categoryTreeData:bookmarksLoaded', this.bookmarksLoaded.bindAsEventListener(this)); this.msgBus.observe('categoryTreeData:bookmarksChanged', this.bookmarksChanged.bindAsEventListener(this)); }, // Auxiliary functions getCIDFromLi : function (li) { var m = li.id.match(/^CID(.*)$/); return (m && m.length ? m[1] : null); } }); // VIEW: BookmarkList // BookmarkList view // Navigation.Model.BookmarkList = Class.create({ initialize : function (options) { this.msgBus = $(document); Object.extend(this, { categoryData : options.categoryData, targetElement : $('category_bookmarks_tree') }); this.initMessagesListener(); }, bookmarksLoaded : function () { this.render(); if (this.selectOnLoad){ this.select(this.selectOnLoad) } }, // render : function () { var bookmarks = this.categoryData.getBookmarks(true), output = '', self = this, renderedCount = 0; for ( var i = 0; i< bookmarks.length; i++) { var path = this.categoryData.getCategoryPath(bookmarks[i]); if (bookmarks[i] && path.length) { var category = path[0]; var top = path[path.length-1]; output += Templates.categoryTree.bookmarkItem.evaluate({ label : category.data.label, id : 'BKMCID' + category.data.id, linkUrl : 'eventssportsbook.html?bookmark=true&category_id=' + category.data.id, iconClass : 'CID' + top.data.id + '-icon' }); renderedCount++; } } this.renderedBookmarkCount = renderedCount; this.updateBookmarkTabLabel(); // modify dom only once this.targetElement.update(output); // add event handlers this.targetElement.select('.bookmark_item a').each(function(el){ el.observe('click', self.onItemClick.bindAsEventListener(self, el)); }); this.targetElement.select('.bookmark_item .remove').each(function(el){ el.observe('click', self.onRemoveClick.bindAsEventListener(self, el)); }); this.targetElement.up(0).select('.buttons .button_remove_all').each(function(el){ el.observe('click', self.onRemoveAllClick.bindAsEventListener(self, el)); }); }, select : function (CID) { var previous = this.targetElement.select('.selected').first(); previous && previous.removeClassName('selected'); var current = $('BKMCID' + CID); if (current) { current.addClassName('selected'); } else { this.selectOnLoad = CID } }, // events bookmarksChanged : function (ev) { var changes = ev.memo; if ( changes.removed ) { for (var i = 0; i < changes.removed.length; i++) { $('BKMCID' + changes.removed[i]).remove(); this.renderedBookmarkCount--; this.updateBookmarkTabLabel(); } } if ( changes.added ) { this.render(); } if ( changes.removedAll ) { this.render(); } }, updateBookmarkTabLabel : function () { // returns the actual number of rendered bookmarks // Though stored, some of them may not be rendered if // the category is disabled $$('#bookmark_tab .count').first().update(' (' + this.renderedBookmarkCount + ')'); if(this.renderedBookmarkCount == 0){ $('category_bookmarks').down('.buttons').hide(); $('category_bookmarks').down('.no_bookmarks').show(); } else { $('category_bookmarks').down('.buttons').show(); $('category_bookmarks').down('.no_bookmarks').hide(); } }, onItemClick : function (ev, el) { var li = el.up('li'); this.select(this.getCIDFromLi(li)); }, onRemoveClick : function (ev, el) { var li = el.up('li'); this.categoryData.removeBookmark( this.getCIDFromLi(li) ); }, onRemoveAllClick : function (ev, el) { this.categoryData.removeAllBookmarks(); }, initMessagesListener : function () { this.msgBus.observe('categoryTreeData:bookmarksLoaded', this.bookmarksLoaded.bindAsEventListener(this)); this.msgBus.observe('categoryTreeData:bookmarksChanged', this.bookmarksChanged.bindAsEventListener(this)); }, // auxiliary getCIDFromLi : function (li) { return li.id.match(/^BKMCID(.*)$/)[1]; } }); Navigation.Model.BookmarkStars = Class.create({ initialize : function (CID) { this.msgBus = $(document); this.data = Model.CategoryTree.getInstance(); this.initMessagesListener(); this.observeEvents(); }, observeEvents : function () { $$('.fav_icon').each(function(star) { star.observe('click', this.onStarClick.bindAsEventListener(this, star)); }.bind(this)); }, onStarClick : function (ev, el) { this.data.toggleBookmark( this.getCIDFromElement(el) ); }, initMessagesListener : function () { this.msgBus.observe('categoryTreeData:bookmarksLoaded', this.bookmarksLoaded.bindAsEventListener(this)); this.msgBus.observe('categoryTreeData:bookmarksChanged', this.bookmarksChanged.bindAsEventListener(this)); if (this.data.bookmarksLoaded()) { this.bookmarksLoaded() } }, bookmarksLoaded : function () { var data = this.data; var stars = $$('.fav_icon'); for (var i = 0,l = stars.length; i pathB[0].data.label.replace(/^\s*(.*)\s*$/g,"$1"))?1:-1; } else { return parentA - parentB; } } catch (err) { return 0; } }); } return ret; }, isBookmarked : function (CID) { return this.getBookmarks().indexOf(CID) != -1; }, saveBookmarks : function (data) { this.bookmarkStore.set(data); this.bookmarkStore.save(); }, toggleBookmark : function (CID) { var bookmarks = this.getBookmarks(); if (bookmarks.indexOf(CID) != -1) { this.removeBookmark(CID); } else { this.addBookmark(CID); } }, removeBookmark : function (CID) { var bookmarks = this.getBookmarks(); this.saveBookmarks( bookmarks.without(CID) ); this.fireBookmarksChanged({ removed : [CID] }); }, removeAllBookmarks : function () { var bookmarks = this.getBookmarks(); this.saveBookmarks( bookmarks.clear() ); this.fireBookmarksChanged({ removedAll: [] }); }, addBookmark : function (CID){ var bookmarks = this.getBookmarks(); bookmarks[bookmarks.length] = CID; this.saveBookmarks(bookmarks); this.fireBookmarksChanged({ added : [CID] }); }, fireBookmarksChanged: function(data) { var gambitData = data.removedAll ? [] : data; this.broadcaster.say('bookmarksChanged', data); this.gambitBroadcaster.say('CategoryTree:updateBookmarks', gambitData); }, countBookmarks : function () { return this.getBookmarks().length; } }); if (!window.Model) { Model = {}; } Model.CategoryTree = { getInstance : function () { if (!this.instance) { this.instance = new Navigation.Model.CategoryTree.Data({ bookmarksEnabled : Store.isAvailable('local') }); } return this.instance; } } if (typeof Navigation == 'undefined') var Navigation = {Model : {}}; Navigation.Model.CasinoCategoryTree = Class.create(Navigation.Model.CategoryTree, { categoriesLoaded : function ($super) { $super(); var casinoGames = $('casino_games'); var categories = this.data.getCategory(); for ( var i = 0; i Broadcasting message:', messageID, data); try { this.messageBus.fire(messageID, data); } catch(e) { if(DEBUG) { console.log( this.tag, '> Unable to send [',messageID,'/',data,'] through ', this.msgBus,':',e ); } } }, listen : function(messageTag, handler, scope) { this.handlers[messageTag] = handler.bindAsEventListener(scope); this.messageBus.observe(messageTag, this.handlers[messageTag]); }, destroy : function() { Util.log(this.tag, '> Destroying message handlers...'); for (var messageTag in this.handlers) { this.messageBus.stopObserving(messageTag, this.handlers[messageTag]); } this.handlers = {}; } }); return Broadcaster; }); Broadcaster = require('Broadcaster'); define('getCookieValue', [], function() { //=================================================================================================== //=== getCookieValue ================================================================================ //=================================================================================================== function getCookieValue(offset) { var endstr = document.cookie.indexOf (";", offset); if (endstr == -1) endstr = document.cookie.length; return unescape (document.cookie.substring(offset, endstr)); } return getCookieValue; }); getCookieValue = require('getCookieValue'); define('getCookie', ['getCookieValue'], function(getCookieValue) { //=================================================================================================== //=== getCookie ===================================================================================== //=================================================================================================== function getCookie(name) { var argument = name+"="; var argument_len = argument.length; var cookie_len = document.cookie.length; var i = 0; while (i < cookie_len) { var j = i + argument_len; if (document.cookie.substring(i, j) == argument) return getCookieValue(j); i = document.cookie.indexOf(" ", i) + 1; if (i === 0) break; } return null; } return getCookie; }); getCookie = require('getCookie'); define('setCookie', [], function() { //=================================================================================================== //=== setCookie ===================================================================================== //=================================================================================================== function setCookie (name, value) { var exp = new Date(); exp.setTime(exp.getTime() + (2*365*24*60*60*1000)); // default 2 years var argv = setCookie.arguments; var argc = setCookie.arguments.length; var expires = (argc > 2) ? argv[2] : exp; var path = (argc > 3) ? argv[3] : '/'; var domain = (argc > 4) ? argv[4] : null; var secure = (argc > 5) ? argv[5] : false; document.cookie = name + "=" + escape (value) + (!expires ? "" : ("; expires=" + expires.toGMTString())) + (!path ? "" : ("; path=" + path)) + (!domain ? "" : ("; domain=" + domain)) + (secure ? "; secure" : ""); } return setCookie; }); setCookie = require('setCookie'); define('removeCookie', ['setCookie'], function(setCookie) { //=================================================================================================== //=== removeCookie ===================================================================================== //=================================================================================================== function removeCookie (name) { var exp = new Date(); exp.setTime(Date.parse('January, 1 1970 01:01:01')); setCookie(name, '', exp); } return removeCookie; }); removeCookie = require('removeCookie'); /* Copyright (c) 2007 Brian Dillard and Brad Neuberg: Brian Dillard | Project Lead | bdillard@pathf.com | http://blogs.pathf.com/agileajax/ Brad Neuberg | Original Project Creator | http://codinginparadise.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* dhtmlHistory: An object that provides history, history data, and bookmarking for DHTML and Ajax applications. dependencies: * the historyStorage object included in this file. */ /* Patched by the Bet3000 dev team */ window.dhtmlHistory = { /*Public: User-agent booleans*/ isIE: false, isOpera: false, isSafari: false, isKonquerer: false, isGecko: false, isSupported: false, /*Public: Create the DHTML history infrastructure*/ create: function(options) { /* options - object to store initialization parameters options.debugMode - boolean that causes hidden form fields to be shown for development purposes. options.toJSON - function to override default JSON stringifier options.fromJSON - function to override default JSON parser */ var that = this; /*set user-agent flags*/ var UA = navigator.userAgent.toLowerCase(); var platform = navigator.platform.toLowerCase(); var vendor = navigator.vendor || ""; if (vendor === "KDE") { this.isKonqueror = true; this.isSupported = false; } else if (typeof window.opera !== "undefined") { this.isOpera = true; this.isSupported = true; } else if (typeof document.all !== "undefined") { // PATCH: ie version detection var iev = 0; if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) { iev = new Number(RegExp.$1); } if(iev >= 8 && document.compatMode == 'BackCompat' || iev < 8) { this.isIE = true; this.isSupported = true; } else { this.isGecko = true; this.isSupported = true; } } else if (vendor.indexOf("Apple Computer, Inc.") > -1) { // PATCH: safari version detection TODO: review!!! var version = UA.match(/version\/(\d+)/); if (version[1] && parseInt(version[1]) >= 3) { this.isGecko = true; this.isSupported = true; } else { this.isSafari = true; this.isSupported = (platform.indexOf("mac") > -1); } } else if (UA.indexOf("gecko") != -1) { this.isGecko = true; this.isSupported = true; } /*Set up the historyStorage object; pass in init parameters*/ window.historyStorage.setup(options); /*Execute browser-specific setup methods*/ if (this.isSafari) { this.createSafari(); } else if (this.isOpera) { this.createOpera(); } /*Get our initial location*/ var initialHash = this.getCurrentLocation(); /*Save it as our current location*/ this.currentLocation = initialHash; /*Now that we have a hash, create IE-specific code*/ if (this.isIE) { this.createIE(initialHash); } /*Add an unload listener for the page; this is needed for FF 1.5+ because this browser caches all dynamic updates to the page, which can break some of our logic related to testing whether this is the first instance a page has loaded or whether it is being pulled from the cache*/ var unloadHandler = function() { that.firstLoad = null; }; this.addEventListener(window,'unload',unloadHandler); /*Determine if this is our first page load; for IE, we do this in this.iframeLoaded(), which is fired on pageload. We do it there because we have no historyStorage at this point, which only exists after the page is finished loading in IE*/ if (this.isIE) { /*The iframe will get loaded on page load, and we want to ignore this fact*/ this.ignoreLocationChange = true; } else { if (!historyStorage.hasKey(this.PAGELOADEDSTRING)) { /*This is our first page load, so ignore the location change and add our special history entry*/ this.ignoreLocationChange = true; this.firstLoad = true; historyStorage.put(this.PAGELOADEDSTRING, true); } else { /*This isn't our first page load, so indicate that we want to pay attention to this location change*/ this.ignoreLocationChange = false; /*For browsers other than IE, fire a history change event; on IE, the event will be thrown automatically when its hidden iframe reloads on page load. Unfortunately, we don't have any listeners yet; indicate that we want to fire an event when a listener is added.*/ this.fireOnNewListener = true; } } /*Other browsers can use a location handler that checks at regular intervals as their primary mechanism; we use it for IE as well to handle an important edge case; see checkLocation() for details*/ var locationHandler = function() { that.checkLocation(); }; setInterval(locationHandler, 100); }, /*Public: Initialize our DHTML history. You must call this after the page is finished loading.*/ initialize: function() { /*IE needs to be explicitly initialized. IE doesn't autofill form data until the page is finished loading, so we have to wait*/ if (this.isIE) { /*If this is the first time this page has loaded*/ if (!historyStorage.hasKey(this.PAGELOADEDSTRING)) { /*For IE, we do this in initialize(); for other browsers, we do it in create()*/ this.fireOnNewListener = false; this.firstLoad = true; historyStorage.put(this.PAGELOADEDSTRING, true); } /*Else if this is a fake onload event*/ else { this.fireOnNewListener = true; this.firstLoad = false; } } }, /*Public: Adds a history change listener. Note that only one listener is supported at this time.*/ addListener: function(listener) { this.listener = listener; /*If the page was just loaded and we should not ignore it, fire an event to our new listener now*/ if (this.fireOnNewListener) { this.fireHistoryEvent(this.currentLocation); this.fireOnNewListener = false; } }, /*Public: Generic utility function for attaching events*/ addEventListener: function(o,e,l) { if (o.addEventListener) { o.addEventListener(e,l,false); } else if (o.attachEvent) { o.attachEvent('on'+e,function() { l(window.event); }); } }, /*Public: Add a history point.*/ add: function(newLocation, historyData) { if (this.isSafari) { /*Remove any leading hash symbols on newLocation*/ newLocation = this.removeHash(newLocation); /*Store the history data into history storage*/ historyStorage.put(newLocation, historyData); /*Save this as our current location*/ this.currentLocation = newLocation; /*Change the browser location*/ window.location.hash = newLocation; /*Save this to the Safari form field*/ this.putSafariState(newLocation); } else { /*Most browsers require that we wait a certain amount of time before changing the location, such as 200 MS; rather than forcing external callers to use window.setTimeout to account for this, we internally handle it by putting requests in a queue.*/ var that = this; var addImpl = function() { /*Indicate that the current wait time is now less*/ if (that.currentWaitTime > 0) { that.currentWaitTime = that.currentWaitTime - that.waitTime; } /*Remove any leading hash symbols on newLocation*/ newLocation = that.removeHash(newLocation); /*IE has a strange bug; if the newLocation is the same as _any_ preexisting id in the document, then the history action gets recorded twice; throw a programmer exception if there is an element with this ID*/ if (document.getElementById(newLocation) && that.debugMode) { var e = "Exception: History locations can not have the same value as _any_ IDs that might be in the document," + " due to a bug in IE; please ask the developer to choose a history location that does not match any HTML" + " IDs in this document. The following ID is already taken and cannot be a location: " + newLocation; throw new Error(e); } /*Store the history data into history storage*/ historyStorage.put(newLocation, historyData); /*Indicate to the browser to ignore this upcomming location change since we're making it programmatically*/ that.ignoreLocationChange = true; /*Indicate to IE that this is an atomic location change block*/ that.ieAtomicLocationChange = true; /*Save this as our current location*/ that.currentLocation = newLocation; /*Change the browser location*/ window.location.hash = newLocation; /*Change the hidden iframe's location if on IE*/ if (that.isIE) { that.iframe.src = "/blank.html?" + newLocation; } /*End of atomic location change block for IE*/ that.ieAtomicLocationChange = false; }; /*Now queue up this add request*/ window.setTimeout(addImpl, this.currentWaitTime); /*Indicate that the next request will have to wait for awhile*/ this.currentWaitTime = this.currentWaitTime + this.waitTime; } }, /*Public*/ isFirstLoad: function() { return this.firstLoad; }, /*Public*/ getVersion: function() { return "0.6"; }, /*Get browser's current hash location; for Safari, read value from a hidden form field*/ /*Public*/ getCurrentLocation: function() { var r = (this.isSafari ? this.getSafariState() : this.getCurrentHash() ); return r; }, /*Public: Manually parse the current url for a hash; tip of the hat to YUI*/ getCurrentHash: function() { var r = window.location.href; var i = r.indexOf("#"); return (i >= 0 ? r.substr(i+1) : "" ); }, /*- - - - - - - - - - - -*/ /*Private: Constant for our own internal history event called when the page is loaded*/ PAGELOADEDSTRING: "DhtmlHistory_pageLoaded", /*Private: Our history change listener.*/ listener: null, /*Private: MS to wait between add requests - will be reset for certain browsers*/ waitTime: 200, /*Private: MS before an add request can execute*/ currentWaitTime: 0, /*Private: Our current hash location, without the "#" symbol.*/ currentLocation: null, /*Private: Hidden iframe used to IE to detect history changes*/ iframe: null, /*Private: Flags and DOM references used only by Safari*/ safariHistoryStartPoint: null, safariStack: null, safariLength: null, /*Private: Flag used to keep checkLocation() from doing anything when it discovers location changes we've made ourselves programmatically with the add() method. Basically, add() sets this to true. When checkLocation() discovers it's true, it refrains from firing our listener, then resets the flag to false for next cycle. That way, our listener only gets fired on history change events triggered by the user via back/forward buttons and manual hash changes. This flag also helps us set up IE's special iframe-based method of handling history changes.*/ ignoreLocationChange: null, /*Private: A flag that indicates that we should fire a history change event when we are ready, i.e. after we are initialized and we have a history change listener. This is needed due to an edge case in browsers other than IE; if you leave a page entirely then return, we must fire this as a history change event. Unfortunately, we have lost all references to listeners from earlier, because JavaScript clears out.*/ fireOnNewListener: null, /*Private: A variable that indicates whether this is the first time this page has been loaded. If you go to a web page, leave it for another one, and then return, the page's onload listener fires again. We need a way to differentiate between the first page load and subsequent ones. This variable works hand in hand with the pageLoaded variable we store into historyStorage.*/ firstLoad: null, /*Private: A variable to handle an important edge case in IE. In IE, if a user manually types an address into their browser's location bar, we must intercept this by calling checkLocation() at regular intervals. However, if we are programmatically changing the location bar ourselves using the add() method, we need to ignore these changes in checkLocation(). Unfortunately, these changes take several lines of code to complete, so for the duration of those lines of code, we set this variable to true. That signals to checkLocation() to ignore the change-in-progress. Once we're done with our chunk of location-change code in add(), we set this back to false. We'll do the same thing when capturing user-entered address changes in checkLocation itself.*/ ieAtomicLocationChange: null, /*Private: Create IE-specific DOM nodes and overrides*/ createIE: function(initialHash) { /*write out a hidden iframe for IE and set the amount of time to wait between add() requests*/ this.waitTime = 400;/*IE needs longer between history updates*/ var styles = (historyStorage.debugMode ? 'width: 800px;height:80px;border:1px solid black;' : historyStorage.hideStyles ); var iframeID = "rshHistoryFrame"; var iframeHTML = ''; document.write(iframeHTML); this.iframe = document.getElementById(iframeID); }, /*Private: Create Opera-specific DOM nodes and overrides*/ createOpera: function() { this.waitTime = 400;/*Opera needs longer between history updates*/ var imgHTML = ''; document.write(imgHTML); }, /*Private: Create Safari-specific DOM nodes and overrides*/ createSafari: function() { var formID = "rshSafariForm"; var stackID = "rshSafariStack"; var lengthID = "rshSafariLength"; var formStyles = historyStorage.debugMode ? historyStorage.showStyles : historyStorage.hideStyles; var inputStyles = (historyStorage.debugMode ? 'width:800px;height:20px;border:1px solid black;margin:0;padding:0;' : historyStorage.hideStyles ); var safariHTML = '
    ' + '' + '' + '
    '; document.write(safariHTML); this.safariStack = document.getElementById(stackID); this.safariLength = document.getElementById(lengthID); if (!historyStorage.hasKey(this.PAGELOADEDSTRING)) { this.safariHistoryStartPoint = history.length; this.safariLength.value = this.safariHistoryStartPoint; } else { this.safariHistoryStartPoint = this.safariLength.value; } }, /*Private: Safari method to read the history stack from a hidden form field*/ getSafariStack: function() { var r = this.safariStack.value; return historyStorage.fromJSON(r); }, /*Private: Safari method to read from the history stack*/ getSafariState: function() { var stack = this.getSafariStack(); var state = stack[history.length - this.safariHistoryStartPoint - 1]; return state; }, /*Private: Safari method to write the history stack to a hidden form field*/ putSafariState: function(newLocation) { var stack = this.getSafariStack(); stack[history.length - this.safariHistoryStartPoint] = newLocation; this.safariStack.value = historyStorage.toJSON(stack); }, /*Private: Notify the listener of new history changes.*/ fireHistoryEvent: function(newHash) { /*extract the value from our history storage for this hash*/ var historyData = historyStorage.get(newHash); /*call our listener*/ this.listener.call(null, newHash, historyData); }, /*Private: See if the browser has changed location. This is the primary history mechanism for Firefox. For IE, we use this to handle an important edge case: if a user manually types in a new hash value into their IE location bar and press enter, we want to to intercept this and notify any history listener.*/ checkLocation: function() { /*Ignore any location changes that we made ourselves for browsers other than IE*/ if (!this.isIE && this.ignoreLocationChange) { this.ignoreLocationChange = false; return; } /*If we are dealing with IE and we are in the middle of making a location change from an iframe, ignore it*/ if (!this.isIE && this.ieAtomicLocationChange) { return; } /*Get hash location*/ var hash = this.getCurrentLocation(); /*Do nothing if there's been no change*/ if (hash == this.currentLocation) { return; } /*In IE, users manually entering locations into the browser; we do this by comparing the browser's location against the iframe's location; if they differ, we are dealing with a manual event and need to place it inside our history, otherwise we can return*/ this.ieAtomicLocationChange = true; if (this.isIE && this.getIframeHash() != hash) { this.iframe.src = "/blank.html?" + hash; } else if (this.isIE) { /*the iframe is unchanged*/ return; } /*Save this new location*/ this.currentLocation = hash; this.ieAtomicLocationChange = false; /*Notify listeners of the change*/ this.fireHistoryEvent(hash); }, /*Private: Get the current location of IE's hidden iframe.*/ getIframeHash: function() { var doc = this.iframe.contentWindow.document; var hash = String(doc.location.search); if (hash.length == 1 && hash.charAt(0) == "?") { hash = ""; } else if (hash.length >= 2 && hash.charAt(0) == "?") { hash = hash.substring(1); } return hash; }, /*Private: Remove any leading hash that might be on a location.*/ removeHash: function(hashValue) { var r; if (hashValue === null || hashValue === undefined) { r = null; } else if (hashValue === "") { r = ""; } else if (hashValue.length == 1 && hashValue.charAt(0) == "#") { r = ""; } else if (hashValue.length > 1 && hashValue.charAt(0) == "#") { r = hashValue.substring(1); } else { r = hashValue; } return r; }, /*Private: For IE, tell when the hidden iframe has finished loading.*/ iframeLoaded: function(newLocation) { /*ignore any location changes that we made ourselves*/ if (this.ignoreLocationChange) { this.ignoreLocationChange = false; return; } /*Get the new location*/ var hash = String(newLocation.search); if (hash.length == 1 && hash.charAt(0) == "?") { hash = ""; } else if (hash.length >= 2 && hash.charAt(0) == "?") { hash = hash.substring(1); } /*Keep the browser location bar in sync with the iframe hash*/ window.location.hash = hash; /*Notify listeners of the change*/ this.fireHistoryEvent(hash); } }; /* historyStorage: An object that uses a hidden form to store history state across page loads. The mechanism for doing so relies on the fact that browsers save the text in form data for the life of the browser session, which means the text is still there when the user navigates back to the page. This object can be used independently of the dhtmlHistory object for caching of Ajax session information. dependencies: * json2007.js (included in a separate file) or alternate JSON methods passed in through an options bundle. */ window.historyStorage = { /*Public: Set up our historyStorage object for use by dhtmlHistory or other objects*/ setup: function(options) { /* options - object to store initialization parameters - passed in from dhtmlHistory or directly into historyStorage options.debugMode - boolean that causes hidden form fields to be shown for development purposes. options.toJSON - function to override default JSON stringifier options.fromJSON - function to override default JSON parser */ /*process init parameters*/ if (typeof options !== "undefined") { if (options.debugMode) { this.debugMode = options.debugMode; } if (options.toJSON) { this.toJSON = options.toJSON; } if (options.fromJSON) { this.fromJSON = options.fromJSON; } } /*write a hidden form and textarea into the page; we'll stow our history stack here*/ var formID = "rshStorageForm"; var textareaID = "rshStorageField"; var formStyles = this.debugMode ? historyStorage.showStyles : historyStorage.hideStyles; var textareaStyles = (historyStorage.debugMode ? 'width: 800px;height:80px;border:1px solid black;' : historyStorage.hideStyles ); var textareaHTML = '
    ' + '' + '
    '; document.write(textareaHTML); this.storageField = document.getElementById(textareaID); if (typeof window.opera !== "undefined") { this.storageField.focus();/*Opera needs to focus this element before persisting values in it*/ } }, /*Public*/ put: function(key, value) { this.assertValidKey(key); /*if we already have a value for this, remove the value before adding the new one*/ if (this.hasKey(key)) { this.remove(key); } /*store this new key*/ this.storageHash[key] = value; /*save and serialize the hashtable into the form*/ this.saveHashTable(); }, /*Public*/ get: function(key) { this.assertValidKey(key); /*make sure the hash table has been loaded from the form*/ this.loadHashTable(); var value = this.storageHash[key]; if (value === undefined) { value = null; } return value; }, /*Public*/ remove: function(key) { this.assertValidKey(key); /*make sure the hash table has been loaded from the form*/ this.loadHashTable(); /*delete the value*/ delete this.storageHash[key]; /*serialize and save the hash table into the form*/ this.saveHashTable(); }, /*Public: Clears out all saved data.*/ reset: function() { this.storageField.value = ""; this.storageHash = {}; }, /*Public*/ hasKey: function(key) { this.assertValidKey(key); /*make sure the hash table has been loaded from the form*/ this.loadHashTable(); return (typeof this.storageHash[key] !== "undefined"); }, /*Public*/ isValidKey: function(key) { return (typeof key === "string"); }, /*Public - CSS strings utilized by both objects to hide or show behind-the-scenes DOM elements*/ showStyles: 'border:0;margin:0;padding:0;', hideStyles: 'left:-1000px;top:-1000px;width:1px;height:1px;border:0;position:absolute;', /*Public - debug mode flag*/ debugMode: false, /*- - - - - - - - - - - -*/ /*Private: Our hash of key name/values.*/ storageHash: {}, /*Private: If true, we have loaded our hash table out of the storage form.*/ hashLoaded: false, /*Private: DOM reference to our history field*/ storageField: null, /*Private: Assert that a key is valid; throw an exception if it not.*/ assertValidKey: function(key) { var isValid = this.isValidKey(key); if (!isValid && this.debugMode) { throw new Error("Please provide a valid key for window.historyStorage. Invalid key = " + key + "."); } }, /*Private: Load the hash table up from the form.*/ loadHashTable: function() { if (!this.hashLoaded) { var serializedHashTable = this.storageField.value; if (serializedHashTable !== "" && serializedHashTable !== null) { this.storageHash = this.fromJSON(serializedHashTable); this.hashLoaded = true; } } }, /*Private: Save the hash table into the form.*/ saveHashTable: function() { this.loadHashTable(); var serializedHashTable = this.toJSON(this.storageHash); this.storageField.value = serializedHashTable; }, /*Private: Bridges for our JSON implementations - both rely on 2007 JSON.org library - can be overridden by options bundle*/ toJSON: function(o) { return o.toJSONString(); }, fromJSON: function(s) { return s.parseJSON(); } }; // PATCH: Using prototypejs json methods window.dhtmlHistory.create({ toJSON: function(o) { return Object.toJSON(o); }, fromJSON: function(s) { return s.evalJSON(); } }); if (typeof Navigation == 'undefined') var Navigation = {Model : {}}; Navigation.initAffiliatesCookies = function() { var affiliate = Util.getUrlParam('affiliate_id'); if (affiliate) { setCookie('affiliate_id', affiliate); } var ia_affid = Util.getUrlParam('ia_affid'); if (ia_affid) { var older_ia_affid = getCookie('ia_affid'); if ( older_ia_affid == null ) { var t = new Date(); t.setMonth(t.getMonth() + 1); setCookie('ia_affid', ia_affid, t); } } var btag = Util.getUrlParam('btag'); if (btag) { var olderBtag = getCookie('btag'); if ( olderBtag == null ) { var t = new Date(); t.setMonth(t.getMonth() + 1); setCookie('btag', btag, t); } } }; Navigation.addValueClickRegisterImg = function(userID) { // Income access related stuff if (parseInt(getCookie('ia_affid')) == 226 && userID) { var img = new Image(); img.height = "1"; img.width = "20"; img.src = "https://www.emjcd.com/u?CID=1520502&OID=" + userID + "&TYPE=344277&AMOUNT=0&CURRENCY=EUR&METHOD=IMG"; } }; Navigation.addValueClickTransactionImg = function(partner,userID) { // Check first deposit partner if (partner == 'VALUECLICK' && userID) { var img = new Image(); img.height = "1"; img.width = "20"; img.src = "https://www.emjcd.com/u?CID=1520502&OID=" + userID + "&TYPE=344279&AMOUNT=1.00&CURRENCY=EUR&METHOD=IMG"; } }; Navigation.changeLang = function(lang) { var oldLang = Vars.lang; if (lang && lang != oldLang) { try { //Sportsbook.bettingSlip.saveOnCookies(); Gambit.bettingSlip.persist(); } catch(e) { /* Ignore exception, we are probably somewhere that doesn't * have a sportsbook */ } var url = Util.getHistoryUrl(); setCookie("lang", lang); if (url.indexOf('/cms/') > -1) { // CMS hack. CMS directory structure is so weird to mantain current page. Just go to home. var token = Util.getToken(); token = token ? '/' + token : ''; url = token + '/' + lang + '/html/home.html'; } else { // Stay in current page. if (url.indexOf('/' + oldLang + '/') > -1) { // If lang is present in current url just replace it. url = url.replace('/' + oldLang + '/', '/' + lang + '/'); } else { // Lang not present, add it to url. var idx = Util.getToken(url) ? 4 : 3; urlPieces = url.split('/'); urlPieces.splice(idx, 0, lang); url = urlPieces.join('/'); } } window.location.href = url; } }; if (typeof Navigation == 'undefined') var Navigation = {Model : {}}; Navigation.Model.Ajaxifier = Class.create({ initialize : function(options) { this.tag = 'Ajaxifier'; this.broadcaster = new Broadcaster('ajaxNavigation'); this.config = { /* sample: dynamicPageName : 'eventssportsbook.html', containerID : 'pages_placeholder', onReady : function() { this.broadcaster.listen('eventssportsbook:dataLoaded', function(msg) { if (!msg.memo.reloading) { this.resetScroll(); } this.idle(); }, this); }, onLoad : function() {}, dynamic : false */ }; if (options !== undefined) { Object.extend(this.config, options); } this.broadcaster.listen('ajaxHistory:load', function(msg) { this.loadHistory(msg.memo); }, this); if (this.config.onReady && Object.isFunction(this.config.onReady)) { this.config.onReady.bind(this)(); } this.ajaxifyForms(); this.ajaxifyLinks(); }, /* * Returns true or false depending on whether the browser is currently * displaying a dynamic page. * * Dynamic pages (unlike static pages) are responsible * for handling it's links and content. */ isDynamic : function(url) { if (!this.config.dynamicPageName) return false; var re = new RegExp( '(^' + this.config.dynamicPageName + '|/' + this.config.dynamicPageName + ')(.*)$' ); return (re.exec(url) !== null); }, working : function() { $(document.body).addClassName('working'); setTimeout(this.idle.bind(this), 5000); }, idle : function() { $(document.body).removeClassName('working'); }, /* * Loads an url from history */ loadHistory : function(historyData) { this.load(historyData.url, { fromHistory : true }); }, /* * Load some url to content. */ load : function(url, options) { options = (options || {}); var dynamic = this.isDynamic(url); var previousDynamic = this.config.dynamic; this.config.dynamic = dynamic; this.working(); // Removing since we're using Backbone routers for this // if (!options.fromHistory) { // this.broadcaster.say('saveHistory', { // url : url, // data : options.historyData || null // }); // } // GambitRouterComment if (!options.fromHistory) { this.broadcaster.say('saveHistory', { url : url, data : options.historyData || null }); } if (dynamic && previousDynamic) { this.loadDynamic(url, options); } else { this.loadStatic(url, options); } this.updateNavigation(url, options); }, /* * This method is called from loadStatic method to parse * the passed url. Normally a href attribute. */ parseUrl : function(url, options) { var re = /\/[^/]+$/; var newUrl = url.split('#')[0]; var options = Object.extend({ useXhrUrl : false }, (options || {})); if (options.useXhrUrl === true && re.test(newUrl)) { var match = re.exec(newUrl)[0]; var xhrPath = '/xhr' + match; newUrl = newUrl.substr(0, newUrl.indexOf(match)) + xhrPath; } return newUrl; }, /* * Trigger an updateNavigation event page (dynamic or not) can fix it's * navigation if it has any */ updateNavigation : function(url, options) { var dynamic = this.isDynamic(url); if (dynamic) { options.dynamic = true; Object.extend(options, Util.normalizeParams(Util.parseUrlParams(url))); this.broadcaster.say('updateNavigation', options); } else { this.broadcaster.say('updateNavigation', {reset : true}); } }, /* * Reset page scroll */ resetScroll : function() { window.scrollTo(0, 0); }, /* * Load a static page using xhr */ loadStatic : function(url, options) { var options = Object.extend({ method : 'get', params : {}, useXhrParam : true, useXhrUrl : false }, (options || {})); var method = options.method || 'get'; var params = options.params || {}; url = this.parseUrl(url, { useXhrUrl : options.useXhrUrl }); if (options.useXhrParam === true) { Object.extend(params, {'xhr' : 1}); } Util.log(this.tag, '> Loading static page:', url, options); this.broadcaster.say('loadStatic'); new Ajax.Updater( {success : $(this.config.containerID)}, url, { parameters : params, method : method, evalScripts : true, onComplete : function() { this.resetScroll(); this.ajaxifyForms(); if (options.success && Object.isFunction(options.success)) { options.success(); } this.triggerOnLoad(url, Util.normalizeParams(Util.parseUrlParams(url))); this.idle(); }.bind(this) } ); }, /* * Trigger a loadDynamic event and let the dynamic page handle * the url as it's sees fit. */ loadDynamic : function(url, options) { options || (options = {}); var data = Util.normalizeParams(Util.parseUrlParams(url)); this.broadcaster.say('loadDynamic', data); if (options.success && Object.isFunction(options.success)) { options.success(); } this.triggerOnLoad(url, data); }, /* * Modify event handlers to use our methods to submit forms */ ajaxifyForms : function() { Util.log(this.tag, '> Ajaxifying forms...'); $A($(this.config.containerID).select('form:not(.static)')).each( function(someForm) { Util.log(this.tag, '> Ajaxifying form:', someForm); someForm.submit = function(ev) { var options = { method : someForm.method || 'post', params : someForm.serialize(true) } this.load(someForm.readAttribute('action'), options); if(ev) { ev.stop(); } return false; }.bind(this); $(someForm).observe('submit', someForm.submit); }.bind(this) ); }, /* * Modify links handlers to use our load() method and use xhr or * to let the dynamic page do it's magic. */ ajaxifyLinks : function() { $(window.document).observe('click', function(ev) { if ((ev.isLeftClick() || Prototype.Browser.IE) && !ev.ctrlKey) { // TODO: check isLeftClick in IE var anchor = ev.findElement('a'); if(anchor && !anchor.hasClassName('static')) { var url = anchor.readAttribute('href'); this.load(url); ev.stop(); return false; } } return true; }.bind(this)); }, triggerOnLoad : function(url, data) { if (this.config.onLoad && Object.isFunction(this.config.onLoad)) { this.config.onLoad.bind(this)(url, data); } } }); if (typeof Navigation == 'undefined') var Navigation = {Model : {}}; Navigation.Model.AjaxHistory = Class.create({ initialize : function() { this.tag = 'AjaxHistory'; this.msgBus = $(document); this.initBroadcaster(); dhtmlHistory.initialize(); dhtmlHistory.addListener(this.load.bind(this)); if (dhtmlHistory.isFirstLoad()) { if (Util.urlHasHistory()) { this.load(); } else { this.firstLoad(); } } }, initBroadcaster : function() { this.broadcaster = new Broadcaster('ajaxHistory'); this.broadcaster.listen('ajaxNavigation:saveHistory', function(msg) { this.save(msg.memo); }, this); }, genHistoryKey : function(data) { return '#!' + data.url; }, save : function(data) { Util.log(this.tag, '> Saving history point:', data); dhtmlHistory.add(this.genHistoryKey(data), data); }, load : function(newLocation, historyData) { if (!historyData) { // No data arrived (normally the first page visited or a named anchor). Use current url. var url = Util.getHistoryUrl(); // If the url contains history data use it. Elsewhere normal url is used. if (url.indexOf('#') > -1) return; // Is named anchor! Not history point, don't do nothing. historyData = {url : url}; } Util.log(this.tag, '> Loading history point:', historyData); this.broadcaster.say('load', historyData); }, firstLoad : function() { Util.log(this.tag, '> Loading for the first time.'); this.broadcaster.say('firstLoad'); } }); var Casino = { //Constants GAME_MODE_CLOSED : 0, GAME_MODE_REAL : 1, GAME_MODE_DEMO : 2, MODE_CHECK_INTERVAL : 500, //ms //properties periodicModeCheckRunning : false, previousGameMode : 0, homePage : null, casinoGames : null, currentCategory : '', progressiveSlotsIDs : {}, init : function(options) { this.initBroadcaster(); this.casinoGames = $('casino_games'); this.categoryTree = $('category_tree'); // if (this.casinoGames) { // this.casinoGames.select('ul li.progressive').each(function(gameBlockParent) { // var gameBlock = gameBlockParent.down('div'); // this.progressiveSlotsIDs[gameBlock.id] = gameBlock.id; // }.bind(this)); // } if (options && options.CID) this.showCategory(options.CID); else this.showCategory(); }, initBroadcaster : function() { this.broadcaster = new Broadcaster('Casino'); this.broadcaster.listen('ajaxNavigation:loadDynamic', function(msg) { this.showCategory(msg.memo.CID); }, this); this.broadcaster.listen('ajaxNavigation:loadStatic', function(msg) { this.broadcaster.destroy(); }, this); //this.broadcaster.listen('ajaxHistory:firstLoad', function(msg) { // this.showCategory(); //}, this); }, showCategory : function(categoryID) { try { if (!categoryID) categoryID = 'top_game'; var categoryName = this.categoryMap[categoryID]; this.casinoGames.down('.box_header h2').innerHTML = categoryName; if(categoryID !== '' && categoryID !== 'all') { this.casinoGames.select('ul li').each(function(gameBlock) { if(!gameBlock.hasClassName('none')) { gameBlock.addClassName('none'); } }); this.casinoGames.select('li.'+categoryID).each(function(gameBlock) { gameBlock.removeClassName('none'); }); } else { this.casinoGames.select('ul li').each(function(gameBlock) { gameBlock.removeClassName('none'); }); } } catch(e) {} this.broadcaster.say('dataLoaded'); }, openGame : function(gameID, demo) { demo = demo ? true : false; var token = Util.getToken(); token = token ? token + '/' : ''; var lang = (Vars && Vars.lang) ? Vars.lang + '/' : ''; var siteURL = (Vars && Vars.siteURLInsecure) ? Vars.siteURLInsecure + '/' : ''; var page = (demo === true ) ? 'launch_demo_game.html' : 'launch_game.html'; var progressiveParam = (gameID in this.progressiveSlotsIDs) ? '&progressive=1' : ''; if( !(demo === true && (gameID in this.progressiveSlotsIDs)) ) { var gameWindow = window.open( siteURL + token + lang + 'casino/popup/' + page + '?game_id=' + gameID, 'gameWindow', 'width=1148,'+ 'height=804,'+ 'directories=no,'+ 'toolbar=no,'+ 'resizable=no,'+ 'location=no,'+ 'menubar=no,'+ 'status=no,'+ 'scrollbars=no,'+ 'fullscreen=no'); /* The popup window will store the current mode in a cookie. So i start a periodic check for that cookie to see if the user switched modes while the popup remained open. */ if(!this.periodicModeCheckRunning) { this.periodicModeCheck(); } } }, openLiveGame : function(pageID) { var token = Util.getToken(); token = token ? token + '/': ''; var lang = (Vars && Vars.lang) ? Vars.lang + '/' : ''; var siteURL = (Vars && Vars.siteURLInsecure) ? Vars.siteURLInsecure + '/' : ''; var page = 'launch_game.html'; var gameWindow = window.open( siteURL + token + lang + 'casino_live/popup/' + page + '?page_id=' + pageID, 'gameWindow', 'width=800,'+ 'height=600,'+ 'directories=no,'+ 'toolbar=no,'+ 'resizable=no,'+ 'location=no,'+ 'menubar=no,'+ 'status=no,'+ 'scrollbars=no,'+ 'fullscreen=no'); /* The popup window will store the current mode in a cookie. So i start a periodic check for that cookie to see if the user switched modes while the popup remained open. */ if(!this.periodicModeCheckRunning) { this.periodicModeCheck(); } }, openLiveLobby : function() { var token = Util.getToken(); token = token ? token + '/': ''; var lang = (window.Vars && Vars.lang) ? Vars.lang + '/' : ''; var siteURL = (window.Vars && Vars.siteURLInsecure) ? Vars.siteURLInsecure + '/' : ''; var page = 'launch_game.html'; var gameWindow = window.open( siteURL + token + lang + 'casino_live/popup/' + page, 'gameWindow', 'width=1020,'+ 'height=736,'+ 'directories=no,'+ 'toolbar=no,'+ 'resizable=no,'+ 'location=no,'+ 'menubar=no,'+ 'status=no,'+ 'scrollbars=no,'+ 'fullscreen=no'); /* The popup window will store the current mode in a cookie. So i start a periodic check for that cookie to see if the user switched modes while the popup remained open. */ if(!this.periodicModeCheckRunning) { this.periodicModeCheck(); } }, /* Periodically checks if the game has switched modes. And toggles the visibility of the balance accordingly. */ periodicModeCheck : function() { this.periodicModeCheckRunning = true; var mode = isNaN(parseInt(getCookie('casino_game_mode'),10)) ? this.GAME_MODE_CLOSED:parseInt(getCookie('casino_game_mode'),10); if(mode !== this.previousGameMode) { NavigationTop.toggleBalanceOnFocus(); this.previousGameMode = mode; } setTimeout(this.periodicModeCheck.bind(this), this.MODE_CHECK_INTERVAL); }, gameControls : { switchMode: function() { var url = '' + window.location.href; if(url.indexOf('launch_demo_game.html') >= 0) { window.location.href = url.replace(/(.*)(launch_demo_game.html)(.*)/, "$1launch_game.html$3"); } else { window.location.href = url.replace(/(.*)(launch_game.html)(.*)/, "$1launch_demo_game.html$3"); } }, /* The handler for the screen size toggler button. */ toggleScreenSize: function(options) { var toggler = $('screen_size_toggler'); if(toggler.hasClassName('toggled')) { Casino.gameControls.restore(options); toggler.removeClassName('toggled'); } else { Casino.gameControls.maximize(options); toggler.addClassName('toggled'); } }, /* Move the window to the top left corner and make it grow to the bottom right corner. The magic number 36 being the height of the buttons bar. The weird timeout is to make sure the window has resized before we try to resize it's contents. IE worked fine without the timeout but firefox throws weird numbers in window.innerHeight without the timeout. */ maximize: function() { window.moveTo(0,0); window.resizeTo(screen.availWidth, screen.availHeight); setTimeout(function() { var screenHeight = (window.innerHeight === undefined)? document.documentElement.clientHeight: window.innerHeight; $('game').width = screen.availWidth + "px"; $('game').height = (screenHeight - 36) + "px"; }, 200); }, /* Gets called only if the window is maximized. Reduces it's size to 800x600, but doesn't move it. */ restore: function(options) { if (!options) options = {}; var popupHeight = options.height || 600; var popupWidth = options.width || 800; var popupOffsetTop = Math.floor((screen.availHeight - popupHeight) / 2); var popupOffsetLeft = Math.floor((screen.availWidth - popupWidth) / 2); window.resizeTo(popupWidth, popupHeight); window.moveTo(popupOffsetLeft, popupOffsetTop); var screenHeight = (window.innerHeight === undefined)? document.documentElement.clientHeight: window.innerHeight; $('game').width = popupWidth + "px"; $('game').height = (screenHeight - 36) + "px"; } } }; var Widgets = {}; Widgets.Spinner = Class.create({ initialize : function(DOMElement, configuration) { configuration = configuration?configuration:{}; this.DOMElement = $(DOMElement); this.ul = new Element('ul'); this.autoScroll = ('autoScroll' in configuration) ? configuration.autoScroll:true; this.autoScrollDelay = ('autoScrollDelay' in configuration) ? configuration.autoScrollDelay:2; this.scrollButtons = ('scrollButtons' in configuration) ? configuration.scrollButtons:true; this.itemsInView = ('itemsInView' in configuration) ? parseInt(configuration.itemsInView,10):3; this.itemList = this.DOMElement.select('li'); this.lastItemShown = 0; this.spinnify(); }, spinnify : function() { var someItem = this.itemList[0]; this.DOMElement.insert({ before : this.ul }); this.ul.setStyle({ 'overflow': 'hidden', 'display': 'block', 'height' : (someItem.clientHeight * this.itemsInView) + "px" }); /*this.DOMElement.style.overflow = "hidden"; this.DOMElement.style.display = "block"; this.DOMElement.style.height = (someItem.clientHeight * this.itemsInView) + "px";*/ /*while(this.DOMElement.childNodes[0]) { this.DOMElement.removeChild(this.DOMElement.childNodes[0]); }*/ (this.itemsInView).times(function(i) { this.ul.appendChild(this.itemList[i]); this.lastItemShown = i; }.bind(this)); if(this.autoScroll) { setTimeout( this.scrollDown.bind(this), (this.autoScrollDelay * 1000) ); } }, scrollDown : function() { ++this.lastItemShown; if(this.lastItemShown == this.itemList.length) { this.lastItemShown = 0; } this.ul.appendChild(this.itemList[this.lastItemShown]); (20).times(function(i) { setTimeout(function() { this.ul.scrollTop = this.ul.scrollTop + 5; if(this.ul.scrollTop >= 100) { this.finishScrollDown(); } }.bind(this), (50 * i)); }.bind(this)); }, finishScrollDown : function() { //~ var childToDelete; //~ var ulChilds = this.ul.select('li'); //~ //~ if(this.lastItemShown < this.itemsInView) { //~ childToDelete = //~ ulChilds.length + (this.lastItemShown - this.itemsInView); //~ } //~ else { //~ childToDelete = this.lastItemShown - this.itemsInView; //~ } //~ this.ul.removeChild(ulChilds[childToDelete]); //~ this.ul.scrollTop = 0; this.ul.removeChild(this.ul.down('li')); this.ul.scrollTop = 0; if(this.autoScroll) { setTimeout( this.scrollDown.bind(this), (this.autoScrollDelay * 1000) ); } } }); var LoginForm = { form : null, init : function() { this.form = $('log_in'); // dinamically sends Meteor information when log in if (this.form) {this.form.observe('submit', this.createMeteorStatusHiddenFields.bindAsEventListener(this))} // login fields functionallity var loginField = $('login'); var passwordField = $('password'); var passwordVisibleField = $('password_visible'); loginField.observe('focus', function() { loginField.addClassName('focus'); if (!loginField.hasClassName('edited')) { loginField.value = ''; loginField.addClassName('edited'); } }); passwordVisibleField.observe('focus', function() { passwordVisibleField.hide(); passwordField.show(); passwordField.focus(); }); }, createMeteorStatusHiddenFields : function() { var meteor = top.Meteor; var fieldHtml = new Template(''); if (meteor) { if ('meteor_id' in this.form.elements) this.form.elements['meteor_id'].value = meteor.hostid; else this.form.insert(fieldHtml.evaluate({name : 'meteor_id', value : meteor.hostid})); if ('meteor_status' in this.form.elements) this.form.elements['meteor_status'].value = meteor.status; else this.form.insert(fieldHtml.evaluate({name : 'meteor_status', value : meteor.status})); } } } var NavigationTop = { broadcaster : new Broadcaster('navigationtop'), userInfo : { user_logged_in : 0, user_name : 'Guest' }, init : function() { this.updateUserInfo(); this.initToggleBalanceOnFocus(); /* search for new features and mark them! */ this.markNewFeatures(); }, showError : function(msg) { var node = $('nav_top_error'); if (node) { node.update(msg); node.show(); } }, /* * TODO! Move this out of here */ updateUserInfo : function() { var token = (this.getToken() !== null)?'/'+this.getToken():''; var url = Vars.siteURL + token + '/ajax/' + Vars.lang + '/user_information.json.html'; new Ajax.Request(url, { requestHeaders: { Accept: 'application/json' }, method: 'get', onSuccess : function(transport, json) { if(!json) json = transport.responseText.evalJSON(true); this.userInfo = json; if(this.userInfo.user_logged_in) { this.broadcaster.say('logged_in'); this.updateBalance(); if($('logged_user_info')) { $('logged_user_info').removeClassName('none'); } if($('user_controls')) { $('user_controls').removeClassName('none'); } if($('login_box')) { $('login_box').addClassName('none'); } $('logged_user_name_label').innerHTML = this.userInfo.user_name; if($('navtop_register_link')) { $('navtop_register_link').addClassName('none'); } if($('navtop_affiliates_link')) { $('navtop_affiliates_link').addClassName('none'); } } else { this.broadcaster.say('logged_out'); if($('login_box')) { $('login_box').removeClassName('none'); } if($('navtop_register_link')) { $('navtop_register_link').removeClassName('none'); } if($('navtop_affiliates_link')) { $('navtop_affiliates_link').removeClassName('none'); } if($('logged_user_info')) { $('logged_user_info').addClassName('none'); } if($('user_controls')) { $('user_controls').addClassName('none'); } LoginForm.init(); } }.bind(this) }); }, updateBalance : function() { var url = Vars.siteURL + '/' + this.getToken() + '/ajax/' + Vars.lang + '/balance_data.json.html'; new Ajax.Request(url, { requestHeaders: {Accept: 'application/json'}, // parameters : '', method : 'get', onSuccess: function(transport, json) { if (!json) json = transport.responseText.evalJSON(true); if ($('balance')) { $('balance').update(json.balance + ' ' + (Gambit.user.currencyCode || Vars.currencySymbol)); } } }); }, getToken : function() { var urlstr = new String(window.location); var urlPieces = urlstr.split('/'); if(urlPieces[3] && urlPieces[3].length === 20) { return urlPieces[3]; } else { return null; } }, /* Examine the links for each section to see if they are marked as a new feature. Return an array of the elements that have the 'new_feature' class */ searchForNewFeatures : function() { var menuElements = $('nav_top_holder').down('.sites_menu').select('li'); var newFeatures = []; menuElements.each(function(menuElement) { if(menuElement.hasClassName('new_feature')) { newFeatures.push(menuElement); } }); return newFeatures; }, /* Applies a fade in effect to the element 'mark' */ fadeInMark : function(mark) { var fadeInStepping = 0.05; //max 1 var fadeInIntervalDuration = 200; //in ms /* make it appear */ var currentOpacity = 0; var delay = 0; for(i = (fadeInIntervalDuration/fadeInStepping/fadeInIntervalDuration); i > 0; i--) { delay = fadeInIntervalDuration * ((fadeInIntervalDuration/fadeInStepping/fadeInIntervalDuration) - i + 1); setTimeout(function() { currentOpacity += fadeInStepping; mark.style.opacity = currentOpacity; mark.style.filter = 'alpha(opacity:'+Math.floor(currentOpacity*100)+')'; }, delay); } }, /* Make the element spin 360° clockwise by setting N(depends on how the animation is set up) timeouts, each transforming the element a certain amount of degrees. Before executing the animation i add the "spinning" class to the element so that i can tell that the animation is in progress. */ spinMark : function(mark) { var spinStepping = 15; //in deg var spinIntervalDuration = 35; //in ms var currentAngle = 0; var delay = 0; if(!mark.hasClassName('spinning')) { mark.addClassName('spinning'); for(i = 360/spinStepping; i > 0; i--) { delay = spinIntervalDuration * ((360/spinStepping) - i + 1); setTimeout(function() { currentAngle += spinStepping; mark.style.MozTransform = 'rotate('+currentAngle+'deg)'; }, delay); } setTimeout(function() { mark.removeClassName('spinning'); }, delay + 1); } }, /* Look around to see if there is any new feature, add a mark to them and do some crappy animations. */ markNewFeatures : function() { var newFeatures = $A(this.searchForNewFeatures()); newFeatures.each(function(newFeature) { var newFeatureMark = document.createElement('div'); $(newFeatureMark).addClassName('mark'); newFeature.appendChild(newFeatureMark); /* webkit supports both, transition and transform; gecko supports only transform; and IE doesn't support anything. Since i only need CSS for webkit, check for mozTransform to emulate the transition with js and completly ignore IE. */ if(newFeatureMark.style.MozTransform !== undefined) { newFeatureMark.observe('mouseover', function(ev) { this.spinMark(newFeatureMark); }.bind(this)); } this.fadeInMark(newFeatureMark); }.bind(this)); }, /* Returns true or false whether there is a casino game open or not. */ casinoGameOpen : function() { return (parseInt(getCookie('casino_game_mode')) === 1); }, initToggleBalanceOnFocus : function() { if(!Prototype.Browser.IE) { $(window.document).observe('focus', this.siteOnFocus.bindAsEventListener(this)); $(window.document).observe('blur', this.siteOnBlur.bindAsEventListener(this)); } }, /* This method gets called any time our page/s is focused or blurred. If the main window has focus it shows the balance. Additionaly if a casino game is open, we update said balance. If the main window is blurred and a casino game is open, we hide the balance. */ toggleBalanceOnFocus : function() { try { var balanceElement = $('balance').up('p'); if(this.siteHasFocus()) { if(this.casinoGameOpen() || balanceElement.hasClassName('none')) { this.updateBalance(); } balanceElement.removeClassName('none'); } else { if(this.casinoGameOpen()) { balanceElement.addClassName('none'); } } } catch(e) { /* Most likely the user isn't logged in and thus the balance element doesn't exist */ } }, siteHasFocus : function() { return $(document.body).hasClassName('has_focus'); }, siteOnFocus : function() { $(document.body).addClassName('has_focus'); this.toggleBalanceOnFocus(); }, siteOnBlur : function() { $(document.body).removeClassName('has_focus'); this.toggleBalanceOnFocus(); } }