Cookie clicker tools

Cookie clicker tools (visual)

اعتبارا من 27-11-2018. شاهد أحدث إصدار.

You will need to install an extension such as Tampermonkey, Greasemonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Userscripts to install this script.

You will need to install an extension such as Tampermonkey to install this script.

You will need to install a user script manager extension to install this script.

(I already have a user script manager, let me install it!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

ستحتاج إلى تثبيت إضافة مثل Stylus لتثبيت هذا النمط.

ستحتاج إلى تثبيت إضافة لإدارة أنماط المستخدم لتتمكن من تثبيت هذا النمط.

ستحتاج إلى تثبيت إضافة لإدارة أنماط المستخدم لتثبيت هذا النمط.

ستحتاج إلى تثبيت إضافة لإدارة أنماط المستخدم لتثبيت هذا النمط.

(لدي بالفعل مثبت أنماط للمستخدم، دعني أقم بتثبيته!)

// ==UserScript==
// @name         Cookie clicker tools
// @namespace    orteil.dashnet.org
// @version      2.153
// @description  Cookie clicker tools (visual)
// @author       Anton
// @match        http://orteil.dashnet.org/cookieclicker/*
// @require      http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
// ==/UserScript==

(function() {
	'use strict';
	var log = [], newLogs = 0;

	var started = false, t2, t3, tClickFrenzy, oldTitle = '', tLog,
		tPriority, tBankAuto, tAscendDetector, isClickingNow = false,
		tSeasonSwitcher, tReloadPageOnWrongBuff, tAutoClickInterval = 75,
		version = typeof GM_info == 'function' ? GM_info().script.version : 
            (typeof GM_info == 'object' ? GM_info.script.version : '?'),
        logTitle = '<div class="section">Cookie clicker tools ' + version +' is here!</div>';
    var $logButton;

	var _history = function() {
		var hist = [];
		hist.push('2.136 - buyAll function (it is a kind of cheat)');
		hist.push('2.128 - santa and dragon upgrades');
		hist.push('2.122 - season switcher');
		hist.push('2.118 - show season unlocks in "Need to unlock" table');
		hist.push('2.114 - option to disable auto clicking');
		hist.push('2.113 - info table "Achievements to unlock"');
		hist.push('2.112 - info table "Need to unlock"');
		hist.push('2.111 - option to buy infernal upgrades');
		hist.push('2.109 - kill all wrinklers button');
		hist.push('2.107 - click first 15 minutes after ascend');
		hist.push('2.101 - remove all bufs on negative multiplier (same as reload page)');
		hist.push('2.100 - Info section + ascend detector');
		hist.push('2.099 - mouse click upgrades');
		hist.push('2.097 - auto bank storage');
		hist.push('2.096 - buy objects more than 1');
		hist.push('2.091 - priority table refactor');
		hist.push('2.090 - buy very cheap items first');
		hist.push('2.086 - clear log button');
		hist.push('2.084 - buy unknown upgrades if their price is 0.1% of cookie storage');
		hist.push('2.083 - mouse upgrades is processed as Upgrades');
		hist.push('2.082 - start from scratch');
		hist.push('2.079 - hide donate box');
		hist.push('2.078 - Kittens now is processed as Upgrades');
		return hist;
	};

	var _getKittenPercentByUpgradeName = function(kName) {
		if (kName === 'Kitten helpers') return Game.milkProgress*0.1;
		if (kName === 'Kitten workers') return Game.milkProgress*0.125;
		if (kName === 'Kitten engineers') return Game.milkProgress*0.15;
		if (kName === 'Kitten overseers') return Game.milkProgress*0.175;
		if (kName === 'Kitten managers') return Game.milkProgress*0.2;
		if (kName === 'Kitten accountants') return Game.milkProgress*0.2;
		if (kName === 'Kitten specialists') return Game.milkProgress*0.2;
		if (kName === 'Kitten experts') return Game.milkProgress*0.2;
		if (kName === 'Kitten angels') return Game.milkProgress*0.1;
		return 0;
	};

	var aBeautify = function(n, floats) {
		return Beautify(parseInt(n), floats);
	};

	var _getUpgradeListToUnlock = function() {
		var result = [];
		for (var x in Game.UnlockAt) {
			if (Game.UnlockAt.hasOwnProperty(x) &&
				Game.Upgrades.hasOwnProperty(Game.UnlockAt[x].name) &&
				Game.Upgrades[Game.UnlockAt[x].name].bought === 0)
			{
				result.push(Game.UnlockAt[x]);
			}
		}
		
		var halloweenSeason = ['Skull cookies','Ghost cookies','Bat cookies','Slime cookies','Pumpkin cookies','Eyeball cookies','Spider cookies'];
		for (x in halloweenSeason) {
			if (halloweenSeason.hasOwnProperty(x) &&
				Game.Upgrades[halloweenSeason[x]].bought === 0)
			{
				result.push({cookies:'',name:halloweenSeason[x],require:'Kill wrinkler',season:'halloween'});
			}
		}
		
		for (x in Game.easterEggs) {
			if (Game.easterEggs.hasOwnProperty(x) &&
				Game.Upgrades[Game.easterEggs[x]].bought === 0)
			{
				result.push({cookies:'',name:Game.easterEggs[x],require:'Find egg',season:'easter'});
			}
		}
		
		var valentines = ['Pure heart biscuits','Ardent heart biscuits','Sour heart biscuits','Weeping heart biscuits','Golden heart biscuits','Eternal heart biscuits'];
		var lastValentineName = '';
		for (x in valentines) {
			if (valentines.hasOwnProperty(x) &&
				Game.Upgrades[valentines[x]].bought === 0)
			{
				result.push({cookies:'',name:valentines[x],require:lastValentineName,season:'valentines'});
				lastValentineName = valentines[x];
			}
		}
		
		var christmas = ['Christmas tree biscuits','Snowflake biscuits','Snowman biscuits','Holly biscuits','Candy cane biscuits','Bell biscuits','Present biscuits'];
		for (x in christmas) {
			if (christmas.hasOwnProperty(x) &&
				Game.Upgrades[christmas[x]].bought === 0)
			{
				result.push({cookies:Game.Upgrades[christmas[x]].basePrice,name:christmas[x],require:'Christmas',season:'christmas'});
			}
		}
		
		return result;
	};

	var options = {
		bankStoragePercent: 100,
		bankStorageAuto: false,
		buyInfernalUpgrades: false,
		noClicking: false,
		autoSeason: false
	};

	var _store = function(name, value) {
		if (typeof(Storage) !== "undefined") localStorage.setItem(name, value);
	};

	var _restore = function(name, asBool) {
		if (typeof asBool === 'undefined') asBool = false;
		if (typeof(Storage) !== "undefined") {
			if (asBool) {
				return (localStorage.getItem(name) === 'true' || localStorage.getItem(name) === true);
			} else {
				return localStorage.getItem(name);
			}
		}
		else return undefined;
	};

	var _getBuffMult = function () {
		var buffMult = 1;
		for (var buff in Game.buffs) {
			if (Game.buffs[buff] !== 0 && typeof Game.buffs[buff].multCpS !== 'undefined') {
				buffMult = buffMult * Game.buffs[buff].multCpS;
			}
		}
		return buffMult === 0 ? 1 : buffMult;
	};

	var _getNormalCookiesPs = function () {
		return Game.cookiesPs > 0 ? Game.cookiesPs / _getBuffMult() : 1;
	};

	var _getMinimalMoney = function () {
		return Math.floor(_getNormalCookiesPs() * 42100 * options.bankStoragePercent / 100);
	};

	var _getMoneyCanSpend = function () {
        return Game.cookies - _getMinimalMoney();
	};

	var _getWrinklerCount = function () {
		var wrinklersCount = 0;
		for (var i in Game.wrinklers) {
			if (Game.wrinklers[i].sucked > 0) {
				wrinklersCount++;
			}
		}
		return wrinklersCount;
	};

	var priorityListObj = {}, priorityList = [];
	var _createPriorityList = function() {
		var moneyCanSpend = _getMoneyCanSpend();
		var money = Game.cookies;
		var buffMult = _getBuffMult();
		priorityList = [];
		priorityListObj = {};
		
		// top priority
		var topPriorityList = ['A festive hat','A crumbly egg','Heavenly chip secret','Heavenly cookie stand','Heavenly bakery','Heavenly confectionery','Heavenly key'];
		for (var tt in topPriorityList) {
    	    var tp = Game.Upgrades[topPriorityList[tt]];
    		if (typeof tp !== 'undefined' && tp.bought === 0 && parseInt(tp.unlocked) === 1) {
    		    tp.buy();
    		    break;
    		}
		}

		for (var g in Game.UpgradesById) {
			if (Game.UpgradesById[g].bought === 0 && parseInt(Game.UpgradesById[g].unlocked) === 1) {
				var isMultiplier = Game.UpgradesById[g].desc.indexOf('production multiplier') >= 0;
				var isDouble = Game.UpgradesById[g].desc.indexOf('<b>twice</b>') >= 0;
				var isDoubleGrandma = Game.UpgradesById[g].desc.indexOf('Grandmas are <b>twice</b>') >= 0;
				var isKitten = Game.UpgradesById[g].name.indexOf('Kitten ') >= 0;
				var isDoubleCursor = Game.UpgradesById[g].desc.indexOf('The mouse and cursors are <b>twice</b>') >= 0;
				var isClickIncrease = Game.UpgradesById[g].desc.indexOf('Clicking gains <b>+1%') >= 0;
				var isSpecialTech = Game.UpgradesById[g].pool === 'tech' && typeof Game.UpgradesById[g].clickFunction !== 'undefined';
				if (isSpecialTech && Game.UpgradesById[g].clickFunction !== 'undefined' && options.buyInfernalUpgrades) {
					delete(Game.UpgradesById[g].clickFunction);
				}
				var increasedMoney = 0;
				if (isClickIncrease) {
					increasedMoney = Game.cookiesPs * 0.01;
				} else if (isDoubleCursor) {
					increasedMoney = Game.Objects['Cursor'].storedTotalCps * Game.globalCpsMult / buffMult;
					if (isClickingNow) increasedMoney += Game.computedMouseCps * 1000 / tAutoClickInterval;
				} else if (isKitten) {
					var kittenPercent = _getKittenPercentByUpgradeName(Game.UpgradesById[g].name);
					increasedMoney = _getNormalCookiesPs() * kittenPercent;
				} else if (isDoubleGrandma) {
					increasedMoney = Game.Objects['Grandma'].storedTotalCps * Game.globalCpsMult / buffMult;
				} else if (isMultiplier) {
					increasedMoney = _getNormalCookiesPs() * Game.UpgradesById[g].power / 100;
				} else if (isDouble) {
					increasedMoney = Game.UpgradesById[g].buildingTie.storedTotalCps * Game.globalCpsMult / buffMult;
				}
				var interest = increasedMoney > 0 ? Game.UpgradesById[g].getPrice() / increasedMoney : '-';
				if (interest !== '-') {
					if (typeof priorityListObj[Math.floor(interest)] === 'undefined') {
						var pp = moneyCanSpend / Game.UpgradesById[g].getPrice(); // percent of cheapness
						if (pp > 50) interest /= pp * 50;
						priorityListObj[Math.floor(interest)] = {
							name: Game.UpgradesById[g].name,
							title: Game.UpgradesById[g].name + ' - ' + aBeautify(Game.UpgradesById[g].getPrice()),
							price: Game.UpgradesById[g].getPrice(),
							cps: 1,
							type: 'upgrade',
							id: g,
							income: increasedMoney
						};
					}
				} else if (Game.UpgradesById[g].type === 'upgrade' &&
					Game.UpgradesById[g].getPrice() < moneyCanSpend &&
					Game.UpgradesById[g].pool !== 'toggle' && (!isSpecialTech || options.buyInfernalUpgrades))
				{
					interest = Game.UpgradesById[g].getPrice() / moneyCanSpend * 1000;
					if (typeof priorityListObj[Math.floor(interest)] === 'undefined') {
						pp = moneyCanSpend / Game.UpgradesById[g].getPrice(); // percent of cheapness
						if (pp > 50) interest /= pp * 50;
						priorityListObj[Math.floor(interest)] = {
							name: Game.UpgradesById[g].name,
							title: Game.UpgradesById[g].name + ' - ' + aBeautify(Game.UpgradesById[g].getPrice()),
							price: Game.UpgradesById[g].getPrice(),
							cps: 1,
							type: 'upgrade',
							id: g,
							income: 0
						};
					}
				}
			}
		}
		for (var i in Game.ObjectsById) {
			if (typeof i !== 'undefined' && i !== 'undefined' && Game.ObjectsById.hasOwnProperty(i)) {
				if (Game.ObjectsById[i].locked === 0) {
					var cps = (Game.ObjectsById[i].storedTotalCps / Game.ObjectsById[i].amount) * Game.globalCpsMult / buffMult;
					interest = Game.ObjectsById[i].price / cps;
					var pp2 = moneyCanSpend / Game.ObjectsById[i].price; // percent of cheapness
					if (pp2 > 50) interest /= pp2 * 50;
					if (isNaN(Math.floor(interest)) && Game.ObjectsById[i].price < moneyCanSpend) interest = 0;
					priorityListObj[Math.floor(interest)] = {
						name: Game.ObjectsById[i].name,
						title: Game.ObjectsById[i].name + ' - ' + aBeautify(Game.ObjectsById[i].price),
						price: Game.ObjectsById[i].price,
						cps: cps,
						type: 'buy',
						id: i,
						income: cps
					};
					//priorityList.push(Game.ObjectsById[i].name + ' - ' + aBeautify(Game.ObjectsById[i].price) + ' (INTEREST: ' + aBeautify(interest) + ')');
				}
			}
		}
		for (i in priorityListObj) {
			if (priorityListObj.hasOwnProperty(i)) {
                var prefix = priorityListObj[i].price < moneyCanSpend ? '!!! ' : (priorityListObj[i].price < money ? '! ' : '');
                var pp1 = Math.floor(moneyCanSpend / priorityListObj[i].price * 100);
                priorityList.push(prefix + priorityListObj[i].title + ' : ' + i + ' (' + pp1 + '%)');
            }
		}
	};

	var _caption = function(txt) {
		var $v = jQuery('#versionNumber');
		if ($v.text() !== txt) $v.text(txt);
	};

	var _title = function(txt) {
		var newTitle = (newLogs > 0 ? '(' + newLogs + ') ' : '') + txt;
		if (document.title !== newTitle) {
			oldTitle = txt;
			document.title = newTitle;
		}
	};

	var _titlePercent = function(have, need, txt) {
		var percent = Math.ceil(have / (need !== 0 ? need : 1) * 100);
		_title(String(percent) + "% - " + txt);
	};

	var _logSectionTitle = function (text) {
		return '<div class="title">' + text + '</div>';
	};

	var _logSection = function (title, items) {
		return '<div class="subsection">' + _logSectionTitle(title) +
			'<div class="listing">' + items.join('</div><div class="listing">') + '</div>' +
			'</div>';
	};

	var clearLogButton = '<button data-id="clearLog" onclick="Game.CCT.onbuttonclick(this,event)">Clear Log</button>';
	var killWrinklersButton = '<button data-id="killWrinklers" onclick="Game.CCT.onbuttonclick(this,event)">Kill wrinklers</button>';
	var buyEverything = '<button data-id="buyEverything" onclick="Game.CCT.onbuttonclick(this,event)">Buy everything</button>';

	var _logPriorityTable = function() {
		var moneyCanSpend = _getMoneyCanSpend();
		var styles = '<style type="text/css">.prioritytable{width:100%;}.prioritytable td,.prioritytable th{padding:3px;}</style>';
		var t = '<table class="prioritytable"><tr style="border-bottom:1px solid;text-align:left;font-weight:bold;"><th>Type</th><th>Name</th><th>Price</th><th>Interest</th><th>Income</th><th>% bank</th></tr>';
		for (var i in priorityListObj) {
			if (priorityListObj.hasOwnProperty(i)) {
                var o = priorityListObj[i];
                var pp = Math.floor(moneyCanSpend / o.price * 100);
                t += '<tr><td>' + o.type + '</td><td>' + o.name + '</td><td>' + aBeautify(o.price) + '</td><td>' + i + '</td><td>' + aBeautify(o.income) + '</td><td>' + pp + '</td></tr>';
            }
		}
		t += '</table>';
		return styles + '<div class="subsection">' + _logSectionTitle('Priority ' + clearLogButton + ' ' + killWrinklersButton + ' ' + buyEverything) + '<div class="listing">' + t + '</div></div>';
	};

	var _logNeedBuyTable = function() {
		var objList = _getUpgradeListToUnlock();
		if (objList && objList.length > 0) {
			var styles = '<style type="text/css">.prioritytable{width:100%;}.prioritytable td,.prioritytable th{padding:3px;}</style>';
			var t = '<table class="prioritytable"><tr style="border-bottom:1px solid;text-align:left;font-weight:bold;"><th>Name</th><th>Price</th><th>Prerequisite</th><th>Season</th></tr>';
			for (var i in objList) {
				if (objList.hasOwnProperty(i)) {
                    var o = objList[i];
                    t += '<tr><td>' + o.name + '</td><td>' + aBeautify(o.cookies) + '</td><td>' + (typeof o.require !== 'undefined' ? o.require : '') + '</td><td>' + (typeof o.season !== 'undefined' ? o.season : '') + '</td></tr>';
                }
			}
			t += '</table>';
			return styles + '<div class="subsection">' + _logSectionTitle('Need to unlock') + '<div class="listing">' + t + '</div></div>';
		} else {
			return '';
		}
	};

	var _logNeedAchieveTable = function() {
		var ach = [];
		for (var i in Game.Achievements) {
			if(Game.Achievements[i].won === 0 && Game.Achievements[i].pool !== 'dungeon') {
				ach.push(Game.Achievements[i]);
			}
		}
		if (ach.length > 0) {
			var styles = '<style type="text/css">.prioritytable{width:100%;}.prioritytable td,.prioritytable th{padding:3px;}</style>';
			var t = '<table class="prioritytable"><tr style="border-bottom:1px solid;text-align:left;font-weight:bold;"><th>Name</th><th>Description</th></tr>';
			for (i in ach) {
				var o = ach[i];
				t += '<tr><td>' + o.name + '</td><td>' + o.desc + '</td></tr>';
			}
			t += '</table>';
			return styles + '<div class="subsection">' + _logSectionTitle('Achievements to unlock') + '<div class="listing">' + t + '</div></div>';
		} else {
			return '';
		}
	};

	var _optionsSection = function() {
		var content = [];
		content.push('<label for="bankStoragePercent" id="bankStoragePercentLabel">Storage (' + aBeautify(_getMinimalMoney()) + ') percent: ' + options.bankStoragePercent + '%</label> <input name="bankStoragePercent" id="bankStoragePercent" type="range" min="0" max="100" value="' + options.bankStoragePercent + '" onchange="Game.CCT.onsliderchange(this)" />');
		content.push('<button data-id="bankStorageAuto" onclick="Game.CCT.onbuttonclick(this,event)">Automatic set of bank storage percent: ' + (options.bankStorageAuto ? 'TRUE' : 'FALSE') + '</button>');
		content.push('<button data-id="buyInfernalUpgrades" onclick="Game.CCT.onbuttonclick(this,event)">Automatic buy infernal upgrades (makes granny evil): ' + (options.buyInfernalUpgrades ? 'TRUE' : 'FALSE') + '</button>');
		content.push('<button data-id="noClicking" onclick="Game.CCT.onbuttonclick(this,event)">Restrict auto clicking: ' + (options.noClicking ? 'TRUE' : 'FALSE') + '</button>');
		content.push('<button data-id="autoSeason" onclick="Game.CCT.onbuttonclick(this,event)">Auto season swithcer: ' + (options.autoSeason ? 'TRUE' : 'FALSE') + '</button>');
		content.push(clearLogButton);
		return content;
	};

	var _infoSection = function() {
		var content = [];

		var wrinklersTotal = 0;
		for (var i in Game.wrinklers) {
			wrinklersTotal += Game.wrinklers[i].sucked;
		}

		var chipsOwned = Math.floor(Game.HowMuchPrestige(Game.cookiesReset));
		var ascendNowToOwn = Math.floor(Game.HowMuchPrestige(Game.cookiesReset + Game.cookiesEarned));
		var ascendWillGet = ascendNowToOwn - chipsOwned;
		var cookiesToDoubleInitial = Game.HowManyCookiesReset(chipsOwned * 2) - (Game.cookiesEarned + Game.cookiesReset);
		var timeToReachDouble = Math.floor(cookiesToDoubleInitial / _getNormalCookiesPs());

		content.push('Now clicking: ' + (isClickingNow ? "YES" : "NO"));
		content.push('Cookies to double prestige: ' + aBeautify(cookiesToDoubleInitial));
		content.push('Time to double prestige: ' + Game.sayTime(timeToReachDouble * Game.fps, 2));
		content.push('Heavenly chips in storage: ' + Game.heavenlyChips);
		content.push('You will get prestige by ascending: ' + ascendWillGet);
		content.push('Heavenly chips after ascend: ' + (Game.heavenlyChips + ascendWillGet));
		content.push('Buff mult: ' + _getBuffMult());
		content.push('Normal CpS: ' + aBeautify(_getNormalCookiesPs()));
		content.push('Money bank: ' + aBeautify(_getMinimalMoney()));
		content.push('Money can spend: ' + aBeautify(_getMoneyCanSpend()));
		content.push('Wrinklers: ' + _getWrinklerCount());
		content.push('Wrinklers sucked: ' + aBeautify(wrinklersTotal));
		return content;
	};

	var _updateLog = function () {
		Game.updateLog = logTitle +
			_logPriorityTable() +
			_logSection('Info', _infoSection()) +
			_logSection('Log', log) +
			_logSection('Options', _optionsSection()) +
			_logNeedBuyTable() +
			_logNeedAchieveTable() +
			_logSection('History', _history());
		var newButtonText = newLogs > 0 ? 'Log (' + newLogs + ')' : 'Log';
		if ($logButton.text() !== newButtonText) $logButton.text(newButtonText);
		_title(oldTitle);
	};

	var _setBankStogarePercent = function(val, needUpdate) {
		if (options.bankStoragePercent !== val) {
			if (needUpdate === true) jQuery('#bankStoragePercent').val(val);
			if (console) console.log('bankStoragePercent =', val);
			_store('bankStoragePercent', val);
			options.bankStoragePercent = val;
			jQuery('#bankStoragePercentLabel').text('Storage (' + aBeautify(_getMinimalMoney()) + ') percent: ' + val + '%');
			_updateLog();
		}
	};

	var _bankAutoFunction = function() {
		if (options.bankStorageAuto && priorityList.length > 0 && Game.OnAscend === 0) {
			for (var idx in priorityListObj) {
                if (priorityListObj.hasOwnProperty(idx)) {
                    var bankStorageNew = Math.floor(idx / 50000);
                    if (bankStorageNew > 100) bankStorageNew = 100;
                    if (!isNaN(bankStorageNew)) _setBankStogarePercent(bankStorageNew, true);
                    else if (console) console.log('bankStorageNew error:', idx);
                    break;
                }
            }
		}
	};

	var _addLog = function(text, notCritical) {
		var t = new Date();
		log.push(t.toUTCString() + ': ' + text);
		if (notCritical !== true) newLogs++;
		_updateLog();
	};

	var _killAllWrinklers = function (immediately) {
		if (typeof immediately === 'undefined') immediately = false;
		var wrinklersCount = _getWrinklerCount();
		if (wrinklersCount >= 10 || immediately === true) {
			var wrinklesIncome = 0;
			for (var i in Game.wrinklers) {
				wrinklesIncome += Game.wrinklers[i].sucked;
				Game.wrinklers[i].hp = 0; // kill ALL
			}
			if (wrinklesIncome > 0) {
				_addLog('Killed all Wrinkles for ' + aBeautify(wrinklesIncome) + ' of count ' + wrinklersCount +'.', true);
			}
		}
	};

    var _buyEverything = function() {
        for (var x in Game.UpgradesById) {
            if (Game.UpgradesById.hasOwnProperty(x)) {
                if (parseInt(Game.UpgradesById[x].unlocked) === 1
					&& Game.UpgradesById[x].bought === 0 && Game.UpgradesById[x].canBuy()) {
                    var pool = Game.UpgradesById[x].pool;
                    if (pool !== "prestige" &&
                        pool !== 'debug' &&
                        pool !== 'toggle' &&
                        pool !== 'tech' &&
                        pool !== 'shadow' &&
                        pool !== 'unused' &&
                        pool !== 'dungeon')
                    {
                        Game.UpgradesById[x].buy();
                        _addLog('Buy upgrade ' + Game.UpgradesById[x].name + ' for ' + aBeautify(Game.UpgradesById[x].getPrice()));
                    }
                }
            }
        }
        for (x in Game.ObjectsById) {
            if (Game.ObjectsById.hasOwnProperty(x)) {
                var cnt = 0, sum = 0;
                while (Game.cookies >= Game.ObjectsById[x].getPrice()) {
                    sum += Game.ObjectsById[x].getPrice();
                    Game.ObjectsById[x].buy(1);
                    cnt++;
                }
                if (cnt > 0) _addLog('Buy ' + cnt + ' object ' + Game.ObjectsById[x].name + ' for ' + aBeautify(sum));
            }
        }
    };

	var _makeABuy = function() {

		_killAllWrinklers();

		var moneyCanSpend = _getMoneyCanSpend();

		if (moneyCanSpend < 0) {
			var minimalMoney = _getMinimalMoney();
			_caption('Collecting minimum ' + aBeautify(minimalMoney));
			_titlePercent(Game.cookies, minimalMoney, 'minimum');
			return;
		}

		var needToBuy = undefined, needToBuyInterest;
		if (priorityList.length > 0) {
			for (var idx in priorityListObj) {
				if (priorityListObj.hasOwnProperty(idx)) {
                    needToBuy = priorityListObj[idx];
                    needToBuyInterest = idx;
                    if (needToBuy.type === 'upgrade') {
                        _caption('Upgrading ' + needToBuy.name + ' for ' + aBeautify(needToBuy.price));
                        if (needToBuy.price < moneyCanSpend) {
                            if (Game.UpgradesById[needToBuy.id].canBuy()) {
                                Game.UpgradesById[needToBuy.id].buy();
                                _addLog('Buy upgrade ' + Game.UpgradesById[needToBuy.id].name + ' for ' + aBeautify(needToBuy.price));
                                _createPriorityList();
                            }
                        } else {
                            _titlePercent(moneyCanSpend, needToBuy.price, Game.UpgradesById[needToBuy.id].name);
                        }
                    } else {
                        _caption('Collecting ' + aBeautify(moneyCanSpend) + ' of '
							+ aBeautify(needToBuy.price) + ' for ' + needToBuy.name);
                        if (Game.ObjectsById[needToBuy.id].price < moneyCanSpend) {
                            var amount = 1;
                            if (Game.ObjectsById[needToBuy.id].getSumPrice(100) < moneyCanSpend) {
                                Game.ObjectsById[needToBuy.id].buy(100);
                                amount = 100;
                            } else if (Game.ObjectsById[needToBuy.id].getSumPrice(10) < moneyCanSpend) {
                                Game.ObjectsById[needToBuy.id].buy(10);
                                amount = 10;
                            } else {
                                Game.ObjectsById[needToBuy.id].buy(1);
                            }
                            _addLog('Buy ' + amount + ' object ' + Game.ObjectsById[needToBuy.id].name + ' for ' + aBeautify(Game.ObjectsById[needToBuy.id].price));
                            _createPriorityList();
                        } else {
                            _titlePercent(moneyCanSpend, needToBuy.price, Game.ObjectsById[needToBuy.id].name);
                        }
                    }
                    break;
                }
			}
		}
	};

	var startT = function() {
		t2 = setInterval(_makeABuy, 500);

		started = true;
		_caption('Started');
		_addLog('Autobuy start!', true);
	};

	var stopT = function() {
		clearInterval(t2);
		started = false;
		_caption('Collecting gold...');
		_addLog('Autobuy stop.', true);
	};

	jQuery('#versionNumber').on("click", function() {
		if (!started)
			startT();
		else
			stopT();
	});

    var _restoreAll = function() {
    	options.bankStoragePercent = parseInt(_restore('bankStoragePercent'));
    	if (typeof options.bankStoragePercent === 'undefined' || options.bankStoragePercent === null) {
    		options.bankStoragePercent = 100;
    	}
    	options.bankStorageAuto = _restore('bankStorageAuto', true);
    	if (typeof options.bankStorageAuto === 'undefined' || options.bankStorageAuto === null) {
    		options.bankStorageAuto = false;
    	}
    
    	options.buyInfernalUpgrades = _restore('buyInfernalUpgrades', true);
    	if (typeof options.buyInfernalUpgrades === 'undefined' || options.buyInfernalUpgrades === null) {
    		options.buyInfernalUpgrades = false;
    	}
    
    	options.noClicking = _restore('noClicking', true);
    	if (typeof options.noClicking === 'undefined' || options.noClicking === null) {
    		options.noClicking = false;
    	}
    
    	options.autoSeason = _restore('autoSeason', true);
    	if (typeof options.autoSeason === 'undefined' || options.autoSeason === null) {
    		options.autoSeason = false;
    	}
    };

    var _seasonSwitcher = function() {
        if (!options.autoSeason) return;
        
	    if (_getWrinklerCount() >= 8) {
    		var halloweenSeason = ['Skull cookies','Ghost cookies','Bat cookies','Slime cookies','Pumpkin cookies','Eyeball cookies','Spider cookies'];
    		for (var x in halloweenSeason) {
    			if (halloweenSeason.hasOwnProperty(x) && Game.Upgrades[halloweenSeason[x]].bought === 0) {
                    if (Game.season !== 'halloween') {
    			        Game.Upgrades['Ghostly biscuit'].buy();
    			        _killAllWrinklers(true);
        			    return;   
    			    }
			    }
			}
		}
		
		if (Game.Has('A crumbly egg') && Game.dragonLevel<Game.dragonLevels.length-1 && Game.dragonLevels[Game.dragonLevel].cost()) {
		    Game.UpgradeDragon();
            Game.specialTab = 'Hello';
            Game.ToggleSpecialMenu(0);
		}
		
		if (Game.dragonLevel >= 12 && parseInt(Game.dragonAura) !== 9) {
	        Game.dragonAura = 9; //"Arcane Aura"
	        Game.recalculateGains = 1;
		} else if (Game.dragonLevel >= 21 && parseInt(Game.dragonAura2) !== 15) {
	        Game.dragonAura2 = 15; //"Radiant Appetite"
	        Game.recalculateGains = 1;
		}

		if (!Game.Has('Santa\'s dominion')) {
    	    if (Game.season !== 'christmas') {
    	        Game.Upgrades['Festive biscuit'].buy();
    	    } else {
    	        if (Game.Has('A festive hat')) {
    	            for (var i = 0; i < (14 - Game.santaLevel); i++) Game.UpgradeSanta();
    	            Game.specialTab = 'Hello';
    	            Game.ToggleSpecialMenu(0);
    	        }
    	    }
    	    return;
		}
		
        var valentines = ['Pure heart biscuits','Ardent heart biscuits','Sour heart biscuits','Weeping heart biscuits','Golden heart biscuits','Eternal heart biscuits'];
		for (x in valentines) {
			if (valentines.hasOwnProperty(x) && Game.Upgrades[valentines[x]].bought === 0) {
			    if (Game.season !== 'valentines') {
			        Game.Upgrades['Lovesick biscuit'].buy();
			    }
			    return;
			}
		}

		for (x in Game.easterEggs) {
			if (Game.easterEggs.hasOwnProperty(x) && Game.Upgrades[Game.easterEggs[x]].bought === 0) {
			    if (Game.season !== 'easter') {
			        Game.Upgrades['Bunny biscuit'].buy();
			    }
			    return;
			}
		}

	    if (Game.season !== 'christmas') {
	        Game.Upgrades['Festive biscuit'].buy();
	    }
    };

    _restoreAll();

    var _initLogButton = function() {
        $logButton = jQuery('#logButton');

        $logButton.text('Log').on("click", function() {
            newLogs = 0;
            $logButton.text('Log');
        });

        Game.CCT = {}; // Coockie clicker tools
        Game.CCT.onsliderchange = function(el) {
            var val = $(el).val();
            _setBankStogarePercent(val);
        };

        Game.CCT.onbuttonclick = function(el,e) {
            e.preventDefault();
            var id = jQuery(el).attr('data-id');
            if (id === 'bankStorageAuto') {
                options.bankStorageAuto = !options.bankStorageAuto;
                _store('bankStorageAuto', options.bankStorageAuto);
                if (console) console.log('bankStorageAuto =', options.bankStorageAuto ? 'TRUE' : 'FALSE');
                _bankAutoFunction();
            } else if (id === 'killWrinklers') {
                _killAllWrinklers(true);
            } else if (id === 'buyEverything') {
                _buyEverything();
            } else if (id === 'buyInfernalUpgrades') {
                options.buyInfernalUpgrades = !options.buyInfernalUpgrades;
                _store('buyInfernalUpgrades', options.buyInfernalUpgrades);
                if (console) console.log('buyInfernalUpgrades =', options.buyInfernalUpgrades ? 'TRUE' : 'FALSE');
            } else if (id === 'noClicking') {
                options.noClicking = !options.noClicking;
                _store('noClicking', options.noClicking);
                if (console) console.log('noClicking =', options.noClicking ? 'TRUE' : 'FALSE');
            } else if (id === 'autoSeason') {
                options.autoSeason = !options.autoSeason;
                _store('autoSeason', options.autoSeason);
                if (console) console.log('autoSeason =', options.autoSeason ? 'TRUE' : 'FALSE');
            } else if (id === 'clearLog') {
                log = [];
                newLogs = 0;
            }
            //jQuery(el).attr('disabled', 'disabled');
            _updateLog();
        };
	};

	setTimeout(function() {
		_initLogButton();

		jQuery('#donateBox').hide();

        tSeasonSwitcher = setInterval(_seasonSwitcher, 3000);

		tPriority = setInterval(function () {
			_createPriorityList();
			_updateLog();
		}, 1000);

		tLog = setInterval(function () {
			_updateLog();
		}, 600);

		tReloadPageOnWrongBuff = setInterval(function() {
			if (_getBuffMult() < 1) {
				var hasBuffsToKill = false;
				for (var buff in Game.buffs) {
					if (Game.buffs[buff] !== 0 && typeof Game.buffs[buff].multCpS !== 'undefined') {
						Game.buffs[buff].time = 0; // remove all buffs, not only negative (not cheating)
						hasBuffsToKill = true;
					}
				}
				if (hasBuffsToKill) _addLog('Remove all buffs because of negative multiplier', true);
			}
		}, 1000);

		tAscendDetector = setInterval(function() {
			if (parseInt(Game.OnAscend) === 1) {
				_setBankStogarePercent(0, true);
			}
		}, 1000);

		t3 = setInterval(function() {
			var golden = Game.shimmers;
			if (golden && golden.length > 0) {
				for (var i in golden) {
					if (golden.hasOwnProperty(i)) {
                        golden[i].pop();
                    }
				}
			}
		}, 500);

		tBankAuto = setInterval(_bankAutoFunction, 600001); // 10 minutes

		tClickFrenzy = setInterval(function() {
			if (options.noClicking) return;
			var date=new Date();
			date.setTime(Date.now()-Game.startDate);
			var seconds = date.getTime() / 1000;
			var buffMult = _getBuffMult();
			var buffClicker = typeof Game.hasBuff !== 'undefined' && (
			    Game.hasBuff('Click frenzy') ||
				Game.hasBuff('Cursed finger') ||
				Game.hasBuff('Elder frenzy') ||
				Game.hasBuff('Dragon Harvest') ||
				Game.hasBuff('Dragonflight')
			    );
			if (buffMult >= 15 ||
				Game.cookiesPs < 1000000 ||
				buffClicker ||
				seconds < 1000)
			{
				var $bigCookie = jQuery('#bigCookie');
				Game.mouseX = $bigCookie.width() / 2 + $bigCookie.offset().left;
				Game.mouseY = $bigCookie.height() / 2 + $bigCookie.offset().top;
				if (typeof Game.ClickCookie === 'function') Game.ClickCookie();
				isClickingNow = true;
			} else {
				isClickingNow = false;
			}
		}, tAutoClickInterval);

		_caption('Collecting gold...');
		_createPriorityList();
		_updateLog();

		_bankAutoFunction();
	}, 5000);
})();