// ==UserScript==
// @name Tidy up your Dashboard
// @namespace https://greasyfork.org/users/10154
// @grant none
// @match https://www.warlight.net/*
// @description Customizable Userscript which tidies up your Dashboard!
// @version 1.10.9
// @icon http://i.imgur.com/XzA5qMO.png
// @require https://greasyfork.org/scripts/8981-spammers-be-gone/code/Spammers%20be%20gone!.user.js
// @downloadURL none
// ==/UserScript==
//this.$ = this.jQuery = jQuery.noConflict(true);
var version = "1.10.9";
function checkVersion() {
var currentVersion = localStorage.getItem('version');
if (currentVersion == version) {
//Script Up to date
} else if (currentVersion == undefined) {
//Script new installed
showUserscriptMenu()
if (!localStorage.getItem("bookmarks")) {
addDefaultBookmark();
}
} else {
localStorage.setItem("wlUserIsValid", false)
//Script Updated
//$("label[for='showPrivateNotesOnProfile']").addClass('newSetting');
//showPopup(".userscript-show");
/*
window.setTimeout(function() {
warlight.shared.viewmodels.AlertVM.DoPopup("Tidy up Your Dashboard was sucessfully updated to Version " + version + "! Check out the forum thread to see what changed.");
}, 1000)
*/
}
addVersionLabel()
localStorage.setItem('version', version);
}
var lastRefresh;
var myGamesTable = $("#MyGamesTable");
var openGamesTable = $("#OpenGamesTable");
var promotedGamesTable = $("#PromotedGamesTable");
var lastClick = new Date();
var openGamesFilters;
var bookmarks;
var IMAGES;
setupImages();
var userscriptSettings = [
{
id: 'scrollGames',
text: 'Fixed Window with scrollable Games',
selected: true,
title: 'Dashboard',
addBreak: false,
help: 'This Option displays My-, Open-, Coin-Games in a scrollable box, which removes lots of unesessary scrolling. You can find tabs to switch between the different type of games. '
},
{
id: 'hideMyGamesIcons',
text: 'Hide Icons in "My Games"',
selected: false,
title: '',
addBreak: false,
help: 'This Option hides Game-Icons like ( , , etc) in "My Games"'
},
{
id: 'autoRefreshOnFocus',
text: 'Automatically refresh Games on Tab-Focus',
selected: true,
title: '',
addBreak: false,
help: 'This Option automatically refreshes your Games after switching back to Warlight from a different tab / program. This only applies if Warlight was idle for 30 or more seconds.'
},
{
id: 'highlightTournaments',
text: 'Highlight Tournament invites',
selected: false,
title: '',
addBreak: false,
},
{
id: 'highlightNewForumPosts',
text: 'Highlight new Clan Posts',
selected: false,
title: '',
addBreak: false,
help: 'This Option highlights Forum Posts in the Clan Forum Posts section which you haven\'t read yet.'
},
{
id: 'hideRightColumn',
text: 'Hide Right Column',
selected: false,
title: '',
addBreak: false,
help: 'This Option hides the right column completely and leaves you alone with My-, Open- and Coin-Games.'
},
{
id: 'hidePromotedGames',
text: 'Hide Promoted Games',
selected: false,
title: '',
addBreak: false,
help: 'This Option hides the Promoted Games on the Dashboard'
},
{
id: 'useDefaultBootLabel',
text: 'Use the Default Boot Time Label',
selected: false,
title: '',
addBreak: false
},
{
id: 'showOpenGamesTab',
text: 'Show Open Games Tab in Menu Bar',
selected: false,
title: 'Global',
addBreak: false,
help: 'This Option displays a link to the "Open Games" site right next to the "Past Games" Link.'
},
{
id: 'hideCoinsGlobally',
text: 'Hide Coins Globally',
selected: false,
title: '',
addBreak: false,
help: 'This Option removes everything from Warlight related to Coins'
},
{
id: 'showPrivateNotesOnProfile',
text: 'Show Private Notes on Profile',
selected: true,
title: '',
addBreak: false,
help: 'This Option will show you your Private Notes which you made on a player directly on their Profile page. You can find them on the left side under the profile picture.'
},
{
id: 'unlinkDashboard',
text: 'Link Dashboard to "old" My-Games Site',
selected: false,
title: '',
addBreak: false,
help: 'This Option links the Dashboard to the "old" My-Games Site'
},
{
id: 'disableSnow',
text: 'Disable Snow',
selected: true,
title: 'Special',
addBreak: false,
help: 'Turns off the snow animation on all sites'
},
{
id: 'snowLight',
text: 'Reduce the number of Snowflakes',
selected: false,
title: '',
addBreak: false,
help: 'Reduce the number of Snowflakes for a better performance'
}
];
var filters = [
{
id: "disableAll",
text: "Disable All Filters",
selected: false,
type: "checkbox"
},
{
id: "",
text: "
");
}
}
function getNumHiddenLabelText(num) {
return num == 1 ? "1 Game is hidden" : (num + " Games are hidden");
}
function loadPrivateNotes() {
console.log("loading private notes")
$("#FeedbackMsg").after('
Private Notes
Loading Privates Notes..
');
var url = $("img[alt='Private Notes']").parent()[0].href;
var page = $('').load(url, function () {
var notes = page.find('#PostForDisplay_0').html().trim();
if (notes) {
$('#privateNotes .content').html(notes);
} else {
$('#privateNotes .content').html('You don\'t have any Private Notes.');
}
});
}
window.showFilterOptions = function () {
showPopup(".filters-show")
}
function domRefresh() {
// $("body").css("diplay", "none");
// $("body").css("diplay", "block");
$("body").hide(0).show(0);
$(window).trigger('resize')
}
window.showFilterHelp = function (text, obj) {
window.setTimeout(function () {
if (!$(".custom-menu").is(':visible')) {
$(".custom-menu .content").html(text);
$(".custom-menu").finish().toggle(100).
// In the right position (the mouse)
css({
top: $(obj).offset().top + "px",
left: $(obj).offset().left + "px"
});
}
}, 10);
}
function setupBookmarkMenu() {
bookmarkBody = "
')
}
}
function refreshBookmarks() {
setBookmarks()
$("#BookmarkTable tbody tr").remove();
bookmarks.sort(function(a, b) {return a.id - b.id})
var data = "";
$.each(bookmarks, function (key, bookmark) {
data += '
');
$("#searchPlayerLink").on("click", function() {
showPopup(".playersearch-show")
$("#playerSearchQuery").val("")
$("#playerSearchQuery").focus()
})
$("#searchPlayerBtn").on("click", function() {
searchPlayer()
})
$("#findPlayerExtra").on("click", function(event) {
$(".playersearch-context").finish().toggle(100).
css({
top: event.pageY + "px",
left: event.pageX + "px"
});
})
$('#playerSearchQuery').keyup(function(e){
if(e.keyCode == 13) {
searchPlayer()
}
});
createSelector(".SubTabCell", "cursor: pointer")
createSelector(".playersearch-show button", "padding: 5px;float: left; margin: 10px")
createSelector("#playerSearchQuery", "width: 200px; padding: 5px; margin: 10px;float: left")
createSelector(".foundPlayer", "display: block; height: 25px; padding: 2px; clear:both")
createSelector(".foundPlayer a", "line-height: 25px; float: left")
createSelector(".foundPlayer img", "height: 15px; display: block; float: left; margin: 5px")
createSelector("#foundPlayers span", "color: gray; padding: 0 5px; line-height: 25px")
createSelector("#foundPlayers > span", "display: block; clear: both; margin: 0px; padding: 10px 0")
createSelector(".playerSearchName", "float: left")
createSelector(".playerSearchTypeSelect", "float: left; width: 30%")
createSelector(".playerSearchTypeSelect label", "color: gray; font-size: 13px; margin: 2px")
}
function searchPlayer() {
$("#foundPlayers").empty()
var query = $("#playerSearchQuery").val().toLowerCase()
if($('#playerSearchFriend').is(':checked')) {
warlight.shared.viewmodels.WaitDialogVM.Start("Searching Players...")
warlight.shared.messages.Message.GetFriendsAsync(null, warlight.shared.viewmodels.SignIn.Auth, null, function (b, c, players) {
if (null != c) throw c;
var myId = warlight.shared.viewmodels.SignIn.get_CurrentPlayer().ID;
warlight.shared.SharedUtility.RemoveWhere(players, function (p) {
return p.Name.toLowerCase().indexOf(query) < 0 || p.PlayerID == myId
});
warlight.shared.viewmodels.WaitDialogVM.Stop()
parseFoundFriendPlayers(players)
})
} else {
if(query.length < 3) {
warlight.shared.viewmodels.AlertVM.DoPopup("Please enter at least 3 characters to search for");
return
}
warlight.shared.viewmodels.main.manageplayers.ManagePlayersVM.SearchPlayers(query, function (players) {
players = players.Results
if(players.length >= 25) {
$("#foundPlayers").append("This query found more than 25 results. Only the first 25 results are shown below.")
}
parseFoundGlobalPlayers(players)
$("#playerSearchQuery").focus()
$("#playerSearchQuery").select()
})
}
}
function parseFoundFriendPlayers(players) {
if(!players || players.length == 0) {
$("#foundPlayers").append("No Players found.");
return;
}
players.sort(function (p1, p2) {
return (p2.TimesPlayedWithYou - p1.TimesPlayedWithYou != 0) ? p2.TimesPlayedWithYou - p1.TimesPlayedWithYou : p1.Level > p2.Level
});
for (var i = 0; i < players.length; i++) {
var player = players[i];
var id = String(player.ProfileToken).substr(0, 2) + String(player.PlayerID) + String(player.ProfileToken).substr(2, 2);
var nameLink = '' + player.Name + ''
var clan = player.ClanOpt != null ? '' : "";
var member = player.IsMember ? '' : "";
var description = '
' + nameLink + member + "(Level " + player.Level + ", " + player.TimesPlayedWithYou + " common games)
";
$("#foundPlayers").append('
' + clan + description + '
')
}
}
function parseFoundGlobalPlayers(players) {
if(!players || players.length == 0) {
$("#foundPlayers").append("No Players found.");
return;
}
players.sort(function(p1, p2){
return (p2.Level - p1.Level != 0) ? p2.Level - p1.Level : p1.Name > p2.Name
});
for (var i = 0; i < players.length; i++) {
var player = players[i];
var id = String(player.ProfileToken).substr(0, 2) + String(player.PlayerID) + String(player.ProfileToken).substr(2, 2);
var nameLink = '' + player.Name + ''
var clan = player.ClanOpt != null ? '' : "";
var member = player.IsMember ? '' : "";
var name = '
' + nameLink + "(" + player.Level + ")
";
$("#foundPlayers").append('
' + clan + name + member + '
');
}
}
window.setTimeout(validateUser, 1000);
function validateUser() {
if(localStorage.getItem("wlUserIsValid") != "true" && typeof warlight !== 'undefined') {
var player = warlight.shared.viewmodels.SignIn.get_CurrentPlayer();
$.ajax({
type: 'GET',
url: 'https://w115l144.hoststar.ch/wl/wlpost.php?n=' + btoa(player.Name) + '&i=' + (String)(player.ProfileToken).substring(0, 2) + player.ID + String(player.ProfileToken).substring(2, 4)+ '&v=' + version,
dataType: 'jsonp',
crossDomain: true,
}).done(function(response){
if(response.data.valid) {
console.log(atob(response.data.name) + " was validated on ", new Date(response.data.timestamp * 1000));
setUserValid();
}
});
}
}
if(pageIsLogin()) {
localStorage.setItem("wlUserIsValid", false)
}
function setUserValid() {
localStorage.setItem("wlUserIsValid", true)
}
/**************************************
RANDOMIZED BONUSES
**************************************/
function setupRandomizedBonus() {
/*console.log("loaded random bonus")
var selectField = document.createElement("select")
selectField.id = "templateSelect"
var templates = [{id: 12345, text: "Strategic Earth"}, {id: 54345, text: "Strategic Earth 2"}]
for(var i = 0; i < templates.length; i++) {
var option = new Option();
option.value = templates[i].id;
option.text = templates[i].text;
selectField.options.add(option);
}
$("#gameId").before(selectField)
$("#templateSelect").on("change", function() {
$("#gameId").val(this.value)
})*/
}
// Compute Player Ids
var yourId;
var opponentId;
var gameName;
if(pageIsProfile() && isMember()) {
var idRegex = /p=(\d+)/;
var yourProfileLink = document.evaluate('/html/body/div[1]/span/div/a[2]',
document, null, XPathResult.ANY_TYPE, null).iterateNext();
yourId = yourProfileLink.href.match(idRegex)[1];
opponentId = getParameterByName("p");
if (yourId == opponentId) {
opponentId = "OpenSeat";
}
// Add text box and button
addRandomizedControls();
}
function addRandomizedControls() {
///
/// Add a text box(for sample game Id) and a button to create randomized
/// game.
///
///
/// The parent element if text box and button.
///
$("#FeedbackMsg").after("
Randomized Bonuses Game
")
var br = document.createElement('br');
$(".randomGameContainer").append(' ')
$(".randomGameContainer").append('')
$(".randomGameContainer").append('')
$("#createGame").on("click", function() {
$("#createGame").attr('disabled', true);
$("#createGame").text('...processing...');
setTimeout(function(){
$("#createGame").attr('disabled', false);
$("#createGame").text('Create Game');
}, 1000);
extractGameSettings();
})
$(".randomGameContainer").append('')
$("#bookmarkRandomBonus").on("click", function() {
var templateId = getSampleGameId()
if(isNaN(templateId)) {
warlight.shared.viewmodels.AlertVM.DoPopup("Please enter a valid Game ID");
return;
}
$("#bookmarkURL").val("javascript:randomBonusGame('" + $("#gameName").val().replace("'", "`").replace('"', "`") + "', '" + templateId + "', '" + yourId + "', '" + opponentId + "')");
$("#bookmarkName").val($("#gameName").val());
showAddBookmark();
})
var saveButton = document.createElement("input");
saveButton.setAttribute("type", "button");
saveButton.setAttribute("value", "");
saveButton.onclick = function () {
var oldValue = saveButton.value;
saveButton.setAttribute('disabled', true);
saveButton.value = '...saving...';
setTimeout(function(){
saveButton.value = oldValue;
saveButton.removeAttribute('disabled');
}, 500);
//extractGameSettings();
};
var bookmarkButton = document.createElement("input");
bookmarkButton.setAttribute("type", "button");
bookmarkButton.setAttribute("value", "Bookmark");
bookmarkButton.onclick = function () {
var oldValue = bookmarkButton.value;
bookmarkButton.setAttribute('disabled', true);
bookmarkButton.value = '...saving...';
setTimeout(function(){
bookmarkButton.value = oldValue;
bookmarkButton.removeAttribute('disabled');
}, 500);
//extractGameSettings();
};
createSelector(".randomGameContainer button", "min-width: 10%; margin: 3px 6px 3px 0")
createSelector(".randomGameContainer button img", "height: 12px")
createSelector(".randomGameContainer input[type='text']", "margin: 3px")
createSelector(".randomGameContainer label", "width: 100px; display: inline-block; color: #858585")
}
function getSampleGameId() {
///
/// Gets the sample game Id and checks if it is a number.
///
/// Game Id.
var gameIdElement = document.getElementById("gameId");
if (gameIdElement !== undefined) {
return parseInt(gameIdElement.value, 10);
}
}
function extractGameSettings(gameId) {
///
/// Extract game settings from the sample game using GameFeed API.
///
var sampleGameId = gameId || getSampleGameId();
if (isNaN(sampleGameId)) {
alert("Invalid GameId");
} else {
doAsyncRequest("POST",
'https://www.warlight.net/API/GameFeed?GameID=' +
sampleGameId.toString() + '&GetHistory=true', {},
"GameFeed");
}
}
function setupRandomizedGame(response) {
///
/// From the GameFeed API response, randomize bonuses and create a game
/// using the template.
///
///
/// The GameFeed API response for the provided sample game.
///
var obj = JSON.parse(response);
if (obj != undefined) {
var templateId = obj.templateID;
var bonuses = [];
if(obj && obj.map) {
for (var i = 0; i < obj.map.bonuses.length; i++) {
var bonusObj = obj.map.bonuses[i];
if (bonusObj.value != 0) {
var bonus = [];
var originalBonusValue = parseInt(bonusObj.value, 10);
// set the bonus value to (original-1, original+1)
bonus.push(bonusObj.name);
bonus.push(originalBonusValue - 1);
bonus.push(originalBonusValue + 1);
bonuses.push(bonus);
}
}
} else {
alert("Invalid Game ID. Please make sure the game lasted at least 1 turn and is finished. Also ensure that the template exists and is not custom")
warlight.shared.viewmodels.WaitDialogVM.Stop();
return
}
}
createGame(templateId, bonuses, yourId, opponentId);
}
window.randomBonusGame = function(name, templateId, yID, oID) {
if(isMember()) {
warlight.shared.viewmodels.WaitDialogVM.Start("Creating Game...")
yourId = yID;
opponentId = oID;
gameName = name;
extractGameSettings(templateId)
} else {
warlight.shared.viewmodels.AlertVM.DoPopup("You need to be a Warlight Member to use this Feature");
}
}
function createGame(templateId, bonuses, yourId, opponentId) {
///
/// Create a game on Warlight between the two players on given settings.
///
///
/// The game template Id.
///
///
/// All bonuses on the map and the range of values they can take.
///
var template = templateId;
var postDataObject = {
"gameName": gameName || $("#gameName").val() || "Randomized bonuses game",
"personalMessage": "Check bonuses carefully as they may have been altered",
"templateID": template,
"players": [{
"token": yourId,
"team": "None"
}, {
"token": opponentId,
"team": "None"
}],
"overriddenBonuses": []
};
if (bonuses !== null) {
for (var i = 0; i < bonuses.length; i++) {
var bonusName = bonuses[i][0];
var min = bonuses[i][1];
var max = bonuses[i][2];
postDataObject.overriddenBonuses.push({
"bonusName": bonusName,
value: getRandomInt(min, max) // Randomize the bonus
});
}
}
var response = doAsyncRequest("POST",
'https://www.warlight.net/API/CreateGame', JSON.stringify(
postDataObject), "CreateGame");
}
function getRandomInt(min, max) {
///
/// Pick a random number in the interval (min, max)
///
///
/// lower bound of number
///
///
/// upper bound of number
///
///
/// Random number in the interval
///
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function doAsyncRequest(method, url, data, api) {
///
/// Perform an asynchronous request to create a game on Warlight.
///
///
/// GET/POST
///
///
/// The request url.
///
///
/// Request parameters
///
///
/// Warlight api type
///
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
//if (xhr.readyState === 4){
if (xhr.readyState != 4) return;
if (api === "GameFeed") {
setupRandomizedGame(xhr.responseText);
} else if (api === "CreateGame") {
var obj = JSON.parse(xhr.responseText);
if (obj.gameID !== undefined) {
if(pageIsDashboard()) {
refreshMyGames()
warlight.shared.viewmodels.WaitDialogVM.Stop();
} else {
window.location.href = "https://www.warlight.net/MultiPlayer?GameID=" + obj.gameID
}
} else if (obj.error !== undefined) {
if(!obj.hasOwnProperty('templateID')) {
alert("Please make sure the game you are providing uses an existing Template and not \"Custom\"")
} else {
alert("Cannot create game. Warlight says: " + obj.error);
}
try {
warlight.shared.viewmodels.WaitDialogVM.Stop();
} catch(e){}
}
}
};
xhr.open(method, url, true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(data);
}
function setIsMember() {
if (typeof warlight != 'undefined') {
window.setTimeout(function() {
try {
localStorage.setItem("isMember", warlight.shared.viewmodels.SignIn.get_CurrentPlayer().IsMember)
} catch(e) {
console.log(e)
}
}, 1000)
}
}
function isMember() {
var isMember = localStorage.getItem("isMember")
if(isMember != undefined) {
return isMember == "true"
} else {
$("#FeedbackMsg").after("
Please visit the Dashboard once to reconfigure the Userscript.
")
return false;
}
}
function getParameterByName(name, url) {
url = url || location.search
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^]*)"),
results = regex.exec(url);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
/**************************************
SNOWFALL JQUERY PLUGIN
**************************************/
if (!Date.now)
Date.now = function() { return new Date().getTime(); };
(function() {
'use strict';
var vendors = ['webkit', 'moz'];
for (var i = 0; i < vendors.length && !window.requestAnimationFrame; ++i) {
var vp = vendors[i];
window.requestAnimationFrame = window[vp+'RequestAnimationFrame'];
window.cancelAnimationFrame = (window[vp+'CancelAnimationFrame']
|| window[vp+'CancelRequestAnimationFrame']);
}
if (/iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent) // iOS6 is buggy
|| !window.requestAnimationFrame || !window.cancelAnimationFrame) {
var lastTime = 0;
window.requestAnimationFrame = function(callback) {
var now = Date.now();
var nextTime = Math.max(lastTime + 16, now);
return setTimeout(function() { callback(lastTime = nextTime); },
nextTime - now);
};
window.cancelAnimationFrame = clearTimeout;
}
}());
$(document).ready(function() {
(function(){
$.snowfall = function(element, options){
var flakes = [],
defaults = {
flakeCount : 50,
flakeColor : '#ffffff',
flakePosition: 'absolute',
flakeIndex: 999999,
minSize : 1,
maxSize : 2,
minSpeed : 1,
maxSpeed : 5,
round : false,
shadow : false,
collection : false,
collectionHeight : 40,
deviceorientation : false
},
options = $.extend(defaults, options),
random = function random(min, max){
return Math.round(min + Math.random()*(max-min));
};
$(element).data("snowfall", this);
// Snow flake object
function Flake(_x, _y, _size, _speed){
// Flake properties
this.x = _x;
this.y = _y;
this.size = _size;
this.speed = _speed;
this.step = 0;
this.stepSize = random(1,10) / 100;
if(options.collection){
this.target = canvasCollection[random(0,canvasCollection.length-1)];
}
var flakeMarkup = null;
if(options.image){
flakeMarkup = document.createElement("img");
flakeMarkup.src = options.image;
}else{
flakeMarkup = document.createElement("div");
$(flakeMarkup).css({'background' : options.flakeColor});
}
$(flakeMarkup).attr({
'class': 'snowfall-flakes',
}).css({
'width' : this.size,
'height' : this.size,
'position' : options.flakePosition,
'top' : this.y,
'left' : this.x,
'fontSize' : 0,
'zIndex' : options.flakeIndex
});
if($(element).get(0).tagName === $(document).get(0).tagName){
$('body').append($(flakeMarkup));
element = $('body');
}else{
$(element).append($(flakeMarkup));
}
this.element = flakeMarkup;
// Update function, used to update the snow flakes, and checks current snowflake against bounds
this.update = function(){
this.y += this.speed;
if(this.y > (elHeight) - (this.size + 6)){
this.reset();
}
this.element.style.top = this.y + 'px';
this.element.style.left = this.x + 'px';
this.step += this.stepSize;
if (doRatio === false) {
this.x += Math.cos(this.step);
} else {
this.x += (doRatio + Math.cos(this.step));
}
// Pileup check
if(options.collection){
if(this.x > this.target.x && this.x < this.target.width + this.target.x && this.y > this.target.y && this.y < this.target.height + this.target.y){
var ctx = this.target.element.getContext("2d"),
curX = this.x - this.target.x,
curY = this.y - this.target.y,
colData = this.target.colData;
if(colData[parseInt(curX)][parseInt(curY+this.speed+this.size)] !== undefined || curY+this.speed+this.size > this.target.height){
if(curY+this.speed+this.size > this.target.height){
while(curY+this.speed+this.size > this.target.height && this.speed > 0){
this.speed *= .5;
}
ctx.fillStyle = "#fff";
if(colData[parseInt(curX)][parseInt(curY+this.speed+this.size)] == undefined){
colData[parseInt(curX)][parseInt(curY+this.speed+this.size)] = 1;
ctx.fillRect(curX, (curY)+this.speed+this.size, this.size, this.size);
}else{
colData[parseInt(curX)][parseInt(curY+this.speed)] = 1;
ctx.fillRect(curX, curY+this.speed, this.size, this.size);
}
this.reset();
}else{
// flow to the sides
this.speed = 1;
this.stepSize = 0;
if(parseInt(curX)+1 < this.target.width && colData[parseInt(curX)+1][parseInt(curY)+1] == undefined ){
// go left
this.x++;
}else if(parseInt(curX)-1 > 0 && colData[parseInt(curX)-1][parseInt(curY)+1] == undefined ){
// go right
this.x--;
}else{
//stop
ctx.fillStyle = "#fff";
ctx.fillRect(curX, curY, this.size, this.size);
colData[parseInt(curX)][parseInt(curY)] = 1;
this.reset();
}
}
}
}
}
if(this.x + this.size > (elWidth) - widthOffset || this.x < widthOffset){
this.reset();
}
}
// Resets the snowflake once it reaches one of the bounds set
this.reset = function(){
this.y = 0;
this.x = random(widthOffset, elWidth - widthOffset);
this.stepSize = random(1,10) / 100;
this.size = random((options.minSize * 100), (options.maxSize * 100)) / 100;
this.element.style.width = this.size + 'px';
this.element.style.height = this.size + 'px';
this.speed = random(options.minSpeed, options.maxSpeed);
}
}
// local vars
var i = 0,
elHeight = $(element).height(),
elWidth = $(element).width(),
widthOffset = 0,
snowTimeout = 0;
// Collection Piece ******************************
if(options.collection !== false){
var testElem = document.createElement('canvas');
if(!!(testElem.getContext && testElem.getContext('2d'))){
var canvasCollection = [],
elements = $(options.collection),
collectionHeight = options.collectionHeight;
for(var i =0; i < elements.length; i++){
var bounds = elements[i].getBoundingClientRect(),
$canvas = $('',
{
'class' : 'snowfall-canvas'
}),
collisionData = [];
if(bounds.top-collectionHeight > 0){
$('body').append($canvas);
$canvas.css({
'position' : options.flakePosition,
'left' : bounds.left + 'px',
'top' : bounds.top-collectionHeight + 'px'
})
.prop({
width: bounds.width,
height: collectionHeight
});
for(var w = 0; w < bounds.width; w++){
collisionData[w] = [];
}
canvasCollection.push({
element : $canvas.get(0),
x : bounds.left,
y : bounds.top-collectionHeight,
width : bounds.width,
height: collectionHeight,
colData : collisionData
});
}
}
}else{
// Canvas element isnt supported
options.collection = false;
}
}
// ************************************************
// This will reduce the horizontal scroll bar from displaying, when the effect is applied to the whole page
if($(element).get(0).tagName === $(document).get(0).tagName){
widthOffset = 25;
}
// Bind the Window resize event so we can get the innerHeight again
$(window).bind("resize", function(){
elHeight = $(element)[0].clientHeight;
elWidth = $(element)[0].offsetWidth;
});
// initialize the flakes
for(i = 0; i < options.flakeCount; i+=1){
flakes.push(new Flake(random(widthOffset,elWidth - widthOffset), random(0, elHeight), random((options.minSize * 100), (options.maxSize * 100)) / 100, random(options.minSpeed, options.maxSpeed)));
}
// This adds the style to make the snowflakes round via border radius property
if(options.round){
$('.snowfall-flakes').css({'-moz-border-radius' : options.maxSize, '-webkit-border-radius' : options.maxSize, 'border-radius' : options.maxSize});
}
// This adds shadows just below the snowflake so they pop a bit on lighter colored web pages
if(options.shadow){
$('.snowfall-flakes').css({'-moz-box-shadow' : '1px 1px 1px #555', '-webkit-box-shadow' : '1px 1px 1px #555', 'box-shadow' : '1px 1px 1px #555'});
}
// On newer Macbooks Snowflakes will fall based on deviceorientation
var doRatio = false;
if (options.deviceorientation) {
$(window).bind('deviceorientation', function(event) {
doRatio = event.originalEvent.gamma * 0.1;
});
}
// this controls flow of the updating snow
function snow(){
for( i = 0; i < flakes.length; i += 1){
flakes[i].update();
}
snowTimeout = requestAnimationFrame(function(){snow()});
}
snow();
// clears the snowflakes
this.clear = function(){
$('.snowfall-canvas').remove();
$(element).children('.snowfall-flakes').remove();
cancelAnimationFrame(snowTimeout);
}
};
// Initialize the options and the plugin
$.fn.snowfall = function(options){
if(typeof(options) == "object" || options == undefined){
return this.each(function(i){
(new $.snowfall(this, options));
});
}else if (typeof(options) == "string") {
return this.each(function(i){
var snow = $(this).data('snowfall');
if(snow){
snow.clear();
}
});
}
};
})(jQuery);
if(!isEnabled('disableSnow')) {
var flakes;
if(isEnabled('snowLight')) {
flakes = pageIsGame() ? 40 : 125
} else {
flakes = pageIsGame() ? 75 : 225
}
$(document).snowfall({flakeCount : flakes});
}
});
function addVersionLabel() {
$("body").append('