// ==UserScript== // @name PS Facebook Mafia Wars Autoplayer (MWAP) // @namespace mafiawars // @description Autoplayer for the facebook application - Mafia Wars // @include /^https?://(facebook\.mafiawars|mwfb)(\.zynga)?\.com/mwfb/remote/html_server\.php.*?/ // @include /^https?://(facebook\.mafiawars|mwfb)(\.zynga)?\.com/\?skip_req_frame=1&mwcom=1.*?/ // @include /^https?://apps(\.new)?\.facebook\.com/inthemafia/.*?/ // @include /^https?://www.facebook.com/(connect/uiserver|dialog/(feed|apprequests)).*?/ // @exclude /^https?://(facebook.mafiawars|mwfb)(\.zynga)?\.com/.*?(sk_updater\.php|\#|iframe_proxy\.php).*?/ // @version 2.0.44 // ==/UserScript== // to have the job array update, set to same as current version releasing. // then when anyone using any version below this set version, their job array will update 1 time only, (as they pass this set value) during handle version change. // job array automatically updates if length changes ! var updtJobArrayIfWasBelow=42; var SCRIPT = { version: '2.0.44', name: 'inthemafia', appID: 'app10979261223', appNo: '10979261223', presentationurl: 'http://www.playerscripts.co.uk', url: 'http://cdn.playerscripts.co.uk/rokdownloads/ps_facebook_mafia_wars_a.user.js', metadata: 'http://cdn.playerscripts.co.uk/rokdownloads/mwapmeta.js', controller: 'remote/html_server.php?xw_controller=', action: '&xw_action=', city: '&xw_city=', opponent: '&opponent_id=', user: '&user_id=', /*
pages for parsing with logJSONResponse(), added as final_wrapper sibling; we use two pages to prevent interference */ ajaxIDSync: 'ajax_sync', // page for Autoplay ('synchronous') ajaxIDAsync: 'ajax_async', // page for asynchronous clicking (quickbanking, profile icecheck etc) UseDebugConsole : false, UseDebugCategory : 0, PSMWAP_homePath: 'http://www.playerscripts.co.uk/', PSMWAP_imagePath: 'http://cdn.playerscripts.co.uk/images/mwap_graphics/setlog/mwap_int_web_', PSMWAP_iconPath: 'http://cdn.playerscripts.co.uk/images/mwap_graphics/icons/', PSMWAP_imageBPath: 'http://cdn.playerscripts.co.uk/images/banners/' }; // Set the storage path var GMSTORAGE_PATH = 'GM_'+ SCRIPT.appID+'_'; if(/facebook\.com/.test(window.location.href)){ var profElt = xpathFirst('//ul[@id="pageNav"]//a[@accesskey="6"]'); if(profElt && profElt.getAttribute('href').match(/id=(\w+)/)){ GMSTORAGE_PATH = GMSTORAGE_PATH + RegExp.$1; } var profLink = xpathFirst('//div[contains(@id,"div_story_") and contains(@data-ft,"actrs")]'); if(profLink && profLink.getAttribute('data-ft').match(/"actrs":"(\w+)/)){ GMSTORAGE_PATH = GMSTORAGE_PATH + RegExp.$1; } } if(/mwfb\.zynga\.com/.test(window.location.href)){ var docUrl = document.location.href; if(docUrl.match(/sf_xw_user_id=(\w+)/)){ GMSTORAGE_PATH = GMSTORAGE_PATH + RegExp.$1; } } var gvar=function(){}; function GM_ApiBrowserCheck(){ var needApiUpgrade=false; if(typeof(unsafeWindow)=='undefined'){ var div = document.createElement("div"); div.setAttribute("onclick", "return window;"); unsafeWindow = div.onclick(); } if(typeof(GM_log)=='undefined'){ GM_log=function(msg){ try { unsafeWindow.console.log('GM_log: '+msg); } catch(err){} }; } if(typeof(GM_setValue)!='undefined'){ try { var gsv=GM_setValue.toString(); if(gsv.indexOf('staticArgs')>0){gvar.isGreaseMonkey=true;GM_log('GreaseMonkey Api detected...'); } else if(/not\s+supported/.test(gsv)){ needApiUpgrade=true; isBuggedChrome=true; GM_log('Bugged Chrome GM Api detected...'); } } catch(err){ gvar.isGreaseMonkey=true; needApiUpgrade = false; GM_log('GreaseMonkey Api detected...'); } } else { needApiUpgrade=true; GM_log('No GM Api detected...'); } if(needApiUpgrade){ GM_log('Try to recreate needed GM Api...'); GM_log('Using ['+ GMSTORAGE_PATH +'] as storage path.'); var ws=null; try { ws=typeof(unsafeWindow.localStorage); unsafeWindow.localStorage.length; } catch(err){ ws=null; } // Catch Security error if(ws=='object'){ GM_log('Using localStorage for GM Api.'); GM_getValue=function(name,defValue){ var value=unsafeWindow.localStorage.getItem(GMSTORAGE_PATH+name); if(value==null){ if(defValue==null){ return 'undefined'; } else { return defValue; } } else { switch(value.substr(0,2)){ case 'S]': return value.substr(2); case 'N]': return parseInt(value.substr(2)); case 'B]': return value.substr(2)=='true'; } } return value; }; GM_setValue=function(name,value){ switch (typeof(value)){ case 'string': unsafeWindow.localStorage.setItem(GMSTORAGE_PATH+name,'S]'+value); break; case 'number': if(value.toString().indexOf('.')<0){ unsafeWindow.localStorage.setItem(GMSTORAGE_PATH+name,'N]'+value); } break; case 'boolean': unsafeWindow.localStorage.setItem(GMSTORAGE_PATH+name,'B]'+value); break; } }; GM_deleteValue=function(name){ unsafeWindow.localStorage.removeItem(GMSTORAGE_PATH+name); }; } else if(!gvar.isOpera || typeof(GM_setValue)=='undefined'){ GM_log('Using temporarilyStorage for GM Api.'); gvar.temporarilyStorage=new Array(); GM_getValue=function(name,defValue){ if(typeof(gvar.temporarilyStorage[GMSTORAGE_PATH+name])=='undefined'){ return defValue; } else { return gvar.temporarilyStorage[GMSTORAGE_PATH+name]; } }; GM_setValue=function(name,value){ switch (typeof(value)){ case "string": case "boolean": case "number": gvar.temporarilyStorage[GMSTORAGE_PATH+name]=value; } }; GM_deleteValue=function(name){ delete gvar.temporarilyStorage[GMSTORAGE_PATH+name]; }; } if(typeof(GM_openInTab)=='undefined'){ GM_openInTab=function(url){ unsafeWindow.open(url,""); }; } if((typeof(GM_registerMenuCommand)=='undefined') || gvar.isBuggedChrome){ GM_registerMenuCommand=function(name,cmd){ GM_log("Notice: GM_registerMenuCommand is not supported."); }; } // Dummy if(!gvar.isOpera || typeof(GM_xmlhttpRequest)=='undefined'){ GM_log('Using XMLHttpRequest for GM Api.'); GM_xmlhttpRequest=function(obj){ var request=new XMLHttpRequest(); request.onreadystatechange=function(){ if(obj.onreadystatechange){ obj.onreadystatechange(request); } if(request.readyState==4 && obj.onload){ obj.onload(request); } }; request.onerror=function(){ if(obj.onerror){ obj.onerror(request); } }; try { request.open(obj.method,obj.url,true); } catch(err){ if(obj.onerror){ obj.onerror( {readyState:4,responseHeaders:'',responseText:'',responseXML:'',status:403,statusText:'Forbidden'} ); }; return; } if(obj.headers){ for(name in obj.headers){ request.setRequestHeader(name,obj.headers[name]); } } request.send(obj.data); return request; }; } } } GM_ApiBrowserCheck(); if(gvar.isGreaseMonkey) var $ = unsafeWindow.jQuery; function receiver(e){ //{"source":"mwap.me.uk","version":"1240","allowAll":"true","key":"mwapProKey"} var messageSource = e.origin; var messageContent = e.data; //for testing purposes only //messageContent = "myStringisnotbase64"; if(messageSource == 'http://mwap.me.uk'){ GM_setValue('checkMWAPString', messageContent); var dataString = decode64(messageContent); if(IsJsonString(dataString)){ var dataCollector = JSON.parse(dataString); var strMWAPSource = dataCollector.source; var strMWAPVersion = dataCollector.version; var strMWAPPermissions = dataCollector.allowAll; var strMWAPKey = dataCollector.key; if(strMWAPKey == 'mwapProKey' && messageSource.indexOf(strMWAPSource) !=-1){ //colorDEBUG('valid eData: '+dataString+' from '+messageSource); GM_setValue('checkMWAP', strMWAPKey); GM_setValue('checkMWAPPermissions', (strMWAPPermissions=="true"?1:0)); GM_setValue('checkMWAPVersion', strMWAPVersion); GM_setValue('checkMWAPOK', 1); GM_setValue('checkMWAPSum', parseInt(strMWAPVersion)); } } else { GM_setValue('checkMWAPString', 'invalidmessage'); //colorDEBUG('invalid eData: '+dataString+' from '+messageSource, cre); GM_setValue('checkMWAP', 'rubbish'); GM_setValue('checkMWAPPermissions', 0); GM_setValue('checkMWAPVersion', 'rubbish'); GM_setValue('checkMWAPOK', 0); GM_setValue('checkMWAPSum', 9999-parseInt(strMWAPVersion)); } } } function mwapValidation(){ //for testing purposes : return 0 -> returns always invalid // return 0; // if(IsJsonString(decode64(GM_getValue('checkMWAPString', '')))){ var checkMWAP = JSON.parse(decode64(GM_getValue('checkMWAPString', ''))); //colorDEBUG(JSON.stringify(checkMWAP)); var strMWAPKey = GM_getValue('checkMWAP', ''); var strMWAPPermissions = GM_getValue('checkMWAPPermissions', 0); var strMWAPVersion = GM_getValue('checkMWAPVersion', ''); var checkMWAPOK = GM_getValue('checkMWAPOK', 0); //colorDEBUG('mwapValidation: '+checkMWAP.key+'-'+strMWAPKey+' / '+ (checkMWAP.allowAll=="true"?1:0)+'-'+strMWAPPermissions+' / '+ checkMWAPOK); if(checkMWAP.key==strMWAPKey && (checkMWAP.allowAll=="true"?1:0)==strMWAPPermissions && strMWAPPermissions && checkMWAPOK){ //colorDEBUG('mwapValidation check: OK', cli); return parseInt(strMWAPVersion); } } //colorDEBUG('mwapValidation check: NOK', cre); return 0; } window.addEventListener('message', receiver, false); function postSize(e){ if(!gvar.isGreaseMonkey) return; try{ var target = parent.postMessage ? parent : (parent.document.postMessage ? parent.document : undefined); if(typeof target != "undefined" && document.getElementById("mainDiv")) { var divSize = parseInt(document.getElementById("mainDiv").offsetHeight)+200; target.postMessage(divSize, "*"); //change this star to your domain for more security } } catch (postError){ alert('Yeah, we already know by now you hate chrome !'); } } function track_Analytics(){ var newScript = 'try { var pageTracker = _gat._getTracker("UA-3078135-23"); pageTracker._trackPageview(); } catch(err){ }'; makeElement('script', document.getElementsByTagName('head')[0], {'type':'text/javascript'}).appendChild(document.createTextNode(newScript)); } function build_Analytics(){ function GM_wait(){ if(typeof unsafeWindow._gat == 'undefined'){ window.setTimeout(GM_wait,350); } else { track_Analytics(); } } if(!document.getElementById('mwapAnalytics')){ var gaJsHost = (('https:' == document.location.protocol) ? 'https://ssl.' : 'http://www.'); var newScript = gaJsHost+'google-analytics.com/ga.js'; var extElt = makeElement('script', document.getElementsByTagName('head')[0], {'id':'mwapAnalytics', 'type':'text/javascript'}); extElt.src = newScript; extElt.id = 'mwapAnalytics'; GM_wait(); } } build_Analytics(); // Handle Publishing (check for FB publishing) function checkInPublishPopup(){ if(xpathFirst('//div[contains(@class,"aid_'+ SCRIPT.appNo +'")]') && (/connect\/uiserver/.test(window.location.href) || /dialog\/apprequests/.test(window.location.href) || /dialog\/feed/.test(window.location.href)) ){ setGMTime('postTimer', '00:00:06'); window.setTimeout(handlePublishing, 2500); return true; } return false; } function fetchPubOptions(){ copyMWValues(['isRunning','autoGlobalPublishing','autoIcePublish']); } // Handle Free Gift Requests (check for Free Gift Page) function checkInRequestsPopup(){ if(xpathFirst('//div[@id="mfs_container"]')) { setGMTime('requestTimer', '00:15'); window.setTimeout(handleRequests, 2500); return true; } return false; } function checkLoadIframe(){ if(/apps.facebook.com.inthemafia$/.test(document.URL)){ window.location.href = 'http://facebook.mafiawars.com/mwfb/index.php?skip_req_frame=1&mwcom=1'; } else if(/apps.facebook.com.inthemafia/.test(document.URL)){ for(var i=0;i 1){ addToLog('info Icon', this.icon+' '+ this.name+' is set to keep above '+ this.floor+'.'); } } // Log any change to the ceiling. if(this.ceiling != GM_getValue(this.lastCeiling)){ GM_setValue(this.lastCeiling, this.ceiling); if(this.ceiling > this.floor){ addToLog('info Icon', this.icon+' '+ this.name+' refill level set to '+ this.ceiling+'.'); } } // Determine whether spending needs to start or stop. if(curVal >= this.ceiling && !GM_getValue(this.startFlag)){ GM_setValue(this.startFlag, true); } else if(curVal <= this.floor && this.ceiling > this.floor && GM_getValue(this.startFlag)){ GM_setValue(this.startFlag, false); addToLog('info Icon', this.icon+' Refilling '+ this.name+' to '+ this.ceiling+'.'); } }; // // Define Player object and methods. // // Determine whether two player objects refer to the same player. Player.prototype.match = function(player){ if(!player) return false; if(this.id && player.id) return (this.id == player.id); if(this.profile && this.profile == player.profile) return true; if(this.profileAttack && this.profileAttack == player.profileAttack) return true; if(this.attack && this.attack == player.attack) return true; return false; }; // Update this player object's properties with the properties of another. Player.prototype.update = function(player){ if(!this.match(player)) return false; for (var prop in player){ this[prop] = player[prop]; } return true; }; // Constructor for Player objects. function Player(name){ } // Get this player list's array of player objects. PlayerList.prototype.get = function(forceRefresh){ if(this.name && (forceRefresh || !this.list.length)){ // Load the list from storage. var ids = getSavedList(this.name); // Convert the ID list (strings) into a player list (objects). this.list = []; for (var i = 0, l=ids.length; i < l; ++i){ var p = new Player(); p.id = ids[i]; this.list.push(p); } } return this.list; }; PlayerList.prototype.set = function(list){ if(list){ this.list = list; } if(this.name){ // Build an array of player ID's. var a = []; for (var i = 0, l=this.list.length; i < l; ++i){ var player = this.list[i]; if(player && player.id){ a.push(player.id); } } // Store the list. setSavedList(this.name, a); } }; PlayerList.prototype.add = function(player, max){ if(!player) return false; // If the player is already in the list, just update it. var l = this.list.length; for (var i = 0; i < l; ++i){ if(this.list[i].update(player)){ return false; } } // No match. Just push it into the array. this.list.push(player); // Shorten the array if it has become too large. if(max > 0){ while (max < this.list.length){ var playerItem = this.list.shift(); } } return true; }; PlayerList.prototype.remove = function(player){ if(!player) return false; // If the player is in the list, remove it. var l = this.list.length; for (var i = 0; i < l; ++i){ if(this.list[i].match(player)){ this.list.splice(i, 1); return true; } } // No match. return false; }; PlayerList.prototype.indexOf = function(player){ var l = this.list.length; for (var i = 0; i < l; i++){ if(this.list[i].match(player)) return i; } return -1; }; PlayerList.prototype.debug = function(){ var l = this.list.length; var str = 'PlayerList name='+ this.name+', length='+ l+'\n'; for (var i = 0; i < l; ++i){ var p = this.list[i]; str += i+': '; if(p.name) str += ', name='+ p.name; if(p.level) str += ', level='+ p.level; if(p.mafia) str += ', mafia='+ p.mafia; str += '\n'; } return str; }; // Constructor for PlayerList objects. function PlayerList(name){ this.name = name; this.list = []; this.get(); } var lootbagIcon = ''; var attackIcon = ''; var defenseIcon = ''; var omgIcon = ''; var staminaIcon = ''; var energyIcon = ''; var yeahIcon = ''; var plussignIcon = ''; var cashIcon = ''; var cashCubaIcon = ''; var cashMoscowIcon = ''; var cashBangkokIcon = ''; var cashVegasIcon = ''; var cashItalyIcon = ''; var cashBrazilIcon = ''; var mini_Epak_ready = ''; var mini_Epak_wait = ''; var healthIcon = ''; var healOnIcon = ''; var healOnHoldIcon = ''; var healOffIcon = ''; var warningIcon = ''; var debugIcon = ''; var chickenIcon = ''; var hideIcon = ''; var checkedIcon = ''; var unCheckedIcon = ''; var winW = 630, winH = 460; var bgTabImage = ''; var noDelay = 0; // No delay on commands var minDelay = 1000; // Minimum delay on commands var running; // Is the autoplayer running? var innerPageElt; // The currently visible inner page var questBarElt; // The currently visible quest page var appLayoutElt; // The currently visible content page var mastheadElt; // Masthead content var statsrowElt; // statsrow content var menubarElt; // menubar content var popupfodderElt; // popupfodder Element var cashElt; // Cash array of values by city var healthElt, health; // Health DOM element and value var maxHealthElt, maxHealth; // Maximum health DOM element and value var energyElt, energy; // Energy DOM element and value var maxEnergyElt, maxEnergy; // Maximum energy DOM element and value var staminaElt, stamina; // Stamina DOM element and value var maxStaminaElt, maxStamina; // Maximum stamina DOM element and value var levelElt, level; // Level DOM element and value var curAttack; // Current Attack stat value var curDefense; // Current Defense stat value var curAttackEquip; // Current Attack equip value var curDefenseEquip; // Current Defense equip value var prevAttackEquip; // Previous Attack equip value var prevDefenseEquip; // Previous Defense equip value var curExpElt, curExp; // Experience DOM element and value var lvlExpElt, lvlExp; // Level up experience DOM element and value var energyPackElt, energyPack; // Is an energy pack waiting? var ptsToNextLevel; // Experience to next level up var mafia; // Mafia size var stats; // Skill points var city; // Current city (0=New York, 1=Cuba, 2=Moscow) var skipStaminaSpend = false; // Skip stamina actions for now? var Miss_Name; // mission Name holder var Miss_Name_is; var Miss_ID; // a holder to move the mission tag around var Miss_Slot; // a holder to move around the mission slot 0-3 var MyMafiaJobs; // name to use in misssions var Miss_Energy; var Miss_Nrg_Req = 0; var Miss_Stamina; var Miss_Stam_Req = 0; var Miss_Pay_Exp; var Miss_Pay_Cash; var missionsDelays = 2500; var clickAction; // Action being attempted with click simulation var clickContext; // Context for clickAction var modificationTimer; // Timer used to wait for content changes var ajaxAction; // Action being attempted with do_ajax (asynchronous) var ajaxContext; // Context for ajaxContext var ajaxHandling = false; var popupTimer; // setInterval timer for handlePopups() var helpWar = false; // Helping a friend's war? var idle = true; // Is the script currently idle? var lastOpponent; // Last opponent fought (object) var suspendBank = false; // Suspend banking for a while var skipJobs = false; // Skip doing jobs for a while var jobOptimizeOn = false; // Is job optimizing flag var newStaminaMode; // New stamina mode for random fighting var jobid; var mmis_time = '00:00:30'; var endBoss; var xw_sig; var xw_user; var xw_user_id; var cbr = '#FF800D'; // Brown var cye = '#FFD700'; // Yellow Gold var cy = '#FFFF00'; // Yellow var cfu = '#FF00FF'; // Fuchsia var cre = '#FF0000'; // Red var csi = '#C0C0C0'; // Silver var cds = '#808080'; // Dark Silver - Gray var cov = '#808000'; // Olive var cpu = '#800080'; // Purple var cma = '#800000'; // Maroon var caq = '#00FFFF'; // Aqua var cli = '#00FF00'; // Lime var cte = '#008080'; // Teal var cgr = '#008000'; // Green var cbl = '#6495ED'; // Blue var can = '#000080'; // Navy var cbk = '#000000'; // Black var cwt = '#FFFFFF'; // White var color; var line; var new_header = xpathFirst('//div[@class="header_top_row"]') ? true : false; // checks for new header var currentBrazilDistrict = 0; var oldBrazilDistrict = 0 ; var previousBrazilJob = null; var previousBrazilJobMastery = null; var boardLastStamina = 0; var boardLastPtsToNextLevel = 0; var claimLevelUpBonus = true; var inClanBattle = false; var inSafehouse = false; var slotSpins = 0; // Number of remaining slot spins.. var slotBonus = 0; // Bonus level for slots.. var isBossRunning = false; var current_boss_id = 0; //Current BossID for family Boss Fights var current_boss_index = 0; var current_boss_name = ''; var clicks = 1; var isProfileSearching = false; var profileCount=0; var searchTimer; if(!initialized && !checkInPublishPopup() && !checkInRequestsPopup() && !checkLoadIframe() && ( (/inthemafia/.test(document.referrer) || /facebook\.mafiawars\.com/.test(window.location.href) || /facebook\.mafiawars\.zynga\.com/.test(window.location.href)) || (/m\.mafiawars\.com/.test(document.referrer) || /iframe/.test(window.location.href) ) ) ){ setFBParams(); var settingsOpen = false; var statsOpen = false; var scratchpad = document.createElement('textarea'); var defaultClans = ['{', '[', '(', '<', '\u25C4', '?', '\u2122', '\u03A8', '\u039E']; var defaultPassPatterns = ['LOST', 'punched', 'Whacked', 'you were robbed', 'ticket']; var defaultFailPatterns = ['WON','heal','help','properties','upgraded']; var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; var debug = isGMChecked('enableDebug'); var filter = isGMChecked('filterLog'); // Regular expression for cash matching. var REGEX_CASH = /([A-Z]*?\$|\u00A2)([\d,]*\d)/; // Define how stamina can be used. var STAMINA_HOW_FIGHT_RANDOM = 0; // Random fighting. var STAMINA_HOW_FIGHT_LIST = 1; // List fighting. var STAMINA_HOW_HITMAN = 2; // Hitman. var STAMINA_HOW_ROBBING = 3; // Robbing var STAMINA_HOW_AUTOHITLIST = 4; // Place bounties. var STAMINA_HOW_RANDOM = 5; // Random spending of stamina in random cities. var STAMINA_HOW_FIGHTROB = 6; // Fight then Rob random opponents. var STAMINA_HOW_ROBFIGHT = 7; // Rob then fight, switch to fighting when falls below robFightStaminaFloor. // var STAMINA_HOW_LVJOBFIGHT = 8; // do lv job Fights. var STAMINA_HOW_BATTLE = 99; var staminaSpendChoices = []; staminaSpendChoices[STAMINA_HOW_FIGHT_RANDOM] = 'Fight random opponents'; staminaSpendChoices[STAMINA_HOW_FIGHT_LIST] = 'Fight specific opponents'; staminaSpendChoices[STAMINA_HOW_HITMAN] = 'Collect hitlist bounties'; staminaSpendChoices[STAMINA_HOW_ROBBING] = 'Rob random opponents'; staminaSpendChoices[STAMINA_HOW_AUTOHITLIST] = 'Place hitlist bounties'; staminaSpendChoices[STAMINA_HOW_RANDOM] = 'Spend stamina randomly'; staminaSpendChoices[STAMINA_HOW_FIGHTROB] = 'Fight then Rob'; staminaSpendChoices[STAMINA_HOW_ROBFIGHT] = 'Rob then Fight'; // staminaSpendChoices[STAMINA_HOW_LVJOBFIGHT] = 'Do LV Job Fights'; var randomSpendChoices = []; randomSpendChoices[STAMINA_HOW_FIGHT_RANDOM] = 'Fight random'; randomSpendChoices[STAMINA_HOW_FIGHT_LIST] = 'Fight specific'; randomSpendChoices[STAMINA_HOW_HITMAN] = 'Collect bounties'; randomSpendChoices[STAMINA_HOW_ROBBING] = 'Rob random'; // Rivals Lists var fightRivalsModes = ['Random Opponents','Mafia You Attacked','Your Attackers','Your Rivals','Family Rivals']; // Define Bounty Selection options var BOUNTY_SHORTEST_TIME = 0; // Select qualified bounties with shortest time. var BOUNTY_LONGEST_TIME = 1; // Select qualified bounties with longest time on the hitlist. var BOUNTY_HIGHEST_BOUNTY = 2; // Select qualified bounties with the highest bounty. var BOUNTY_EXACT_AMOUNT = 3; // Select qualified bounties with exact dollar amount. var BOUNTY_RANDOM = 4; // Select random qualified bounty. var bountySelectionChoices = []; bountySelectionChoices[BOUNTY_SHORTEST_TIME] = 'Shortest time'; bountySelectionChoices[BOUNTY_LONGEST_TIME] = 'Longest time'; bountySelectionChoices[BOUNTY_HIGHEST_BOUNTY] = 'Highest bounty'; bountySelectionChoices[BOUNTY_EXACT_AMOUNT] = 'Exact dollar amount'; bountySelectionChoices[BOUNTY_RANDOM] = 'No preference (random)'; // Define war modes var WAR_HOW_RANDOM = 0; // Random war. var WAR_HOW_LIST = 1; // List warring var warModeChoices = ['War a random Enemy', 'War Enemies from a list']; // Define AutoStat allocation mode var AUTOSTAT_TARGET = 0; var AUTOSTAT_RATIO_LEVEL = 1; var AUTOSTAT_RATIO_ATTACK = 2; var AUTOSTAT_RATIO_DEFENSE = 3; var AUTOSTAT_RATIO_HEALTH = 4; var AUTOSTAT_RATIO_ENERGY = 5; var AUTOSTAT_RATIO_STAMINA = 6; // Auto Stat mode arrays var autoStatDescrips = ['Level', 'Attack', 'Defense', 'Health', 'Energy', 'Stamina']; var autoStatModes = ['autoStatAttackMode', 'autoStatDefenseMode', 'autoStatHealthMode', 'autoStatEnergyMode', 'autoStatStaminaMode']; var autoStatPrios = ['autoStatAttackPrio', 'autoStatDefensePrio', 'autoStatHealthPrio', 'autoStatEnergyPrio', 'autoStatStaminaPrio']; var autoStatFallbacks = ['autoStatAttackFallback', 'autoStatDefenseFallback', 'autoStatHealthFallback', 'autoStatEnergyFallback', 'autoStatStaminaFallback']; var autoStatBases = ['autoStatAttackBase', 'autoStatDefenseBase', 'autoStatHealthBase', 'autoStatEnergyBase', 'autoStatStaminaBase']; var autoStatRatios = ['autoStatAttackRatio', 'autoStatDefenseRatio', 'autoStatHealthRatio', 'autoStatEnergyRatio', 'autoStatStaminaRatio']; // Number Scheme var SCHEME_PERCENT = 0; var SCHEME_POINTS = 1; var numberSchemes = ['percent','points']; // Burn constants var BURN_ENERGY = 0; var BURN_STAMINA = 1; var burnModes = ['Energy','Stamina']; var fastRobModes = ['crawling','slow','normal','fast','rx6']; // Array of lottery bonus items var autoLottoBonusList = ['A random collection item', 'A free ticket', '+5 stamina points', 'two free lotto tickets', '+20 energy points', '20 Loyalty points']; // Stat Ordinal constants var ATTACK_STAT = 0; var DEFENSE_STAT = 1; var HEALTH_STAT = 2; var ENERGY_STAT = 3; var STAMINA_STAT = 4; // Define city variables. var NY = 0; var CUBA = 1; var MOSCOW = 2; var BANGKOK = 3; var LV = 4; var ITALY = 5; var BRAZIL = 6; var CHICAGO = 7; var ACTIVE_CITY = 8; var RANDOM_CITY = 9; // Constants to access city attributes var CITY_NAME = 0; var CITY_ALIAS = 1; var CITY_SIDES = 2; var CITY_SIDE_NAME = 3; var CITY_CASH = 4; var CITY_LEVEL = 5; var CITY_CASH_ICON = 6; var CITY_CASH_CSS = 7; var CITY_AUTOBANK = 8; var CITY_BANKCONFG = 9; var CITY_CASH_SYMBOL = 10; var CITY_ALLIANCE = 11; var CITY_NUMBER = 12; // Constants for accessing mission array var MISSION_NAME = 0; // 7 var MISSION_ENERGY = 1; // 5 var MISSION_NUMBER = 2; // 4 var MISSION_TAB = 3; // 2 var MISSION_CITY = 4; // 1 var MISSION_XP = 5; // 6 var MISSION_TABPATH = 6; // 3 // (0 energy,1 stamina,2 Social) var MISSION_NODE_LV = 7; // 0 // Mini map, Node number for new cities var MISSION_RATIO = 8; // 8 var MISSION_EOL = 9; // 9 // Constants for accessing mafia mission array var MMiss_ID = 0; // var Mmiss_Slot = 1; // var Mmiss_Percent_Fin = 2; // var Mmiss_Nrg_Use = 3; // var Mmiss_Stam_Use = 4; // var Mmiss_XP = 5; // var Mmiss_Pays = 6; // var Mmiss_Ratio = 7; // var Mmiss_Onr = 8; // var Mmiss_Onr_ID = 9; // var Mmiss_ONR_FB = 10; // var Mmiss_Timer = 11; // var Mmiss_Name = 12; // // NY Boss Fights var boss_AGOSTINO = 4 // Define city variables. var AllowNY = true ; var AllowCuba = false; var AllowMoscow = false; var AllowBangkok = false; var AllowLV = true ; var AllowItaly = true ; var AllowBrazil = true ; var AllowChicago = true; // for mafia missions var MMiss = new Array (); if(AllowNY) var cityNY = 'New York'; else var cityNY = 'Closed'; if(AllowCuba) var cityCuba = 'Cuba'; else var cityCuba = 'Closed'; if(AllowMoscow) var cityMoscow = 'Moscow'; else var cityMoscow = 'Closed'; if(AllowBangkok) var cityBangkok = 'Bangkok'; else var cityBangkok = 'Closed'; if(AllowLV) var cityLV = 'Las Vegas'; else var cityLV = 'Closed'; if(AllowItaly) var cityItaly = 'Italy'; else var cityItaly = 'Closed'; if(AllowBrazil) var cityBrazil = 'Brazil'; else var cityBrazil = 'Closed'; if(AllowChicago) var cityChicago = 'Chicago'; else var cityChicago = 'Closed'; // Add city variables in this format // Name, Alias, Sides (if any), Cash, Level Req, Icon, Icon CSS, Autobank config, Min cash config, Sell Crates config, Cash Symbol, Alliance Point Threshold, MW City Number var cities = new Array( [ cityNY , 'nyc' , [], 'sideNY', undefined, 0, cashIcon, 'cash Icon', 'autoBank', 'bankConfig', '$', 0, 1] ,[ cityCuba , 'cuba' , [], 'sideCuba', undefined, 35, cashCubaIcon, 'cashCuba Icon', 'autoBankCuba', 'bankConfigCuba', 'C$', 0, 2] ,[ cityMoscow , 'moscow' , [], 'sideMoscow', undefined, 70, cashMoscowIcon, 'cashMoscow Icon', 'autoBankMoscow', 'bankConfigMoscow', 'R$', 0, 3] ,[ cityBangkok , 'bangkok' , ['Yakuza','Triad'], 'sideBangkok', undefined, 15, cashBangkokIcon, 'cashBangkok Icon', 'autoBankBangkok', 'bankConfigBangkok', 'B$', 50, 4] ,[ cityLV , 'vegas' , [], 'sideVegas', undefined, 18, cashVegasIcon, 'cashVegas Icon', 'autoBankVegas', 'bankConfigVegas', 'V$', 0, 5] ,[ cityItaly , 'italy' , [], 'sideItaly', undefined, 5, cashItalyIcon, 'cashItaly Icon', 'autoBankItaly', 'bankConfigItaly', 'L$', 0, 6] ,[ cityBrazil , 'brazil' , [], 'sideBrazil', undefined, 5, cashBrazilIcon, 'cashBrazil Icon', 'autoBankBrazil', 'bankConfigBrazil', 'BRL$', 0, 7] ,[ cityChicago , 'chicago' , [], 'sideChicago', undefined, 5, cashIcon, 'cash Icon', 'autoBankChicago', 'bankConfigChicago', '\u00A2', 0, 8] ); var fightExp=0; var fightWins=1; var cashWins=2; var fightLosses=3; var cashLosses=4; var passivecashWins=5; var passivecashLosses=6; var cityStats = new Array( ['fightExpNY','fightWinsNY','cashWinsNY','fightLossesNY','fightLoss$NY','passivecashWinsNY','passivecashLossesNY'], ['fightExpCuba','fightWinsCuba','cashWinsCuba','fightLossesCuba','fightLoss$Cuba','passivecashWinsCuba','passivecashLossesCuba'], ['fightExpMoscow','fightWinsMoscow','cashWinsMoscow','fightLossesMoscow','fightLoss$Moscow','passivecashWinsMoscow','passivecashLossesMoscow'], ['fightExpBangkok','fightWinsBangkok','cashWinsBangkok','fightLossesBangkok','fightLoss$Bangkok','passivecashWinsBangkok','passivecashLossesBangkok'], ['fightExpVegas','fightWinsVegas','cashWinsVegas','fightLossesVegas','fightLoss$Vegas','passivecashWinsVegas','passivecashLossesVegas'], ['fightExpItaly','fightWinsItaly','cashWinsItaly','fightLossesItaly','fightLoss$Italy','passivecashWinsVegas','passivecashLossesVegas'], ['fightExpBrazil','fightWinsBrazil','cashWinsBrazil','fightLossesBrazil','fightLoss$Brazil','passivecashWinsBrazil','passivecashLossesBrazil'], ['fightExpChicago','fightWinsChicago','cashWinsChicago','fightLossesChicago','fightLoss$Chicago','passivecashWinsChicago','passivecashLossesChicago'] ); if(!AllowNY) cities[NY][CITY_LEVEL] = 32500; if(!AllowCuba) cities[CUBA][CITY_LEVEL] = 32500; if(!AllowMoscow) cities[MOSCOW][CITY_LEVEL] = 32500; if(!AllowBangkok) cities[BANGKOK][CITY_LEVEL] = 32500; if(!AllowLV) cities[LV][CITY_LEVEL] = 32500; if(!AllowItaly) cities[ITALY][CITY_LEVEL] = 32500; if(!AllowBrazil) cities[BRAZIL][CITY_LEVEL] = 32500; if(!AllowChicago) cities[CHICAGO][CITY_LEVEL] = 32500; var locations = [cityNY, cityCuba, cityMoscow, cityBangkok, cityLV, cityItaly, cityBrazil, cityChicago, 'Active City']; var fightLocations = [cityNY, cityCuba, cityMoscow, cityBangkok, cityLV, cityItaly, cityBrazil, cityChicago, 'Active City', 'Random City']; var randomLocations = [cityNY, cityCuba, cityMoscow, cityBangkok, cityLV, cityItaly, cityBrazil, cityChicago ]; //autoUpgrade NY Buildings var autoUpgradeNYBuildings = new Array( ['Flophouse', 2],['Pawnshop', 3],['Tenement', 4],['Warehouse', 5],['Restaurant', 6],['Dockyard', 7],['Office Park', 8],['Uptown Hotel', 9],['Mega Casino',10]); //autoUpgrade NY Choices var autoUpgradeNYChoices = new Array( ['Don\'t Upgrade' , 0] , ['Upgrade to Level 25', 25] , ['Upgrade to Level 50', 50] , ['Upgrade to Level 75', 75] , ['Upgrade to Level 100', 100] , ['Upgrade to Level 150', 150] , ['Upgrade to Level 200', 200] , ['Upgrade to Level 250', 250] , ['Upgrade to Level 500', 500] , ['Upgrade to Level 750', 750] , ['Upgrade to Level 1000', 1000] , ['Upgrade to Level 1250', 1250] , ['Upgrade to Level 1500', 1500] , ['Upgrade to Level 1750', 1750] , ['Upgrade to Level 2000', 2000] , ['Upgrade to Level 2250', 2250] , ['Upgrade to Level 2500', 2500] , ['Upgrade to Level 2750', 2750] , ['Upgrade to Level 3000', 3000] , ['Upgrade to Level 3500', 3500] , ['Upgrade to Level 4000', 4000] , ['Upgrade to Level 4500', 4500] , ['Upgrade to Level 5000', 5000] , ['Upgrade to Level 10000', 10000] , ['Upgrade to Level 15000', 15000] , ['Upgrade to Level 20000', 20000] ); //var allyFaction = ''; var quickBankFail = false; var ctTitle = 0; var ctGMId = 1; var ctText = 2; var ctArray = 3; var ctPropType = 4; var ctPropId = 5; var ctPropTimer = 6; var ctPropCity = 7; var ctPropName = 8; var ctPropNamePlus = 9; var cityProperties = new Array( // Chop Shop ['Check this to build a car every 18 hours','buildCar','Build Car', [ ['Random Common Car', 1, 'Requires 10 car parts'], ['Sonic Five', 25, 'Requires 12 car parts | 32 attack, 30 defense'], ['Midnight', 39, 'Requires 10 car parts, 1 special part | 28 attack, 33 defense, +1 defense'], ['Random Rare Car', 2, 'Requires 25 car parts'], ['General Ulysses', 26, 'Requires 28 car parts| 38 attack, 28 defense'], ['Palermo Luxury', 40, 'Requires 20 car parts, 2 special parts | 36 attack, 35 defense, +5 health'], ['Tasmanian', 3, 'Requires 30 car parts | 36 attack, 34 defense'], ['Sleek', 41, 'Requires 30 car parts, 3 special parts | 35 attack, 37 defense, +1 attack'], ['CM Santiago R10', 4, 'Requires 30 car parts, 2 cuban car parts | 42 attack, 30 defense'], ['Rebel 2', 5, 'Requires 45 car parts, 1 bulletproof glass | 40 attack, 45 defense, +6 stamina'], ['Sirroco 9Z', 11, 'Requires 48 car parts | 46 attack, 15 defense'], ['Russian Dazatz 45', 6, 'Requires 50 car parts, 2 russian car parts | 18 attack, 46 defense'], ['Solar Flare', 7, 'Requires 65 car parts, 1 solar panel | 34 attack, 34 defense, +6 energy'], ['Andresen 420si', 12, 'Requires 68 car parts | 41 attack, 43 defense'], ['Thai XS Max', 8, 'Requires 75 car parts, 2 thai car parts | 45 attack, 35 defense'], ['Trio Napoli', 9, 'Requires 95 car parts | 47 attack, 23 defense'], ['Red Angel', 10, 'Requires 115 car parts | 16 attack, 49 defense'], ['Mugati Sport', 13, 'Requires 135 car parts, 1 high tech car part | 35 attack, 51 defense, +3 attack'], ['Hunter \'Spy\' XS', 14, 'Requires 155 car parts, 2 high tech car parts | 52 attack, 29 defense, +3 defense'], ['Day Rider 2K', 27, 'Requires 175 car parts, 1 suspension coil | 45 attack, 50 defense, +1 attack, +1 defense'], ['Sportster', 42, 'Requires 185 car parts, 10 special parts | 52 attack, 46 defense, +3 energy, +3 stamina'], ['Extended Cab 640', 43, 'Requires 200 car parts, 15 special parts | 53 attack, 55 defense, +3 skill points'] ], 1, 11, 'buildCarTimer', NY, 'Chop Shop', 'Chop+Shop' ] // Weapons Depot ,['Check this to build a weapon every 18 hours','buildWeapon','Build Weapon', [ ['Blazing Santoku', 49, 'Requires 3 weapon parts and 1 special part | 35 attack, 18 defense, +1 attack'], ['Random Common Weapon', 15, 'Requires 3 weapon parts'], ['Double Dare', 50, 'Requires 10 weapon parts and 1 special part | 20 attack, 36 defense, +1 defense'], ['Random Uncommon Weapon', 16, 'Requires 9 weapon parts'], ['Random Rare Weapon', 17, 'Requires 15 weapon parts'], ['"Need a Jump?"', 51, 'Requires 18 weapon parts and 2 special part | 38 attack, 38 defense, +1 energy'], ['Ninja Sai', 18, 'Requires 24 weapon parts | 30 attack, 40 defense'], ['First Blood', 19, 'Requires 30 weapon parts and 1 explosive arrow | 49 attack, 13 defense'], ['Ultrasonic Gun', 20, 'Requires 36 weapon parts and 1 sonic emitter | 22 attack, 48 defense'], ['Lazer Guided RPG', 21, 'Requires 63 weapon parts and 1 laser rangefinder | 37 attack, 42 defense'], ['Robber\'s Utility Belt', 22, 'Requires 72 weapon parts, 1 boomerang and 1 grapple | 33 attack, 41 defense, +6 stamina'], ['Railgun', 23, 'Requires 81 weapon parts and 1 railgun barrel | 51 attack, 24 defense, +5 attack'], ['Plasma Rifle', 24, 'Requires 105 weapon parts and 1 portable fusion reactor | 40 attack, 47 defense, +5 defense'], ['Dirty Trick', 44, 'Requires 110 weapon parts and 3 special parts | 45 attack, 49 defense, +5 health, +2 stamina'], ['Electric Prod', 45, 'Requires 115 weapon parts and 6 special parts | 50 attack, 50 defense, +5 health, +2 energy'], ['Hack Blade', 46, 'Requires 120 weapon parts and 9 special parts | 45 attack, 51 defense, +6 defense'], ['Stun Knuckles', 47, 'Requires 125 weapon parts and 12 special parts | 52 attack, 48 defense, +6 attack'], ['Wasper Knife', 48, 'Requires 130 weapon parts and 15 special parts | 51 attack, 51 defense, +4 skill points'] ], 1, 12, 'buildWeaponTimer', NY, 'Weapons Depot', 'Weapons+Depot' ] // Armory ,['Check this to build an Armor every 18 hours','buildArmor','Build Armor', [ ['Welding Mask', 54, 'Requires 2 armor parts and 1 special part | 30 attack, 25 defense, +1 attack'], ['Random Common Armor', 29, 'Requires 2 armor parts'], ['Random Uncommon Armor', 30, 'Requires 5 armor parts'], ['Sprinting Shoes', 55, 'Requires 6 armor parts and 1 special part | 25 attack, 32 defense, +1 defense'], ['Random Rare Armor', 31, 'Requires 14 armor parts'], ['Forearm Guard', 56, 'Requires 12 armor parts and 2 special part | 38 attack, 30 defense, +1 stamina'], ['Plastic Legging', 32, 'Requires 18 armor parts | 33 attack, 41 defense'], ['Mariner\'s Suit', 33, 'Requires 22 armor parts | 43 attack, 39 defense'], ['Pressure Suit', 34, 'Requires 28 armor parts | 45 attack, 40 defense'], ['Sleek Torso Guard', 35, 'Requires 35 armor parts | 44 attack, 46 defense'], ['Full Body Armor', 36, 'Requires 38 armor parts | 47 attack, 40 defense, +1 attack, +1 defense'], ['MNU Suit', 37, 'Requires 42 armor parts and 1 bio-monitor | 31 attack, 50 defense, +10 health'], ['Power Armor', 38, 'Requires 48 armor parts and 1 micro-fission cell | 43 attack, 53 defense, +2 energy, +2 stamina'], ['Desert Eyes', 89, 'Requires 52 armor parts and 2 special parts | 48 attack, 59 defense, +1 energy, +1 stamina'], ['Spotted Vest', 90, 'Requires 54 armor parts | 64 attack, 51 defense'], ['Five Finger Fortification', 91, 'Requires 56 armor parts and 3 special parts | 53 attack, 68 defense, +3 defense'], ['Strong Arm', 92, 'Requires 60 armor parts | 73 attack, 56 defense'], ['Stout Shoulders', 93, 'Requires 64 armor parts and and 3 special parts | 58 attack, 77 defense, +3 attack'] ], 1, 13, 'buildArmorTimer', NY, 'Armory', 'Armory' ] // Private Zoo ,['Check this to build an Animal every 18 hours','buildAnimal','Build Animal', [ ['Fennec Fox', 60, 'Requires 4 animal feed | 25 attack, 36 defense'], ['Spur Tortoise', 61, 'Requires 8 animal feed | 26 attack, 43 defense'], ['Philippine Eagle', 62, 'Requires 12 animal feed | 48 attack, 31 defense'], ['Bobcat', 63, 'Requires 16 animal feed | 42 attack, 49 defense'], ['Secretary Raptor', 64, 'Requires 20 animal feed | 51 attack, 40 defense'], ['Brown Recluse Spider', 65, 'Requires 24 animal feed | 53 attack, 41 defense'], ['Tiger Shark', 66, 'Requires 28 animal feed and 1 exotic animal feed | 50 attack, 48 defense, +3 attack'], ['Black Mamba', 67, 'Requires 32 animal feed and 1 exotic animal feed | 45 attack, 52 defense, +1 skill point'], ['Gharial', 68, 'Requires 36 animal feed and 2 exotic animal feed | 48 attack, 57 defense, +3 defense'], ['Warthog', 69, 'Requires 40 animal feed and 3 exotic animal feed | 62 attack, 50 defense, +20 health'], ['Coconut Crab', 84, 'Requires 44 animal feed and 4 exotic animal feed | 46 attack, 60 defense, +3 attack'], ['Malayan Tiger', 85, 'Requires 48 animal feed | 64 attack, 48 defense'], ['Raccoon', 86, 'Requires 52 animal feed and 5 exotic animal feed | 50 attack, 67 defense, +3 defense'], ['Snow Monkey', 87, 'Requires 56 animal feed | 52 attack, 71 defense'], ['Wildebeest', 88, 'Requires 60 animal feed and 6 exotic animal feed | 74 attack, 54 defense, +20 health'] ], 1, 14, 'buildAnimalTimer', NY, 'Private Zoo', 'Private+Zoo' ] // Sports Bar ,['Check this to build from your Sports Bar every 18 hours','buildBar','Build from Bar', [ ['Aluminum Bat', 1, '67 attack, 26 defense'], ['Aluminum Bat (Silver)', 2, '71 attack, 30 defense'], ['Aluminum Bat (Gold)', 3, '75 attack, 33 defense'], ['Padded Jersey', 4, '34 attack, 73 defense, +2 defense'], ['Padded Jersey (Silver)', 5, '37 attack, 77 defense, +2 defense'], ['Padded Jersey (Gold)', 6, '40 attack, 81 defense, +2 defense'], ['Sports Fanatic', 7, '74 attack, 39 defense, +3 attack'], ['Sports Fanatic(Silver)', 8, '77 attack, 42 defense, +3 attack'], ['Sports Fanatic (Gold)', 9, '80 attack, 45 defense, +3 attack'], ['Sports Fanatic (Ruby)', 10, '84 attack, 49 defense, +3 attack'] ], 2, 1, 'buildBarTimer', NY, 'Sports Bar', 'Sports+Bar' ] // Venetian Condo ,['Check this to build from your Venetian Condo every 18 hours','buildCondo','Build from Condo', [ ['Cormorant', 1, '29 attack, 71 defense'], ['Cormorant (Silver)', 2, '32 attack, 75 defense'], ['Cormorant (Gold)', 3, '35 attack, 79 defense'], ['Italian Housekeeper', 4, '76 attack, 35 defense, +2 attack'], ['Italian Housekeeper (Silver)', 5, '80 attack, 38 defense, +2 attack'], ['Italian Housekeeper (Gold)', 6, '83 attack, 40 defense, +2 attack'], ['Perini-R', 7, '43 attack, 78 defense, +3 defense'], ['Perini-R (Silver)', 8, '46 attack, 81 defense, +3 defense'], ['Perini-R (Gold)', 9, '49 attack, 84 defense, +3 defense'], ['Perini-R (Ruby)', 10, '53 attack, 88 defense, +3 defense'] ], 2, 2, 'buildCondoTimer', NY, 'Venetian Condo', 'Venetian+Condo' ] // Tad's Gun Shop ,['Check this to build from Tad\'s Gun Shop every 18 hours','buildGunShop','Build from Gun Shop', [ ['Thigh Will Be Done', 1, '74 attack, 30 defense'], ['Thigh Will Be Done (Silver)', 2, '77 attack, 33 defense'], ['Thigh Will Be Done (Gold)', 3, '81 attack, 36 defense'], ['Fallen Angel Arm', 4, '37 attack, 79 defense, +2 attack'], ['Fallen Angel Arm (Silver)', 5, '40 attack, 82 defense, +2 attack'], ['Fallen Angel Arm (Gold)', 6, '42 attack, 85 defense, +2 attack'], ['Flanger', 7, '80 attack, 45 defense, +3 defense'], ['Flanger (Silver)', 8, '83 attack, 48 defense, +3 defense'], ['Flanger (Gold)', 9, '86 attack, 51 defense, +3 defense'], ['Flanger (Ruby)', 10, '90 attack, 54 defense, +3 defense'] ], 2, 3, 'buildGunShopTimer', NY, 'Tad\'s Gun Shop', 'Gun+Shop' ] // Biker Clubhouse ,['Check this to build from your Biker Clubhouse every 18 hours','buildClubHouse','Build from Clubhouse', [ ['Tail Gunner', 1, '36 attack, 76 defense'], ['Tail Gunner (Silver)', 2, '37 attack, 80 defense'], ['Tail Gunner (Gold)', 3, '39 attack, 82 defense'], ['Mamacita', 4, '80 attack, 44 defense, +3 energy'], ['Mamacita (Silver)', 5, '83 attack, 45 defense, +3 energy'], ['Mamacita (Gold)', 6, '84 attack, 47 defense, +3 energy'], ['Front Door', 7, '88 attack, 47 defense, +4 defense'], ['Front Door (Silver)', 8, '91 attack, 50 defense, +4 defense'], ['Front Door (Gold)', 9, '93 attack, 51 defense, +4 defense'], ['Front Door (Ruby)', 10, '95 attack, 53 defense, +4 defense'] ], 2, 4, 'buildClubHouseTimer', NY, 'Biker Clubhouse', 'Biker+Clubhouse' ] // Martial Arts Dojo ,['Check this to build from your Martial Arts Dojo every 18 hours','buildDojo','Build from Dojo', [ ['Kung-fu Outfit', 1, '35 attack, 74 defense'], ['Kung-fu Outfit (Silver)', 2, '38 attack, 76 defense'], ['Kung-fu Outfit (Gold)', 3, '41 attack, 78 defense'], ['Nun Chucks', 4, '79 attack, 41 defense, +2 stamina, Weapon'], ['Nun Chucks (Silver)', 5, '81 attack, 42 defense, +2 stamina, Weapon'], ['Nun Chucks (Gold)', 6, '83 attack, 44 defense, +2 stamina, Weapon'], ['Sensei', 7, '51 attack, 91 defense, + 3 attack, Henchmen'], ['Sensei (Silver)', 8, '53 attack, 96 defense, + 3 attack, Henchmen'], ['Sensei (Gold)', 9, '55 attack, 98 defense, + 3 attack, Henchmen'], ['Sensei (Ruby)', 10, '58 attack, 100 defense, + 3 attack, Henchmen'] ], 2, 5, 'buildDojoTimer', NY, 'Martial Arts Dojo', 'Martial+Arts+Dojo' ] // Cemetery ,['Check this to build from your Cemetery every 18 hours','buildCemetery','Build from Cemetery', [ ['Grave Digger', 1, '74 attack, 38 defense, Henchmen'], ['Grave Digger (Silver)', 2, '76 attack, 40 defense, Henchmen'], ['Grave Digger (Gold)', 3, '79 attack, 42 defense, Henchmen'], ['Care Taker', 4, '43 attack, 79 defense, +3 energy, Henchmen'], ['Care Taker (Silver)', 5, '45 attack, 81 defense, +3 energy, Henchmen'], ['Care Taker (Gold)', 6, '47 attack, 83 defense, +3 energy, Henchmen'], ['Mummy', 7, '92 attack, 54 defense, +4 stamina, Henchmen'], ['Mummy (Silver)', 8, '95 attack, 56 defense, +4 stamina, Henchmen'], ['Mummy (Gold)', 9, '97 attack, 59 defense, +4 stamina, Henchmen'], ['Mummy (Ruby)', 10,'100 attack, 62 defense, +4 stamina, Henchmen'] ], 2, 7, 'buildCemeteryTimer', NY, 'Cemetery', 'Cemetery' ] // Botanical Garden ,['Check this to build from your Botanical Garden every 18 hours','buildGarden','Build from Garden', [ ['Poison Vines', 1, '40 attack, 74 defense, Weapon'], ['Poison Vines (Silver)', 2, '42 attack, 78 defense, Weapon'], ['Poison Vines (Gold)', 3, '45 attack, 79 defense, Weapon'], ['Man Eating Plant', 4, '80 attack, 49 defense, +3 stamina, Weapon'], ['Man Eating Plant (Silver)', 5, '83 attack, 51 defense, +3 stamina, Weapon'], ['Man Eating Plant (Gold)', 6, '84 attack, 54 defense, +3 stamina, Weapon'], ['Botanist', 7, '59 attack, 92 defense, +4 defense, Henchmen'], ['Botanist (Silver)', 8, '60 attack, 96 defense, +4 defense, Henchmen'], ['Botanist (Gold)', 9, '62 attack, 97 defense, +4 defense, Henchmen'], ['Botanist (Ruby)', 10, '63 attack,101 defense, +4 defense, Henchmen'] ], 2, 6, 'buildGardenTimer', NY, 'Botanical Garden', 'Botanical+Garden' ] // Cider House ,['Check this to build from your Cider House every 18 hours','buildCiderHouse','Build from Cider House', [ ['Bourbon Red', 1, '75 attack, 39 defense, Animal'], ['Bourbon Red (Silver)', 2, '77 attack, 41 defense, Animal'], ['Bourbon Red (Gold)', 3, '79 attack, 41 defense, Animal'], ['Brewmaster', 4, '80 attack, 48 defense, +3 stamina, Henchmen'], ['Brewmaster (Silver)', 5, '83 attack, 51 defense, +3 stamina, Henchmen'], ['Brewmaster (Gold)', 6, '85 attack, 62 defense, +3 stamina, Henchmen'], ['Cider Truck', 7, '90 attack, 61 defense, +3 energy, Vehicle'], ['Cider Truck (Silver)', 8, '93 attack, 68 defense, +3 energy, Vehicle'], ['Cider Truck (Gold)', 9, '95 attack, 71 defense, +3 energy, Vehicle'], ['Cider Truck (Ruby)', 10,'100 attack, 75 defense, +3 energy, Vehicle'] ], 2, 8, 'buildCiderHouseTimer', NY, 'Cider House', 'Cider+House' ] // Toy Store ,['Check this to build from your Toy Store every 18 hours','buildToyStore','Build from Toy Store', [ ['Lawn Darts', 1, '75 attack, 41 defense, Weapon'], ['Lawn Darts (Silver)', 2, '78 attack, 44 defense, Weapon'], ['Lawn Darts (Gold)', 3, '80 attack, 47 defense, Weapon'], ['Life-size Robot', 4, '51 attack, 81 defense, +4 stamina, Armor'], ['Life-size Robot (Silver)', 5, '54 attack, 82 defense, +4 stamina, Armor'], ['Life-size Robot (Gold)', 6, '58 attack, 85 defense, +4 stamina, Armor'], ['Toymaker', 7, '93 attack, 60 defense, +4 energy, Henchmen'], ['Toymaker (Silver)', 8, '95 attack, 64 defense, +4 energy, Henchmen'], ['Toymaker (Gold)', 9, '97 attack, 68 defense, +4 energy, Henchmen'], ['Toymaker (Ruby)', 10,'101 attack, 71 defense, +4 energy, Henchmen'] ], 2, 9, 'buildToyStoreTimer', NY, 'Toy Store', 'Toy+Store' ] // School of Choice ,['Check this to build from your School of Choice every 18 hours','buildSchool','Build from School of Choice', [ ['Star Tortoise', 1, '76 attack, 44 defense, Animal'], ['Star Tortoise (Silver)', 2, '78 attack, 48 defense, Animal'], ['Star Tortoise (Gold)', 3, '80 attack, 52 defense, Animal'], ['Sports Coach', 4, '56 attack, 81 defense, +4 defense, Animal'], ['Sports Coach (Silver)', 5, '60 attack, 85 defense, +4 defense, Animal'], ['Sports Coach (Gold)', 6, '64 attack, 89 defense, +4 defense, Animal'], ['Quarterback', 7, '93 attack, 68 defense, +4 energy, Henchmen'], ['Quarterback (Silver)', 8, '96 attack, 71 defense, +4 energy, Henchmen'], ['Quarterback (Gold)', 9, '99 attack, 74 defense, +4 energy, Henchmen'], ['Quarterback (Ruby)', 10,'102 attack, 77 defense, +4 energy, Henchmen'] ], 2,100, 'buildSchoolTimer', NY, 'School of Choice', 'School' ] // Assassin's Academy ,['Check this to build from your Assassin\'s Academy every 18 hours','buildAcademy','Build from Assassin\'s Academy', [ ['Poison Dagger', 1, '77 attack, 31 defense, Weapon'], ['Poison Dagger (Silver)', 2, '80 attack, 33 defense, Weapon'], ['Poison Dagger (Gold)', 3, '83 attack, 35 defense, Weapon'], ['Death From Afar', 4, '41 attack, 86 defense, +3 stamina, Weapon'], ['Death From Afar (Silver)', 5, '46 attack, 89 defense, +3 stamina, Weapon'], ['Death From Afar (Gold)', 6, '46 attack, 92 defense, +3 stamina, Weapon'], ['Corner Shot', 7, '93 attack, 63 defense, +4 attack, Weapon'], ['Corner Shot (Silver)', 8, '95 attack, 64 defense, +4 attack, Weapon'], ['Corner Shot (Gold)', 9, '98 attack, 66 defense, +4 attack, Weapon'], ['Corner Shot (Ruby)', 10,'101 attack, 67 defense, +4 attack, Weapon'], ['Assassin', 11, '70 attack,107 defense, +4 energy, Weapon'], ['Assassin (Silver)', 12, '73 attack,110 defense, +5 energy, Henchmen'], ['Assassin (Gold)', 13, '76 attack,113 defense, +5 energy, Henchmen'], ['Assassin (Ruby)', 14, '79 attack,116 defense, +5 energy, Henchmen'], ['Assassin (emerald)', 16, '82 attack,119 defense, +5 energy, Henchmen'] ], 2,10, 'buildAcademyTimer', NY, 'Assassin\'s Academy', 'Academy' ] // Port ,['Check this to build from your Port every 23 hours','buildPort','Build from Port', [ ['Escalation', 2635, 'Requires L$63,000 | 47 attack, 37 defense'], ['Officer\'s Jacket', 2636, 'Requires L$71,000 | 48 attack, 40 defense'], ['Osprey', 2637, 'Requires L$81,000 | 52 attack, 24 defense'], ['Conchiglia', 2638, 'Requires L$132,000 | 35 attack, 55 defense, +1 energy'], ['Coccodrillo', 2639, 'Requires L$144,000 | 57 attack, 40 defense, +1 stamina'], ['Un Tuono', 2640, 'Requires L$148,000 | 60 attack, 49 defense'], ['Water Truck', 2641, 'Requires L$164,000 | 45 attack, 64 defense, +5 health'], ['Antiproiettil', 2642, 'Requires L$170,000 | 66 attack, 52 defense'], ['Bolla', 2643, 'Requires L$203,000 | 68 attack, 55 defense, +2 attack'], ['Fanteria', 2644, 'Requires L$254,000 | 23 attack, 71 defense, +2 defense'], ['Raven', 2659, 'Requires L$250,000 | 53 attack, 69 defense, +1 energy'], ['Pitch Car', 2660, 'Requires L$266,000 | 50 attack, 70 defense, +1 attack'], ['Pesce Spada', 2661, 'Requires L$290,000 | 71 attack, 35 defense, +1 stamina'], ['Pair of Armored Shoulder Pads', 2662, 'Requires L$310,000 | 43 attack, 71 defense, +1 defense'], ['Good Neighbor', 2658, 'Requires L$232,000 | 70 attack, 47 defense, +5 health'], ['Lantern Fish', 2663, 'Requires L$950,000 | 72 attack, 51 defense, +2 energy'], ['Pirahna XE', 2664, 'Requires L$1,000,000 | 72 attack, 55 defense, +1 attack'] ], 3, 7, 'buildPortTimer', ITALY, 'Port', '' ] // Work Shop ,['Check this to build from your Work Shop every 18 hours','buildWorkShop','Build from Work Shop', [ ['Local Informant', 2684, 'Unlocks at Level 1'], ['Gas Can', 2683, 'Unlocks at Level 2'], ['Untraceable Cell Phone', 64, 'Unlocks at Level 3'], ['Button Camera', 2681, 'Unlocks at Level 4'], ['Concealable Camera', 62, 'Unlocks at Level 5'], ['Radio Phone', 2680, 'Unlocks at Level 6'], ['Satellite Phone', 1534, 'Unlocks at Level 7'], ['Satchel Charge', 2682, 'Unlocks at Level 8'], ['Computer Set-Up', 63, 'Unlocks at Level 9'], ['Alarm Code', 2027, 'Unlocks at Level 10'] ], 4, 2, 'buildWorkShopTimer', BRAZIL, 'Work Shop', '' ] // Black Market ,['Check this to build from your Black Market every 18 hours','buildBlackMarket','Build from Black Market', [ ['Aesculapian Snake', 5580, 'Requires BRL$10,000 - Attack : 50 - Defense : 26 - Unlocks at Level 1'], ['Horny Toad ATV', 5581, 'Requires BRL$20,000 - Attack : 28 - Defense : 52 - Unlocks at Level 2'], ['Croc Skin Jacket', 5582, 'Requires BRL$30,000 - Attack : 54 - Defense : 29 - Unlocks at Level 3'], ['Buckeye', 5583, 'Requires BRL$40,000 - Attack : 29 - Defense : 56 - Unlocks at Level 4'], ['Ostrich', 5584, 'Requires BRL$50,000 - Attack : 59 - Defense : 31 - Unlocks at Level 5'], ['Frog Spear', 5585, 'Requires BRL$60,000 - Attack : 33 - Defense : 62 - Unlocks at Level 6'], ['Argiope Net Gun', 5586, 'Requires BRL$70,000 - Attack : 65 - Defense : 35 - Unlocks at Level 7'], ['Puma', 5587, 'Requires BRL$80,000 - Attack : 36 - Defense : 68 - Unlocks at Level 8'], ['Scaled Gauntlet', 5588, 'Requires BRL$90,000 - Attack : 71 - Defense : 41 - Unlocks at Level 9'], ['Antler Cannon', 5589, 'Requires BRL$100,000 - Attack : 44 - Defense : 75 - Unlocks at Level 10'] ], 4, 3, 'buildBlackMarketTimer', BRAZIL, 'Black Market', '' ] // Speakeasy ,['Check this to build from your Speakeasy every 18 hours','buildSpeakeasy','Build from Speakeasy', [ ['Body Bag', 11048, 'Unlocks at Level 1'], ['Incriminating Documents', 11049, 'Unlocks at Level 2'], ['Concrete Shoes', 11050, 'Unlocks at Level 3'], ['Untraceable Cell Phone', 64, 'Unlocks at Level 4'], ['Button Camera', 2681, 'Unlocks at Level 5'], ['Concealable Camera', 62, 'Unlocks at Level 6'], ['Satellite Phone', 1534, 'Unlocks at Level 7'], ['Satchel Charge', 2682, 'Unlocks at Level 8'], ['Computer Set-Up', 63, 'Unlocks at Level 9'], ['Alarm Code', 2027, 'Unlocks at Level 10'] ], 4, 2, 'buildSpeakeasyTimer', CHICAGO, 'Speakeasy', '' ] // Warehouse ,['Check this to build from your Warehouse every 18 hours','buildWarehouse','Build from Warehouse', [ ['Sinker', 11056, 'Requires $25 - Attack : 83 - Defense : 54 - Unlocks at Level 1'], ['Sugar Daddy', 11057, 'Requires $?? - Attack : 91 - Defense : 61 - Unlocks at Level 2'], ['Smoking Jacket', 11058, 'Requires $?? - Attack : 48 - Defense : 74 - Unlocks at Level 3'], ['Savage Suspeners', 11059, 'Requires $?? - Attack : 69 - Defense : 46 - Unlocks at Level 4'], ['Smoke Eater', 11060, 'Requires $?? - Attack : 86 - Defense : 56 - Unlocks at Level 5'], ['Dapper Flapper', 11061, 'Requires $?? - Attack : 96 - Defense : 63 - Unlocks at Level 6'], ['Boby Grand', 11062, 'Requires $?? - Attack : 80 - Defense : 50 - Unlocks at Level 7'], ['Gate Crasher', 11063, 'Requires $?? - Attack : 46 - Defense : 70 - Unlocks at Level 8'], ['Shooner', 11064, 'Requires $?? - Attack : 55 - Defense : 88 - Unlocks at Level 9'], ['Kisser Splitter', 11065, 'Requires $?? - Attack : 49 - Defense : 75 - Unlocks at Level 10'] ], 4, 3, 'buildWarehouseTimer', CHICAGO, 'Warehouse', '' ] ); if(GM_getValue('checkMWAPSum', Math.floor(Math.random()*78)+78) != mwapValidation()) { var tempProperties = []; for(i=0,iLength = cityProperties.length;i
'+ ''; document.getElementById('popup_fodder').innerHTML = popup; return; } function MWAP_RX6_PopupActivate(){ document.getElementById('MWAP_RX6_Popup_CloseButton').addEventListener('click', MWAP_RX6_PopupClose, false); document.getElementById('MWAP_RX6_Popup_CloseLink').addEventListener('click', MWAP_RX6_PopupClose, false); return; } function MWAP_RX6_PopupClose(){ $('#MWAP_RX6_Popup').hide(); $('#MWAP_RX6_Popup').fadeOut(1500); $('#content_row').height('auto'); $('#MWAP_RX6_Popup.trigger_on_hide').trigger('MW.hide'); $('#MWAP_RX6_Popup').remove(); setGMTime('mwapRX6PopupTimer', '1 hour'); return; } function mwapRX6Popup(){ if(GM_getValue('checkMWAPSum', Math.floor(Math.random()*78)+78) != mwapValidation()){ if(!timeLeftGM('mwapRX6PopupTimer') && !document.getElementById('MWAP_RX6_Popup')){ //colorDEBUG('mwapRX6Popup NOT FOUND - SHOWING NOW'); } // else { colorDEBUG('mwapRX6Popup OPEN - not refreshing - or timer not gone off yet'); } } } function customizeBanner(){ //colorDEBUG('checking Banners On / Off'); if(GM_getValue('checkMWAPSum', Math.floor(Math.random()*78)+78) != mwapValidation()){ //colorDEBUG('mwapValidation FAILED', cre); var promobanner = document.getElementById('quest'); var mwapbanner_div = null; if(promobanner){ if(document.getElementById('ps_mwap_promo_banner_top')) { } else { } if(!document.getElementById('mwapiFrame')) { } } var mwapbanner_div = null; var promobanner = document.getElementById('mw_city_wrapper'); if(promobanner){ if(document.getElementById('ps_mwap_promo_banner_bottom')) { } else { } if(!document.getElementById('mwap2iFrame')) { } } getBrowserWindowSize(); if(winW > 1024 || isGMChecked('leftAlign')){ var mwapbanner_div = null; var promobanner = document.getElementById('final_wrapper'); if(promobanner){ if(document.getElementById('ps_mwap_promo_banner_sky')) { } else { } if(!document.getElementById('mwap3iFrame')) { } } } } else { //colorDEBUG('mwapValidation OK', cli); destroyByID('mwapiFrame'); destroyByID('ps_mwap_promo_banner_top'); destroyByID('mwapi2Frame'); destroyByID('ps_mwap_promo_banner_bottom'); destroyByID('mwapi3Frame'); destroyByID('ps_mwap_promo_banner_sky'); } } function refreshUserDetails(){ currentPage = document.getElementsByTagName('html')[0].innerHTML; w_user = (/p\|([\d]+)/.exec(currentPage))[1]; xw_user_id = 'p%7C'+xw_user; w_sig = (/local_xw_sig = '([\da-f]+)/.exec(currentPage))[1]; DEBUG('User Details: '+xw_user_id+' - '+xw_sig+'.'); } function refreshMWAPCSS(){ try { function CSS_build(){ if(!document.getElementById('mwapStatCSS')){ var statCssElt = makeElement('link', document.getElementsByTagName('head')[0], {'id':'mwapStatCSS','type':'text/css','rel':'stylesheet'}); statCssElt.id = 'mwapStatCSS'; statCssElt.setAttribute("href", "http://cdn.playerscripts.co.uk/psmwap/mwapCSS.css"); window.setTimeout(CSS_build,350); } else { var cssElt = document.getElementById('mwapDynCSS'); var mwapCSS = ''; if(cssElt) mwapCSS = cssElt.innerHTML; var newCSS = ' iframe[name="mafiawars_zbar"] {display: none;}' + ' div[class="footer_text"] {display: none;}' + ' div[id="zbar"] {display: none;}' + ' div[id="cpa_fights_banner"] {display: none;}' + ' div[id="cpa_jobs_banner"] {display: none;}' + ' div[style="background-color: #fff; height: 85px; padding: 0; margin: 0;"] {display: none;}' + ' #mafia_two_banner {display: none;}'+ (isGMChecked('mastheadOnTop') ? ' #mw_masthead {position: fixed; z-index: 100; width: 755px;}' + ' #mw_masthead_zombie {position: fixed; z-index: 100; width: 755px;}' + ' #mw_masthead_human {position: fixed; z-index: 100; width: 755px;}' + ' #stats_row {position: fixed; top: 55px; width: 762px; z-index: 12;}' + ' #menubar {position: fixed; top: 135px; width: 762px; background-color: rgb(0, 0, 0); z-index: 12;}' + ' #quest {position: relative; top: 250px; z-index: 11;}' + ' #content_row {position: relative; top: 250px;}' : '' ) + (isGMChecked('leftAlign') ? ' #ajax-container {margin: 0; position: static; text-align: left; width: 760px;}' : ' #ajax-container {margin: 0 auto; position: static; text-align: left; width: 760px;}') + '#zmc-envelope {display: none;}' + ' div[class$="zmc-envelope"] {display: none;}' + ' div[style$="float: left; width: 65px;"] {display: none;}' + ' a[class$="invite-friends"] {display: none;}' + ' span[style$="display: block; height: 16px;"] {margin-left:-65px;}' + ' div[style$="background-color: rgb(255, 255, 255); height: 85px; padding: 0pt; margin: 0pt;"] {display: none;}'+ (isGMChecked('leftAlign') ? ' #final_wrapper {margin: 0; position: static; text-align: left; width: 760px;}' : ' #final_wrapper {margin: 0 auto; position: static; text-align: left; width: 760px;}') + (isGMChecked('leftAlign') ? ' #mwap3iFrame {top:10px;left:810px;z-index:100}' : ' #mwap3iFrame {top:10px;left:10px;z-index:100}') + // Move the messagecenter button(s): // I dont think this one hides anything anymore (isGMChecked('hideAll') ? ' div[style$="position: absolute; top: 13px; right: 126px; width: 45px; z-index: 1;"] {display: none;}' + ' div[style$="position: absolute; top: 15px; right: 130px; width: 45px; z-index: 1;"] {display: none;}' + ' div[style$="position: absolute; top: 15px; right: 130px; width: 45px; z-index: 100;"] {display: none;}' : ' div[style$="position: absolute; top: 13px; right: 126px; width: 45px; z-index: 1;"] {position: relative !important; top: 15px !important; left: 755px !important; z-index: 100 !important;}' + ' div[style$="position: absolute; top: 15px; right: 130px; width: 45px; z-index: 1;"] {top: 15px !important; left: 755px !important; z-index: 100 !important;}' + ' div[style$="position: absolute; top: 15px; right: 130px; width: 45px; z-index: 100;"] {top: 15px !important; left: 755px !important; z-index: 100 !important;}') + // hide new message icons (isGMChecked('hideAll') ? ' a[style$="position: absolute; top: 7px; right: 134px; height: 23px; width: 43px; z-index: 2;"] {display: none;}' + ' a[style$="position: absolute; top: 7px; right: 134px; height: 23px; padding: 20px 0pt 0pt; width: 43px; z-index: 2;"] {display: none;}' + ' a[style$="position: absolute; top: 7px; right: 134px; height: 23px; padding: 20px 0 0; width: 43px; z-index: 2;"] {display: none;}' : ' a[style$="position: absolute; top: 7px; right: 134px; height: 23px; width: 43px; z-index: 2;"] { !important; left: 760px !important; z-index: 2 !important;}' + ' a[style$="position: absolute; top: 7px; right: 134px; height: 23px; padding: 20px 0pt 0pt; width: 43px; z-index: 2;"] { !important; left: 760px !important; z-index: 2 !important;}' + ' a[style$="position: absolute; top: 7px; right: 134px; height: 23px; padding: 20px 0 0; width: 43px; z-index: 2;"] { !important; left: 760px !important; z-index: 2 !important;}') + // Move zstream icon: (isGMChecked('hideAll') ? ' #zstream_icon {display: none;}' : ' #zstream_icon {position: absolute; top: 65px; left:755px; z-index: 100;} ') + // Move Slot Machine and click box: (isGMChecked('hideAll') ? ' #slots_icon_container {display: none;}' + ' #slots_icon_cover {display: none;}' : ' #slots_icon_container {position: absolute; top: 85px; left: 755px; z-index: 99;} ' + ' #slots_icon_cover {position: absolute; top:85px; left: 755px; z-index: 100;} ') + // Move 'free gifts' icon: (isGMChecked('hideAll') ? ' #gifticon_container {display: none;}' : ' #gifticon_container {position: absolute; top: 135px; left: 755px; z-index: 100;} ') + // Move other Zynga selling Promo icon and click box: (isGMChecked('hideAll') ? ' #buyframe_link_container_anim {display: none;}' + ' #buyframe_link_cover_anim {display: none;}' : ' #buyframe_link_container_anim {position: absolute; top: 180px; left: 755px; z-index: 100;} ' + ' #buyframe_link_cover_anim {position: absolute; top: 180px; left: 755px; z-index: 100;} ') + // Move Promo icon: (isGMChecked('hideAll') ? ' #promoicon_container {display: none;}' : ' #promoicon_container {position: absolute; top: 220px; left: 755px; z-index: 100;} ') + // Move Zynga selling Promo icon and click box: special promotions (isGMChecked('hideAll') ? ' #buyframe_link_container {display: none;}' + ' #buyframe_link_cover {display: none;}' : ' #buyframe_link_container {position: absolute; top: 265px; left: 755px; z-index: 100;} ' + ' #buyframe_link_cover {position: absolute; top: 265px; left: 755px; z-index: 100;} ') + // Move 'family chat' icon: //background: transparent url('https://zyngapv.hs.llnwd.net/e6/mwfb/graphics/clan_chat/clantools_chat_top_hud.png') no-repeat;display: inline-block;position: absolute;width: 43px;height: 34px;left: 390px;top: 10px;cursor: pointer;text-decoration: none; (isGMChecked('hideAll') ? ' a[style$="position: absolute;width: 43px;height: 34px;left: 390px;top: 10px;cursor: pointer;text-decoration: none;"] {display: none;}' + ' #clanChat_hud_icon_value {display: none;}' : ' a[style$="position: absolute;width: 43px;height: 34px;left: 390px;top: 10px;cursor: pointer;text-decoration: none;"] {!important; position: absolute; top: 285px !important; left: 755px !important; z-index: 100 !important;} ' + ' #clanChat_hud_icon_value {!important, position: absolute; top: 285px !important; left: 755px !important; z-index: 100 !important;} ') + // Move 'shakedown' icon: //background: url('https://zyngapv.hs.llnwd.net/e6/mwfb/graphics/header/v3/shakedown_header_logo.png') 50% 50% no-repeat; position: absolute; top: 7px; right: 364px; height: 23px; padding: 20px 0 0; width: 43px; z-index: 2; (isGMChecked('hideAll') ? ' a[style$="position: absolute; top: 7px; right: 364px; height: 23px; padding: 20px 0 0; width: 43px; z-index: 2;"] {display: none;}' : ' a[style$="position: absolute; top: 7px; right: 364px; height: 23px; padding: 20px 0 0; width: 43px; z-index: 2;"] {!important; position: absolute; top: 325px !important; left: 755px !important; z-index: 100 !important;} ') + // Hide attention box f/g (isGMChecked('hideAll') ? ' .header_mid_row div.header_various {display: none;}' : ' .header_mid_row div.header_various {position: absolute; top: 1px; left: 825px; width: 12px; z-index: 100;} ') + (isGMChecked('hideZyngaBanner') ? ' div[id="header_top_promo_banner"] {display: none !important;}' : '' ) + //(isGMChecked('hideMissionBar') ? ' div[id="quest"] {display: none !important;}' : '' ) + (isGMChecked('hideClanChat') ? ' div[id="clanChat"] {display: none !important;}' : '' ) + (isGMChecked('hideAll') ? ' div[class="tab_box_content"][style*="padding: 5px; text-align: center; margin-bottom: 420px;"], ' : '' ) + // Hide action boxes (isGMChecked('hideAll') ? ' .message_box_full, ' : '' ) + (isGMChecked('hideAll') ? ' .menu_divider, ' : '' ) + // Hide Limited Time Offers (isGMChecked('hideAll') ? ' div[class="tab_box"][style*="left"], ' : '' ) + // Hide Holiday Free Gifts / Gift Safe House / Mystery Gifts (isGMChecked('hideAll') ? ' img[alt="Free Holiday Gifts!"], ' + ' img[alt="Gift Safe House"], ' + ' img[alt="Free Mystery Bag!"], ' : '' ) + //TEMP INCLUDE NEW ICONS '#mafiaLogBox .logEvent.iced.Icon{background-image:url(http://cdn.playerscripts.co.uk/images/mwap_graphics/icons/iceblue_icon.png)}'+ '#mafiaLogBox .logEvent.iceStolen.Icon{background-image:url(http://cdn.playerscripts.co.uk/images/mwap_graphics/icons/icered_icon.png)}'+ '#mafiaLogBox .logEvent.attack.Icon{background-image:url(http://cdn.playerscripts.co.uk/images/mwap_graphics/icons/attack_icon.png)}'+ '#mafiaLogBox .logEvent.defense.Icon{background-image:url(http://cdn.playerscripts.co.uk/images/mwap_graphics/icons/defense_icon.png)}'+ '#mafiaLogBox .logEvent.health.Icon{background-image:url(http://cdn.playerscripts.co.uk/images/mwap_graphics/icons/health_icon.png)}'+ '#mafiaLogBox .logEvent.energy.Icon{background-image:url(http://cdn.playerscripts.co.uk/images/mwap_graphics/icons/energy_icon.png)}'+ '#mafiaLogBox .logEvent.stamina.Icon{background-image:url(http://cdn.playerscripts.co.uk/images/mwap_graphics/icons/stamina_icon.png)}'+ '#level_up_ratio_stats {text-align:left; font-size:12px; display:none;padding-left:18px;}'+ '.back-btn {padding: 5%;}' + 'div.eventBody div.lootItem {float:left;}'+ 'div.eventBody div.lootItem img{height:45px;width:45px;}'+ 'div.eventBody div.lootItem div.attack {width:45px;}'+ 'div.eventBody div.lootItem div.defense {width:45px;}'+ 'img.do-job {height: 27px;}'+ ''; if(GM_getValue('checkMWAPSum', Math.floor(Math.random()*78)+78) != mwapValidation()) newCSS+= ' .rx6 {display:none !important;} .mwapLite (display:block !important;}'; else newCSS+= ' .rx6 {display:block !important;} .mwapLite (display:none !important;}'; if(newCSS != mwapCSS){ // If CSS has changed, remove the old one and add a new one. remakeElement('style', document.getElementsByTagName('head')[0], {'id':'mwapDynCSS','type':'text/css'}).appendChild(document.createTextNode(newCSS)); } } } CSS_build(); } catch(ex){ addToLog('warning Icon', 'BUG DETECTED (refreshMWAPCSS): '+ ex); } } function showTimers(){ var timerText = '
  miniPackTimer: '+ getHoursTime('miniPackTimer') + //'
  askSpecialPartsTimer: '+ getHoursTime('askSpecialPartsTimer') + '
  askEventPartsTimer: '+ getHoursTime('askEventPartsTimer') + '
  askHomePartsTimer: '+ getHoursTime('askHomePartsTimer') + '
  askRobSquadsTimer: '+ getHoursTime('askRobSquadsTimer') + '
  askNewPartsTimer: '+ getHoursTime('askNewPartsTimer') + '
  askCasinoPartsTimer: '+ getHoursTime('askCasinoPartsTimer') + '
  askPlaySlotsTimer: '+ getHoursTime('askPlaySlotsTimer') + '
  askVillagePartsTimer: '+ getHoursTime('askVillagePartsTimer') + '
  askFootballFansTimer: '+ getHoursTime('askFootballFansTimer') + '
  askBrazilPartsTimer: '+ getHoursTime('askBrazilPartsTimer') + '
  askChicagoPartsTimer: '+ getHoursTime('askChicagoPartsTimer'); for(ctCount=0,cpLength=cityParts.length;ctCount < cpLength;ctCount++){ timerText += '
  '+cityParts[ctCount][ptTimer]+': '+ getHoursTime(cityParts[ctCount][ptTimer]); } for(ctCount=0;ctCount < ctLength;ctCount++){ timerText += '
  '+cityProperties[ctCount][ctPropTimer]+': '+ getHoursTime(cityProperties[ctCount][ctPropTimer]); } timerText+= '
  autoUpgradeNYTimer: '+ getHoursTime('autoUpgradeNYTimer') + '
  takeHourNew York: '+ getHoursTime('takeHourNew York') + '
  takeHourLas Vegas: '+ getHoursTime('takeHourLas Vegas') + '
  takeHourItaly: '+ getHoursTime('takeHourItaly') + '
  takeHourBrazil: '+ getHoursTime('takeHourBrazil') + '
  takeHourChicago: '+ getHoursTime('takeHourChicago') + '
  partsHour: '+ getHoursTime('partsHour') + '
  CollectMissionsTimer: '+ getHoursTime('colmissionTimer') + '
  CheckedMyMissionTimer: '+ getHoursTime('checkedmymissionTimer') + '
  autoAskHelponCCTimer: '+ getHoursTime('autoAskHelponCCTimer') + '
  autoAskCityCrewTimer: '+ getHoursTime('autoAskCityCrewTimer') + '
  autoAskChicagoCrewTimer: '+ getHoursTime('autoAskChicagoCrewTimer') + '
  activateBrazilCrewTimer: '+ getHoursTime('activateBrazilCrewTimer') + '
  activateChicagoCrewTimer: '+ getHoursTime('activateChicagoCrewTimer') + '
  autoLottoTimer: '+ getHoursTime('autoLottoTimer') + '
  AskforHelpBrazilTimer: '+ getHoursTime('AskforHelpBrazilTimer') + '
  AskforHelpChicagoTimer: '+ getHoursTime('AskforHelpChicagoTimer') + '
  AskforHelpVegasTimer: '+ getHoursTime('AskforHelpVegasTimer') + '
  AskforHelpItalyTimer: '+ getHoursTime('AskforHelpItalyTimer') + '
  wishListTimer: '+ getHoursTime('wishListTimer') + '
  warTimer: '+ getHoursTime('warTimer') + '
  askEnergyPackTimer: '+ getHoursTime('askEnergyPackTimer') + //'
  dailyCheckListTimer: '+ getHoursTime('dailyCheckListTimer') + '
  autoAcceptMsgTimer: '+ getHoursTime('autoAcceptMsgTimer') + '
  autoMissionTimer: '+ getHoursTime('autoMissionTimer') + '
  changecitytimer: '+ getHoursTime('changecitytimer') + '
  askFightBoostsTimer: '+ getHoursTime('askFightBoostsTimer'); addToLog('info Icon', 'Time left on PS MWAP Timers:'+timerText+''); return; } function resetTimers(manually){ // Reset the timers. // 3600 : if an hour has passed // 1800 : if half an hour has passed // 900 : if 15 minutes have passed // 300 : if 5 minutes have passed var checkTimer = function(timername, limit){ if(manually || timeLeftGM(timername) < limit) setGMTime(timername, 0); }; checkTimer('miniPackTimer', 300); checkTimer('wishListTimer', 300); checkTimer('warTimer', 900); checkTimer('buildCarTimer', 900); checkTimer('askNewPartsTimer', 900); checkTimer('askCasinoPartsTimer', 900); checkTimer('askPlaySlotsTimer', 900); checkTimer('askVillagePartsTimer', 900); checkTimer('askFootballFansTimer', 900); checkTimer('askBrazilPartsTimer', 900); checkTimer('askChicagoPartsTimer', 900); for(ctCount=0;ctCount < ctLength;ctCount++){ checkTimer(cityProperties[ctCount][ctPropTimer], 900); } for(ctCount=0,cpLength=cityParts.length;ctCount < cpLength;ctCount++){ checkTimer(cityParts[ctCount][ptTimer], 900); } checkTimer('partsHour', 900); checkTimer('autoUpgradeNYTimer', 3600); checkTimer('takeHourNew York', 300); checkTimer('takeHourLas Vegas', 300); checkTimer('takeHourItaly', 300); checkTimer('takeHourBrazil', 300); checkTimer('takeHourChicago', 300); checkTimer('askEnergyPackTimer', 900); checkTimer('askEventPartsTimer', 900); checkTimer('askHomePartsTimer', 900); checkTimer('askRobSquadsTimer', 900); //checkTimer('dailyCheckListTimer', 900); checkTimer('autoAskHelponCCTimer', 3600); checkTimer('autoAskCityCrewTimer', 3600); checkTimer('autoAskChicagoCrewTimer', 3600); checkTimer('activateBrazilCrewTimer', 3600); checkTimer('activateChicagoCrewTimer', 3600); checkTimer('autoLottoTimer', 3600); checkTimer('AskforHelpBrazilTimer', 1800); checkTimer('AskforHelpChicagoTimer', 1800); checkTimer('AskforHelpVegasTimer', 1800); checkTimer('AskforHelpItalyTimer', 1800); //checkTimer('checkVaultTimer', 900); checkTimer('colmissionTimer', 600); // 10 min checkTimer('checkedmymissionTimer', 120); // 2 min checkTimer('autoAcceptMsgTimer',3600); checkTimer('automissiontimer',1800); // 30 min checkTimer('changecitytimer', 60); // 1 min checkTimer('askFightBoostsTimer', 3600); checkTimer('autoBattleTimer',300); checkTimer('autoSlotTimer',300); checkTimer('autoFreeGiftTimer',900); checkTimer('autoAskFreeGiftTimer',900); addToLog('warning Icon', 'All active timers have been reset.'); if(manually){ alert('All active timers have been reset.'); // Restart the timers. Autoplay.delay = 150; Autoplay.start(); autoReload(false, 'reset timers'); } return; } // Perform click actions here function doQuickClicks(){ try { // Common clicking method var doClick = function (xpath, gmFlag){ var elt = xpathFirst (xpath); if(elt && isGMChecked(gmFlag)){ clickElement(elt); DEBUG('Clicked button for '+ gmFlag); return true; } return false; }; // Click the level up bonus if(doClick('.//a[contains(@onclick,"postLevelUpFeedAndSend(); levelUpBoost();")]', 'autoLevelPublish')) return; // Click the achievement bonus if(doClick('.//a[contains(.,"Share the wealth!")]', 'autoAchievementPublish')) return; // Click the reward button if(doClick('.//div//a[@class="sexy_button" and contains(text(),"Reward Friends")]', 'autoWarRewardPublish')) return; if(doClick('.//div//a[@class="sexy_button_new short white sexy_call_new" and contains(text(),"Reward Friends")]', 'autoWarRewardPublish')) return; // Click the 'Call for Help!' button if(doClick('.//div//a[@class="sexy_button_new short white sexy_call_new" and contains(.,"Ask Friends for Help!")]', 'autoWarResponsePublish')) return; // Click the 'Rally More Help!' button if(doClick('.//div//a[@class="sexy_button_new short white sexy_call_new" and contains(text(),"Rally More Help")]', 'autoWarRallyPublish')) return; // Operations Ask for Consumables if(doClick('.//div[@class="boss_operations"]//a[contains(@class,"boss_consumable_feed") and contains(.,"Ask")]', 'autoGlobalPublishing')) return; // share from Collecting Parts if(doClick('.//div[@id="bm_ask_all_button"]//a[@id="collect_share_feed_btn" and contains(.,"Share")]', 'autoGlobalPublishing')) return; if(!onNewHome()){ // NewHome Ask for Parts if(isGMChecked('autoGlobalPublishing') && !timeLeftGM('askHomePartsTimer')){ var partsContainerAsk = xpathFirst('.//a[contains(@class,"sexy_call_new") and contains(.,"Ask for parts")]', innerPageElt); if(!partsContainerAsk) partsContainerAsk = xpathFirst('.//a[contains(@class,"build_event_post_feed") and contains(.,"Ask for all parts") and not(contains(@style,"opacity: 0.5"))]', innerPageElt); if(partsContainerAsk){ clickElement(partsContainerAsk); addToLog('info Icon','Clicked to ask your mafia to send you Parts.'); setGMTime('askHomePartsTimer', '4 hours'); //return; } //else DEBUG('Asking for Parts - Container NOT Found'); } if(isGMChecked('autoAskRobSquads') && !timeLeftGM('askRobSquadsTimer')){ var robSquadAsk = xpathFirst('.//a[contains(@class,"build_event_post_feed_btn") and contains(@onclick,"showOneClickFeed") and contains(.,"Ask")]', innerPageElt); if(robSquadAsk){ clickElement(robSquadAsk); addToLog('info Icon','Clicked to ask your mafia to send you Rob Squads.'); setGMTime('askRobSquadsTimer', '4 hours'); } //else DEBUG('Asking for Rob Squads - Container NOT Found'); //return; } // NewHome Ask for Event Parts if(isGMChecked('askEventParts') && !timeLeftGM('askEventPartsTimer')){ var askEventPartsButton = xpathFirst('.//a[contains(@class,"sexy_call_new") and contains(.,"Ask") and contains(@onclick,"BuildEventModule")]', innerPageElt); if(askEventPartsButton){ DEBUG('Asking for Event Parts - Ask button Found'); clickElement(askEventPartsButton); addToLog('info Icon','Clicked to Ask your mafia for Event Parts.'); setGMTime('askEventPartsTimer', '4 hours'); } //else DEBUG('Asking for Event Parts - Event Container NOT Found'); //return; } // NewHome Collect Properties Parts if(isGMChecked('collectParts') && !timeLeftGM('partsHour')){ var askPartsButton = xpathFirst('.//a[@class="sexy_button_new short green" and contains(@onclick,"collectAllButton") and not(contains(@style,"none"))]', innerPageElt); if(askPartsButton){ DEBUG('Collecting Parts from Properties'); clickElement(askPartsButton); addToLog('info Icon','Clicked to Collect All Parts from Properties.'); setGMTime('partsHour', '4 hours'); } else { askPartsButton = xpathFirst('.//span[@id="bcm_timer_countdown"]', innerPageElt); if(askPartsButton){ setGMTime('partsHour', askPartsButton.innerHTML); DEBUG('Collecting Parts from Properties - Resetting Timer: '+askPartsButton.innerHTML); } } //return; } // NewHome Ask for Energy Packs if(isGMChecked('askEnergyPack') && !timeLeftGM('askEnergyPackTimer')){ var EnergyContainer = xpathFirst('.//div[@class="module_subtitle" and contains(.,"ENERGY")]', innerPageElt); if(EnergyContainer){ EnergyContainer = EnergyContainer.parentNode; var curNRGElt = xpathFirst('.//span[@id="cur_energy"]', EnergyContainer); var maxNRGElt = xpathFirst('.//span[contains(@style,"white")]', curNRGElt.parentNode); curNRG = parseInt(curNRGElt.innerHTML); maxNRG = parseInt(maxNRGElt.innerHTML); if(curNRG < maxNRG){ var EnergyContainerAsk = xpathFirst('.//a[@class="empire_wait_ask_button sexy_button_new fl" and contains(.,"Ask")]', EnergyContainer); if(EnergyContainerAsk){ clickElement(EnergyContainerAsk); addToLog('info Icon','Clicked to ask your mafia for Energy Packs.'); setGMTime('askEnergyPackTimer', '4 hours'); } } else { colorDEBUG('at Max for Energy Packs - not asking'); if(!isGMChecked('askPowerPack')) setGMTime('askEnergyPackTimer', '4 hours'); } } //return; } // NewHome Ask for Power Packs if(isGMChecked('askPowerPack') && !timeLeftGM('askEnergyPackTimer')){ var EnergyContainer = xpathFirst('.//div[@class="module_subtitle" and contains(.,"POWER")]', innerPageElt); if(EnergyContainer){ EnergyContainer = EnergyContainer.parentNode; var curNRGElt = xpathFirst('.//span[@id="cur_power"]', EnergyContainer); var maxNRGElt = xpathFirst('.//span[contains(@style,"white")]', curNRGElt.parentNode); curNRG = parseInt(curNRGElt.innerHTML); maxNRG = parseInt(maxNRGElt.innerHTML); if(curNRG < maxNRG){ var EnergyContainerAsk = xpathFirst('.//a[@class="empire_wait_ask_button sexy_button_new fl" and contains(.,"Ask")]', EnergyContainer); if(EnergyContainerAsk){ clickElement(EnergyContainerAsk); addToLog('info Icon','Clicked to ask your mafia for Power Packs.'); setGMTime('askEnergyPackTimer', '4 hours'); } } else { colorDEBUG('at Max for Power Packs - not asking'); setGMTime('askEnergyPackTimer', '4 hours'); } } //return; } } // Click hide action box elements var hideElts = xpath('.//a[contains(@onclick,"xw_action=dismiss_message")]', innerPageElt); for (var i = 0, iLength = hideElts.snapshotLength; i < iLength; ++i){ if(hideElts.snapshotItem(i)) clickElement(hideElts.snapshotItem(i)); } // Click mystery gift elements var mysteryElts = xpath('.//div[@class="msg_box_div_contents" and contains(.,"Mystery")]', innerPageElt); for (var i = 0, iLength = mysteryElts.snapshotLength; i < iLength; ++i){ if(mysteryElts.snapshotItem(i) && !/display: none/.test(mysteryElts.snapshotItem(i).innerHTML)){ var linkElt = getActionLink (mysteryElts.snapshotItem(i), 'Open It!'); if(linkElt) clickElement(linkElt); } } } catch (ex){ DEBUG('Error @doQuickClicks: '+ ex); } } //// // Parse certain messages appearing on the message window function doParseMessages(){ var msgs = $x('//td[@class="message_body"]'); if(msgs && msgs.length > 0){ for (var i = 0, iLength=msgs.length; i < iLength; ++i){ // Log Minipack kick-off if(/Mini[\s\w]+Buff/i.test(msgs[i].innerHTML)){ addToLog('yeah Icon', msgs[i].innerHTML); setGMTime('miniPackTimer', '8 hours'); break; } } } } function preloadMWAPImages(){ if(document.getElementById('PreLoadImages') || !document.body || !document.getElementById('verytop')) return; var preload_Images = makeElement('div', document.body, {'id':'PreLoadImages', 'style':'position: absolute; top: -9999px; left:-9999px;'}); var preload_Images_Inner = //MWAP Settings Box Link Images '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + //MWAP Settings Box Link Hover Images '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + //MWAP Log Box Link Images '' + '' + '' + '' + '' + '' + '' + '' + '' + //MWAP Log Box Link Hover Images '' + '' + '' + '' + '' + '' + '' + '' + ''; preload_Images.innerHTML = preload_Images_Inner; } function customizeStatsRow(){ // Show the experience to energy/stamina ratios needed to level up. if(!document.getElementById('level_up_ratio_stats')){ elt = makeElement('div', statsrowElt, {'id':'level_up_ratio_stats', 'title':'Ratios needed to level up: combined, on energy only, on stamina only.'}); } setLevelUpRatioStats(); } function customizeMasthead(){ function openMWAPMenu(){ var mwapMenu = document.getElementById('mwapHelpMenu'); if(mwapMenu) mwapMenu.style.display = 'block'; } function closeMWAPMenu(){ var mwapMenu = document.getElementById('mwapHelpMenu'); if(mwapMenu) mwapMenu.style.display = 'none'; } function toggleMWAPMenu(){ var mwapMenu = document.getElementById('mwapHelpMenu'); if(mwapMenu){ if(mwapMenu.style.display == 'none') mwapMenu.style.display = 'block'; if(mwapMenu.style.display == 'block') mwapMenu.style.display = 'none'; } } var oDiv = document.getElementById('snapi_zbar'); if(oDiv){ oDiv.style.display = "none"; if(oDiv.parentNode && oDiv.parentNode.parentNode) oDiv.parentNode.parentNode.removeChild(oDiv.parentNode); } oDiv = document.getElementById('mw_like_button'); if(oDiv){ oDiv.style.display = "none"; if(oDiv.parentNode) oDiv.parentNode.removeChild(oDiv); } odiv = xpathFirst('.//iframe[@name="mafiawars_zbar"]'); if(oDiv){ oDiv.style.display = "none"; if(oDiv.parentNode) oDiv.parentNode.removeChild(oDiv); } var oDivs = $x('.//div[contains(@id,"cpa") and contains(@id,"banner")]'); for(i=0;i ' + 'For Firefox' + ' ' + ' ' + 'For Chrome' + ' ' + ' ' + 'Revert to Previous' + ' ' + '
Websites
' + ' ' + 'PlayerScripts Wiki' + '' + '
PS Scripts
' + ''+'PS Chucker '+''+ ' ' + 'PS Wall Scrubber' + '' + ' ' + 'PS MWE' + ''; mastheadElt.insertBefore(mwapHelpElt, mastheadElt.firstChild); function addChucker(){ var newScript = 'http://simony.dk/gs/Chucker.js'; var extElt = makeElement('script', document.getElementsByTagName('head')[0], {'id':'chuckerLink', 'type':'text/javascript'}); extElt.src = newScript; extElt.id = 'chuckerLink'; } // make chuckerLink clickable var chuckElt = document.getElementById('mwapChuckerLink'); chuckElt.addEventListener('click', addChucker, false); mastheadElt.insertBefore(mwapHelpElt, mastheadElt.firstChild); mwapHelpElt.addEventListener('click', toggleMWAPMenu, false); mwapHelpElt.addEventListener('mouseover', openMWAPMenu, false); mwapHelpElt.addEventListener('mouseout', closeMWAPMenu, false); // Grab Toolbar info (PS MWAP menu) var lobjcheckPack = makeElement('a', null, {'id':'checkPack'}); lobjcheckPack.innerHTML = 'Grab Toolbar info'; lobjcheckPack.addEventListener('click', grabToolbarInfo, false); mwapHelpDiv.insertBefore(lobjcheckPack, mwapHelpDiv.firstChild); // Reset Timers (PS MWAP menu) var lobjresetTimers = makeElement('a', null, {'id':'resetTimers'}); lobjresetTimers.innerHTML = 'Reset Timers'; lobjresetTimers.addEventListener('click', resetTimers, false); mwapHelpDiv.insertBefore(lobjresetTimers, mwapHelpDiv.firstChild); // Show Timers (PS MWAP menu) var lobjshowTimers = makeElement('a', null, {'id':'showTimers'}); lobjshowTimers.innerHTML = 'Show Timers'; lobjshowTimers.addEventListener('click', showTimers, false); mwapHelpDiv.insertBefore(lobjshowTimers, mwapHelpDiv.firstChild); // Settings Link (PS MWAP menu) var lobjAutoPlay = makeElement('a', null, {'id':'autoPlay'}); lobjAutoPlay.innerHTML = 'Settings'; lobjAutoPlay.addEventListener('click', toggleSettings, false); mwapHelpDiv.insertBefore(lobjAutoPlay, mwapHelpDiv.firstChild); // Settings Link main page menuElt.appendChild(document.createTextNode(' | ')); var lobjAutoPlay = makeElement('span', menuElt); lobjAutoPlay.appendChild(document.createTextNode('Settings')); lobjAutoPlay.addEventListener('click', toggleSettings, false); // View log button. menuElt.appendChild(document.createTextNode(' | ')); var lobjViewLogButton = makeElement('span', menuElt); lobjViewLogButton.appendChild(document.createTextNode('Log')); lobjViewLogButton.addEventListener('click', showMafiaLogBox, false); // Show resume or paused based on if we are running or not. updateMastheadMenu(); } function customizeStats(){ // Don't watch the stats area while we're making changes to it. setListenStats(false); // Make bank icon clickable for instant banking var bankLinkElt = xpathFirst('.//div[@id="game_stats"]//div[@id="cash_stats_'+cities[city][CITY_ALIAS]+'"]/h4/a[@id="mwap_bank"]', statsrowElt); var bankElt = xpathFirst('.//div[@id="game_stats"]//div[@id="cash_stats_'+cities[city][CITY_ALIAS]+'"]/h4/text()', statsrowElt); if(bankElt && !bankLinkElt){ bankLinkElt = makeElement('a', null, {'id': 'mwap_bank', 'title': 'Click to bank immediately.'}); bankElt.parentNode.insertBefore(bankLinkElt, bankElt); bankLinkElt.appendChild(bankElt); bankLinkElt.addEventListener('click', quickBank, false); } // Make energy icon & text clickable for mini pack. var nrgLinkElt = document.getElementById('mwap_nrg'); var nrgElt = xpathFirst('./div[@class="mw_header"]//div[@class="mid_row_text energy_text_bg" and contains(text(), "ENERGY")]', statsrowElt); if(!nrgElt) nrgElt = xpathFirst('.//div[@id="game_stats"]//h4[@class="energy" and contains(text(), "Energy")]', statsrowElt); if(!nrgElt) nrgElt = xpathFirst('.//div[@id="game_stats"]//span[@class="stat_title" and contains(text(),"Energy")]', statsrowElt); if(nrgElt && !nrgLinkElt){ if(isGMChecked('autoMission')){ var nrgTitle = 'Spend Energy ON. '; nrgElt.style.color="#33FF00"; // green } else { // if(below_energy_floor_needs_Identifying){ // var nrgTitle = 'Spend Energy ON, below spend floor. '; // nrgElt.style.color="#FFCC00"; // orange/yellow // } else { var nrgTitle = 'Spend Energy OFF. '; nrgElt.style.color="#FF0000"; // red } //nrgTitle += ' NO LONGER FIRES ENERGY PACK. '; selectedTierValue = GM_getValue('selectTier','0.0').split('.'); masteryCity = parseInt(selectedTierValue[0]); masteryTier = parseInt(selectedTierValue[1]); if( (masteryCity == 0) && ( (masteryTier == 0 ) || ( masteryTier == undefined ) ) ){ nrgTitle += ' Mastering- Turned OFF ' ; } else { nrgTitle += ' Mastering-'+ cities[masteryCity][CITY_NAME] +', District/Region-'+ masteryTier+' '+ missionTabs[masteryCity][masteryTier - 1] ; } nrgElt.style.textDecoration="underline"; nrgLinkElt = makeElement('a', null, {'id':'mwap_nrg', 'title':nrgTitle}); nrgElt.parentNode.insertBefore(nrgLinkElt, nrgElt); nrgLinkElt.appendChild(nrgElt); nrgLinkElt.addEventListener('click', toggleNrgSpend, false); var mepakLink = document.getElementById('mwap_epack'); if(!mepakLink){ var timeLeftPack = getHoursTime('miniPackTimer'); if(timeLeftPack == 0 || timeLeftPack == undefined) var miniPackTitle = 'Mini-Pack available now. '; else var miniPackTitle = timeLeftPack+' until Mini-Pack is available. '; miniPackTitle += ' Click to attempt to fire immediately.'; if(isGMChecked('mastheadOnTop')) var ttop = '0px' ; else var ttop = '60px' ; mepakLink = makeElement('a', null, {'id':'mwap_Fire_epak', 'title':miniPackTitle, 'style':'position:absolute; top:'+ttop+'; right:384px;'} ); if(timeLeftPack == 0 || timeLeftPack == undefined){ var m_epak_icon = mini_Epak_ready ; mepakLink.innerHTML=mini_Epak_ready; var mepk = ('EP') ; } else { var m_epak_icon = mini_Epak_wait ; mepakLink.innerHTML=mini_Epak_wait; var mepk = ('na') ; } mepakParent = nrgLinkElt.parentNode; mepakParent.insertBefore(mepakLink, mepakParent.childNodes[2]); mepakLink.appendChild(document.createTextNode(mepk)); mepakLink.addEventListener('click', miniPackForce, false); } } // Make stamina text & icon pointable for showing. var stamLinkElt = document.getElementById('mwap_stam'); var stamElt = xpathFirst('./div[@class="mw_header"]//div[@class="mid_row_text stamina_text_bg" and contains(text(), "STAMINA")]', statsrowElt); if(!stamElt) stamElt = xpathFirst('.//div[@id="game_stats"]//h4[contains(text(), "Stamina")]', statsrowElt); if(!stamElt) stamElt = xpathFirst('.//div[@id="game_stats"]//span[@class="stat_title" and contains(text(),"Stamina")]', statsrowElt); if(stamElt && !stamLinkElt){ if(isGMChecked('staminaSpend')){ var stamTitle = 'Spend Stamina ON. '; stamElt.style.color="#33FF00"; // green } else { var stamTitle = 'Spend Stamina OFF. '; stamElt.style.color="#FF0000"; // red } stamTitle += 'Minimum Stamina for auto-healing set at '+ GM_getValue('stamina_min_heal')+' points.'; var smode = GM_getValue('staminaSpendHow') ; stamTitle += ' Stamina Spend Mode: '+ staminaSpendChoices[smode] ; stamElt.style.textDecoration="underline"; stamLinkElt = makeElement('a', null, {'id':'mwap_stam', 'title':stamTitle}); stamElt.parentNode.insertBefore(stamLinkElt, stamElt); stamLinkElt.appendChild(stamElt); stamLinkElt.addEventListener('click', toggleStamSpend, false); } // Make health icon&text clickable for instant healing. var hospitalElt = xpathFirst('.//div[@id="game_stats"]//a[@class="heal_link" or @class="heal_link vt-p"]', statsrowElt); var healLinkElt = document.getElementById('mwap_heal'); var healElt = xpathFirst('./div[@class="mw_header"]//div[@class="mid_row_text health_text_bg" and contains(text(), "HEALTH")]', statsrowElt); if(!healElt) healElt = xpathFirst('.//div[@id="game_stats"]//h4[@class="health" and contains(text(), "Health")]', statsrowElt); if(!healElt) healElt = xpathFirst('.//div[@id="game_stats"]//span[@class="stat_title" and contains(text(),"Health")]', statsrowElt); if(healElt){ if(!healLinkElt){ healElt.style.color="#FF0000"; healElt.style.textDecoration="underline"; healElt.style.display="inline-block"; healLinkElt = makeElement('a', null, {'id':'mwap_heal', 'title':'Click to heal immediately.'}); healElt.parentNode.insertBefore(healLinkElt, healElt); healLinkElt.appendChild(healElt); healLinkElt.style.textDecoration="none"; var newLink = document.getElementById('mwap_toggleheal'); if(!newLink){ if(!isGMChecked('autoHeal')){ newLinkTitle='autoHeal unchecked'; } else { if(GM_getValue('staminaSpendHow') == STAMINA_HOW_FIGHTROB) newLinkTitle='autoHeal checked BUT OVERRULED - healing in '+ locations[GM_getValue('healLocation')] +' when health falls below '+GM_getValue('healthLevel')+'.'; else newLinkTitle='autoHeal checked - healing in '+ locations[GM_getValue('healLocation')] +' when health falls below '+GM_getValue('healthLevel')+'.'; } newLink = makeElement('a', null, {'id':'mwap_toggleheal', 'title':newLinkTitle}); if(!isGMChecked('autoHeal')){ newLink.innerHTML=healOffIcon; } else { if(GM_getValue('staminaSpendHow') == STAMINA_HOW_FIGHTROB) newLink.innerHTML=healOnHoldIcon; else newLink.innerHTML=healOnIcon; } newLink.style.padding="5px 0px 0px 8px"; newLink.style.position="absolute"; healParent = healLinkElt.parentNode; healParent.insertBefore(newLink, healParent.childNodes[2]); newLink.addEventListener('click', toggleHeal, false); } } // Substitute the "hide" icon if currently hiding in the hospital. var hidingInHospital = /transparent url/i.test(healElt.getAttribute('style')); if(health < 20 && isGMChecked('hideInHospital')){ if(!hidingInHospital){ healElt.style.background = 'transparent url('+ stripURI(hideIcon)+') no-repeat scroll 0 50%'; healElt.title = 'Currently hiding in the hospital. Click to heal immediately.'; } } else if(hidingInHospital){ healElt.style.background = ''; healElt.title = 'Click to heal immediately.'; } // Make instant heal work without switching pages. if(hospitalElt) healLinkElt.addEventListener('click', quickHeal, false); } // Blink maxed out energy or stamina. energyElt.style.textDecoration = (energy == maxEnergy)? 'blink' : 'none'; staminaElt.style.textDecoration = (stamina == maxStamina)? 'blink' : 'none'; // Blink dangerous health levels. healthElt.style.textDecoration = (health > 19 && health < 29) ? 'blink' : 'none'; // Once health is below 20, set the timer (this is for the conditional healing logic) if(isGMChecked('forceHealOpt5') && health < 20 && GM_getValue('healWaitStarted') != true){ setGMTime('healWaitTime', '05:00'); GM_setValue('healWaitStarted', true); } setListenStats(true); } function toggleHeal(){ if(!document.getElementById('mwap_toggleheal')) return; if(isGMChecked('autoHeal')){ GM_setValue('autoHeal', 0); document.getElementById('mwap_toggleheal').innerHTML=healOffIcon; document.getElementById('mwap_toggleheal').title = 'autoHeal unchecked'; addToLog('healOffIcon Icon', 'autoHeal turned OFF by User'); } else { GM_setValue('autoHeal', 'checked'); if(GM_getValue('staminaSpendHow') == STAMINA_HOW_FIGHTROB){ document.getElementById('mwap_toggleheal').innerHTML=healOnHoldIcon; document.getElementById('mwap_toggleheal').title = 'autoHeal checked BUT OVERRULED - healing in '+ locations[GM_getValue('healLocation')] +' when health falls below '+GM_getValue('healthLevel')+'.'; addToLog('healOnHoldIcon Icon', 'autoHeal turned ON by User, but overruled'); } else { document.getElementById('mwap_toggleheal').innerHTML=healOnIcon; document.getElementById('mwap_toggleheal').title = 'autoHeal checked - healing in '+ locations[GM_getValue('healLocation')] +' when health falls below '+GM_getValue('healthLevel')+'.'; addToLog('healOnIcon Icon', 'autoHeal turned ON by User'); } } } function toggleNrgSpend(){ if(isGMChecked('autoMission')){ GM_setValue('autoMission', 0); addToLog('info Icon', 'Energy Spend turned OFF by User'); } else { GM_setValue('autoMission', 'checked'); addToLog('info Icon', 'Energy turned ON by User'); } update_nrg_stam(); } function toggleStamSpend(){ if(isGMChecked('staminaSpend')){ GM_setValue('staminaSpend', 0); addToLog('info Icon', 'staminaSpend turned OFF by User'); } else { GM_setValue('staminaSpend', 'checked'); addToLog('info Icon', 'staminaSpend turned ON by User'); } update_nrg_stam(); } function quickHeal(healAction, useBackUp){ colorDEBUG('quickHeal healAction: '+ healAction, cpu); if(timeLeft('healTimer')){ colorDEBUG('healTimer has NOT gone off yet - You can not heal so fast', cre); return; } else { colorDEBUG('healTimer has GONE off - You can try to heal', cgr); setGMTime('healTimer','00:05'); } if(isNaN(healAction)) healAction=0; var healLocation; Autoplay.delay = 2000; var aSync = false; if(healAction!=2) aSync=true; if(healAction){ healLocation = parseInt(GM_getValue('healLocation', NY)); } else { healLocation = city; } if(healLocation==NY || useBackUp){ var healElt = makeElement('a', null, {'onclick':'return do_ajax("'+ (aSync ? SCRIPT.ajaxIDAsync : SCRIPT.ajaxIDSync)+'","'+ SCRIPT.controller+'hospital'+ SCRIPT.action+'heal'+ SCRIPT.city + (healLocation + 1)+'&xcity=1", 1, 1, 0, 0); return false;'}); } else { if(healLocation <= cities.length-1 && city != healLocation){ if(!healAction) return; Autoplay.fx = function(){ goLocation(healLocation); }; Autoplay.start(); return; } var healElt = makeElement('a', null, {'onclick':'return do_ajax("'+ (aSync ? SCRIPT.ajaxIDAsync : SCRIPT.ajaxIDSync)+'","'+ SCRIPT.controller+'hospital'+ SCRIPT.action+'heal'+ SCRIPT.city + (healLocation + 1)+'", 1, 1, 0, 0); return false;'}); } if(aSync){ createAjaxPage(false, 'quick heal'); clickElement(healElt); DEBUG('Clicked to quickheal in '+cities[healLocation][CITY_NAME]+'- async.'); return true; } else { createAjaxPage(true); Autoplay.fx = function(){ clickAction = 'quick heal'; clickElement(healElt); DEBUG('Clicked to quickheal in '+cities[healLocation][CITY_NAME]+'- sync.'); }; Autoplay.start(); return true; } } function quickBank(bankCity, amount){ var byUser = false; // Handle user-click action if(isNaN(amount)){ if(isNaN(bankCity)){ bankCity = city; byUser = true; } cashElt = document.getElementById('user_cash_'+ cities[bankCity][CITY_ALIAS]); if(cashElt){ amount = parseCash(cashElt.innerHTML); } else { amount = cities[bankCity][CITY_CASH]; } } // Check vault status & get the URL if(bankCity == LV){ if(GM_getValue('vaultHandling', 0)){ var vaultSpace = parseInt(GM_getValue('vaultSpace','0')); //colorDEBUG('VaultStatus: '+ GM_getValue('vaultHandling', 0)+' - '+vaultSpace); if(vaultSpace <= 0){ if(byUser) addToLog('info Icon', 'Your vault appears to be full, rechecking...'); checkPropertyStatus(LV); return false; } amount = (amount > vaultSpace) ? vaultSpace : amount; } var depositUrl = "xw_controller=propertyV2&xw_action=doaction&xw_city=5&doaction=ActionBankDeposit&building_type=6&city=5&amount=" + amount; } else { var depositUrl = "xw_controller=bank&xw_action=deposit_all&xw_city=" + (bankCity + 1); } // If cash being deposited is greater than 100 billion, do NOT quick-bank! if(amount > 100000000000){ if(byUser) addToLog('updateBad Icon', 'Depositing '+ cities[bankCity][CITY_CASH_SYMBOL] + makeCommaValue(amount) + '!?! HELL NO! Sink it from the banking page.'); quickBankFail = true; return false; } // Do not quick-bank if city has changed if(city != bankCity){ DEBUG('Switching city too fast, not quick-banking.'); return false; } var ajaxID = createAjaxPage(false, 'quick deposit', bankCity); var elt = makeElement('a', null, {'onclick':'return do_ajax("'+ ajaxID+'","remote/html_server.php?'+ depositUrl+'", 1, 1, 0, 0); return false;'}); clickElement(elt); DEBUG('Clicked to quickbank.'); return false; } function customizeHome(){ var oDiv = document.getElementById('snapi_zbar'); if(oDiv) oDiv.parentNode.parentNode.removeChild(oDiv.parentNode); oDiv = document.getElementById('mw_like_button'); if(oDiv) oDiv.style.display = "none"; odiv = xpathFirst('.//iframe[@name="mafiawars_zbar"]'); if(oDiv){ oDiv.style.display = "none"; if(oDiv.parentNode) oDiv.parentNode.removeChild(oDiv); } var oDivs = $x('.//div[contains(@id,"cpa") and contains(@id,"banner")]'); for(i=0;iProjected XP needed = '+ parseInt(ptsNeeded); var packParentElt = document.getElementById('clock_energy_pack'); if(packParentElt){ var descElt = makeElement('div', null, {'style':'float:left; padding: 2px 10px 0px 0px; font-size: 10px;'}); descElt.innerHTML = txt; packParentElt.insertBefore(descElt, packParentElt.firstChild); } } else { energyPack = false; } return true; } } function getPlayerStats(){ var statTable = xpathFirst('.//table[contains(.,"Attack:") and contains(.,"Defense:")]', innerPageElt); // Fetch defense and attack values from profile if(statTable){ DEBUG('Fetching stats from profile page'); // Attack var curAttackRow = xpathFirst('.//tr[contains(.,"Attack:")]', statTable); if(curAttackRow && curAttackRow.innerHTML.match(/>\s*(\d+)/)){ curAttack = parseInt(RegExp.$1); GM_setValue('curAttack', curAttack); } // Defense var curDefenseRow = xpathFirst('.//tr[contains(.,"Defense:")]', statTable); if(curDefenseRow && curDefenseRow.innerHTML.match(/>\s*(\d+)/)){ curDefense = parseInt(RegExp.$1); GM_setValue('curDefense', curDefense); } if(isUndefined(curAttack) || isUndefined(curDefense)){ addToLog('info icon', 'Current status attributes cannot be detected, turning off auto-stat.'); GM_setValue('autoStat', 0); } } } function getPlayerEquip(){ if(!onFightTab() && !onInventoryTab() && !onLootTab()) return; var eltAttackStrength = xpathFirst('.//div[@class="fightbar_group_stat"]//img[contains(@alt, "Mafia Attack Strength")]', innerPageElt); if(eltAttackStrength){ prevAttackEquip = curAttackEquip; curAttackEquip = parseInt(eltAttackStrength.parentNode.childNodes[1].nodeValue.replace(',', '')); GM_setValue('curAttackEquip', curAttackEquip); } var eltDefenseStrength = xpathFirst('.//div[@class="fightbar_group_stat"]//img[contains(@alt, "Mafia Defense Strength")]', innerPageElt); if(eltDefenseStrength){ prevDefenseEquip = curDefenseEquip; curDefenseEquip = parseInt(eltDefenseStrength.parentNode.childNodes[1].nodeValue.replace(',', '')); GM_setValue('curDefenseEquip', curDefenseEquip); } if(isUndefined(curAttackEquip) || isUndefined(curDefenseEquip)) DEBUG('Current equipment attributes cannot be detected.'); } function customizeProfile(){ // Make sure we're on a profile. var statsTable = xpathFirst('.//td[@class="stats_left"]', innerPageElt); if(!statsTable) return false; // Fetch Player Stats getPlayerStats(); // FIXME: Need to rewrite buildAnchor, need to make it more flexible this.buildAnchor = function (Options){ //Options.URLSegment = common portions if URL //Options.href = allow for full control of href //Options.clickEvent = function //Options.title = flyout text //Options.AnchorText = text inside Anchor var buildAnchorOptions = {}; if(Options.URLSegment){ buildAnchorOptions.href='http://mwfb.zynga.com/mwfb/remote/html_server.php?'+Options.URLSegment; } else if(Options.href){ buildAnchorOptions.href = Options.href; } else { buildAnchorOptions.href='#'; } if(!Options.clickEvent && Options.URLSegment){ buildAnchorOptions.onclick ='return do_ajax(\'inner_page\', \'/remote/html_server.php?'+Options.URLSegment+'\', 1, 1, 0, 0); return false; '; } if(Options.id){ buildAnchorOptions.id=Options.id; } var anchorElt = makeElement('a', statsDiv, buildAnchorOptions); if(Options.AnchorText){ anchorElt.appendChild(document.createTextNode(Options.AnchorText)); } if(Options.clickEvent){ anchorElt.addEventListener('click', Options.clickEvent, false); } return anchorElt; }; var statsDiv = xpathFirst('.//a[contains(., "Sucker Punch")]/..', innerPageElt); if(statsDiv){ // On another player's profile page. Add extra options. var tabElt = xpathFirst('.//li[contains(@class, "tab_on")]//a[contains(text(), "Profile")]', innerPageElt); if(tabElt){ var remoteuserid; var remotefbid; var tmpKey; var cbKey; if(tabElt.getAttribute('onclick').match(/tmp=([\d,a-z]+)&cb=([\d,a-z]+)&user=p\|(\d+)/)){ tmpKey = 'tmp='+RegExp.$1+'&'; cbKey = 'cb='+RegExp.$2+'&'; remoteuserid = 'p|'+RegExp.$3; } if(!remoteuserid && tabElt.getAttribute('onclick').match(/user=p\|(\d+)/)) remoteuserid = 'p|'+RegExp.$1; // This code is to grab the facebook id for this profile if(m = /xw_controller=robbing.*?target=([0-9]+)/.exec(document.getElementById('inner_page').innerHTML)){ remotefbid = m[1]; } if(m = /xw_controller=stats.*?user=([0-9]+)/.exec(document.getElementById('inner_page').innerHTML)){ remotefbid = m[1]; } if(m = /xw_action=gift_wishlist.*?user=([0-9]+)/.exec(document.getElementById('inner_page').innerHTML)){ remotefbid = m[1]; } if(m = /q([0-9]+)_(\d+)\.jpg/.exec(document.getElementById('inner_page').innerHTML)){ remotefbid = m[1]; } if(document.getElementsByClassName('fightres_image').length > 1){ var fight_image = /(\d+)_(\d+)_q.jpg/.exec(document.getElementsByClassName('fightres_image')[1].innerHTML); remotefbid = fight_image[1]; } if(m = /xw_controller=VegasSlots.+?friend_id=([0-9]+)/i.exec(document.getElementById('inner_page').innerHTML)){ remotefbid = m[1]; } if(m = /([0-9]+)_(\d+)\_q.jpg/.exec(document.getElementById('inner_page').innerHTML)){ remotefbid = m[1]; } if((m=/user%2522.*?%2522([0-9A-Za-z%]+)%2522/.exec(document.getElementById('mainDiv').innerHTML)) || (m=/user%22.*?%22([0-9A-Za-z%]+)%22/.exec(document.getElementById('mainDiv').innerHTML))){ remotefbid = atob(m[1].replace(/%253D/g,'=').replace(/%3D/g,'=')); } if(!tmpKey && tabElt.getAttribute('onclick').match(/tmp=([\d,a-z]+)&/)){ tmpKey = 'tmp='+RegExp.$1+'&'; } if(!cbKey && tabElt.getAttribute('onclick').match(/cb=([\d,a-z]+)&/)){ cbKey = 'cb='+RegExp.$2+'&'; } DEBUG('Profile: Mafia Wars ID: '+ remoteuserid+' Facebook ID: '+ remotefbid); var userid = remoteuserid.replace('p|',''); // See if this player is in our mafia. var removeElt = xpathFirst('.//a[contains(., "Remove from Mafia")]', statsDiv); // Show if Alive/Dead if(!running && !removeElt){ var titleElt = xpathFirst('./div[@class="title stats_title"]', innerPageElt); if(titleElt){ titleElt.setAttribute('style', 'background: black;'); } var ajaxID = createAjaxPage(false, 'icecheck profile', titleElt); var elt = xpathFirst('.//a[contains(., "Add to Hitlist")]', innerPageElt); var iceCheckElt = makeElement('a', null,null); var newClick = elt.getAttribute('onclick'); newClick = newClick.replace('inner_page',ajaxID); iceCheckElt.setAttribute('onclick', newClick); clickElement(iceCheckElt); } // Don't continue if buttons already there if(document.getElementById('where_are_my_links')) return true; var rDisplay = false; // Explain the buttons makeElement('a', statsDiv, {'id':'where_are_my_links', 'href':'javascript:alert("Due to the way Mafia Wars links to Facebook there are times where PS MWAP cannot find the Facebook profile ID. In those situations PS MWAP will not display buttons that require that ID. You can make the Facebook ID available by refreshing the profile page.");'}).appendChild(document.createTextNode('Where are my links?')); // This is a refresh page button statsDiv.appendChild(document.createTextNode(' | ')); makeElement('a', statsDiv, {'href':'http://facebook.mafiawars.com/mwfb/remote/html_server.php?xw_controller=stats&xw_action=view&xw_city=1&user='+ remoteuserid}).appendChild(document.createTextNode('Refresh this profile!')); rDisplay = true; if(remotefbid){ // Facebook profile if(rDisplay) statsDiv.appendChild(document.createTextNode(' | ')); makeElement('a', statsDiv, {'href':'http://www.facebook.com/profile.php?id='+ remotefbid,'target':'_blank'}).appendChild(document.createTextNode('Facebook Profile')); statsDiv.appendChild(document.createTextNode(' | ')); // Add as Facebook friend makeElement('a', statsDiv, {'href':'http://www.facebook.com/addfriend.php?id='+ remotefbid,'target':'_blank'}).appendChild(document.createTextNode('Add as Friend')); rDisplay = true; } if(removeElt){ // Promote if(rDisplay) statsDiv.appendChild(document.createTextNode(' | ')); //href Example:http://mwfb.zynga.com/mwfb/remote/html_server.php?xw_controller=group&xw_action=view&xw_city=4&tmp=9c2d83eaf30b28fa29319feb437e4f7e&cb=18309240931265744553&promote=yes&uid=48608018 //OnClick Example: return do_ajax('inner_page', 'remote/html_server.php?xw_controller=group&xw_action=view&xw_city=4&tmp=9c2d83eaf30b28fa29319feb437e4f7e&cb=18309240931265744553&promote=yes&uid=48608018', 1, 1, 0, 0); return false; this.buildAnchor( { 'AnchorText':'Promote', 'URLSegment': 'xw_controller=group&'+ 'xw_action=view&'+ 'xw_city='+ (city + 1)+'&'+ tmpKey+ cbKey+ 'promote=yes&'+ 'pid='+ remoteuserid}); rDisplay = true; } if(rDisplay) makeElement('br', statsDiv,{}); rDisplay = false; if(removeElt){//Add or Remove from War List var isOnWarList = (getSavedList('autoWarTargetList').indexOf(userid) != -1); // In my mafia. Show options to add/remove from war list. this.buildAnchor( { 'AnchorText':isOnWarList?'Remove from War List':'Add to AutoWar List', 'id':userid, 'title':'In the settings box, under the mafia tab\nIf you have selected war friends from a list\nupdates the friends ids in the box', 'clickEvent':isOnWarList?clickWarListRemove:clickWarListAdd }); rDisplay = true; } // Add to AutoHitlist if(rDisplay) statsDiv.appendChild(document.createTextNode(' | ')); var isOnAutoHitList = (getSavedList('pautoHitOpponentList').indexOf(userid) != -1); this.buildAnchor( { 'AnchorText':isOnAutoHitList?'Remove from AutoHit List':'Add to AutoHit List', 'id':userid, 'title':'In the settings box, under the stamina tab\nIf you have selected hitlist opponents \nHitlist these opponents:', 'clickEvent':isOnAutoHitList?clickAutoHitListRemove:clickAutoHitListAdd }); rDisplay = true; if(!removeElt){// Not in mafia. Show options to add/remove from fight lists. if(rDisplay) statsDiv.appendChild(document.createTextNode(' | ')); rDisplay = true; var isOnFightList = (getSavedList('pfightlist').indexOf(userid) != -1); this.buildAnchor( { 'AnchorText':isOnFightList?'Remove from Fight List':'Add to AutoFight List', 'id':userid, 'title':'In the settings box, under the stamina tab\nIf you have selected fight specific opponents\nFight these opponents:', 'clickEvent':isOnFightList?clickFightListRemove:clickFightListAdd }); } if(rDisplay) makeElement('br', statsDiv,{}); if(removeElt){//Job Help this.buildAnchor( { 'AnchorText':'NY - Give help', 'URLSegment': 'xw_controller=job&'+ 'xw_action=give_help&'+ 'xw_city='+ (city + 1)+'&'+ tmpKey+ cbKey+ 'target_id='+remoteuserid+'&'+ 'job_city=1' }); statsDiv.appendChild(document.createTextNode(' | ')); makeElement('br', statsDiv,{}); if(remotefbid){ this.buildAnchor( { 'AnchorText':'Mafia Gift', 'title':'Requires that you set the giftkey in advance, see documentation', 'href':'http://www.spockholm.com/mafia/?id='+remotefbid }); statsDiv.appendChild(document.createTextNode(' | ')); } } } } return true; } ////////////////////////////////////////////////////////////////////////////////////////// // Return the job mastery level function getBrazilJobMastery(jobRow, newJobs){ // Logic for new job layout if(newJobs){ var mastery = 100; if( jobRow.innerHTML.untag().match(/(\d+)%/i) ){ mastery = parseInt(RegExp.$1); return mastery; } } // Locked jobs are mastered too if(isJobLocked(jobRow)){ DEBUG('NOT newjob, locked job, returning mastered, to allow to next tier?'); return 100; } // if mastered show it, or show mastery if(/Mastered/i.test(jobRow.innerHTML) ){ return 100; } else if(jobRow.innerHTML.match(/Job\s+Mastery\s+(\d+)%/i) || jobRow.innerHTML.match(/>(\d+)%/i)){ return parseInt(RegExp.$1); } // Get the job with the highest percentage in choice point jobs var divElts = $x('.//td[@class="job_name job_no_border"]//div[contains(text(),"%")]', jobRow); if(divElts){ var iLength = divElts.length; var masteryPct = (iLength == 1) ? 100 : 0; for (var i = 0; i < iLength; ++i){ if(divElts[i].innerHTML.match(/(\d+)%/) && parseInt(RegExp.$1) > masteryPct){ masteryPct = parseInt(RegExp.$1); } } return parseInt(masteryPct); } DEBUG('No mastery items found. Assuming 0% mastery level.'); return 0; } // Return the job mastery level function getJobMastery(jobRow, newJobs){ // Logic for new job layout if(newJobs){ var mastery = 100; if(isJobFight(jobRow) && (isGMChecked('skipfight') ) ){ return 100; } if(jobRow.innerHTML.untag().match(/>(\d+)%\s+Job\s+Mastery/i) || jobRow.innerHTML.untag().match(/(\d+)%/i) || jobRow.innerHTML.match(/Job\s+Mastery\s+(\d+)%/i) || jobRow.innerHTML.match(/>(\d+)%/i)){ mastery = parseInt(RegExp.$1); } else { if(jobRow.innerHTML.untag().match(/margin-right:\s+(\d+)%/i)){ mastery = 100-parseInt(RegExp.$1); } } return mastery; } // Locked jobs are mastered too if(/Mastered/i.test(jobRow.innerHTML) || isJobLocked(jobRow)){ return 100;} else if(jobRow.innerHTML.match(/Job\s+Mastery\s+(\d+)%/i) || jobRow.innerHTML.match(/>(\d+)%/i)){ mastery = parseInt(RegExp.$1); return mastery; } // Get the job with the highest percentage in choice point jobs var divElts = $x('.//td[@class="job_name job_no_border"]//div[contains(text(),"%")]', jobRow); if(divElts){ var iLength = divElts.length; var masteryPct = (iLength == 1) ? 100 : 0; for (var i = 0; i < iLength; ++i){ if(divElts[i].innerHTML.match(/(\d+)%/) && parseInt(RegExp.$1) > masteryPct){ masteryPct = parseInt(RegExp.$1); } } return parseInt(masteryPct); } DEBUG('No mastery items found. Assuming 0% mastery level.'); return 0; } // Set the next job to be mastered for mastery job options function jobMastery(element, newJobs){ if(isGMChecked('repeatJob')) return; var selectMission = parseInt(GM_getValue('selectMission', 1)); var currentJob = missions[selectMission][MISSION_NAME]; var jobno = missions[selectMission][MISSION_NUMBER]; var tabno = missions[selectMission][MISSION_TAB]; var cityno = missions[selectMission][MISSION_CITY]; if(city != cityno || !onJobTab(tabno)) return; var currentJobRow = getJobRow(currentJob, element); // Calculate tier mastery. var tierLevel = 0; var jobPercentComplete = -1; if(currentJobRow) jobPercentComplete = getJobMastery(currentJobRow, newJobs); DEBUG('Job is '+jobPercentComplete+' % complete'); var currentJobMastered = (jobPercentComplete == 100); if(currentJobRow){ if(newJobs && currentJobRow.className.match(/mastery_level_(\d+)/i)){ tierLevel = RegExp.$1; } else if(currentJobRow.innerHTML.match(/level (\d+)/i)){ tierLevel = RegExp.$1; } } var tierPercent = 0; var jobCount = 0; var firstUnmastered = selectMission; var firstFound = false; for (var i = 0, iLength = missions.length; i < iLength; i++){ // Only get the jobs from this city tier if(city == missions[i][MISSION_CITY] && tabno == missions[i][MISSION_TAB]){ var thisJobRow = getJobRow(missions[i][MISSION_NAME]); if(thisJobRow){ var masteryLevel = getJobMastery(thisJobRow, newJobs); //DEBUG('Masterylevel for '+missions[i][MISSION_NAME]+' : '+masteryLevel); if( (isGMChecked('skipfight') && !isJobFight(thisJobRow) ) || !isGMChecked('skipfight') ){ tierPercent += masteryLevel; jobCount++; // Get the first unmastered job on this tier if(!firstFound && masteryLevel < 100){ firstFound = true; firstUnmastered = i; DEBUG('firstUnmastered job is '+missions[i][MISSION_NAME]); } } } } } if(jobCount > 0){ tierPercent = Math.floor(tierPercent / jobCount); } if(GM_getValue('tierCompleteStatus') != tierLevel+'|'+ tierPercent){ GM_setValue('tierCompleteStatus', tierLevel+'|'+ tierPercent); DEBUG('Job tier level '+ tierLevel+' is '+ tierPercent+'% complete.'); } // Calculate job mastery DEBUG("Checking current job mastery."); if(currentJobMastered || jobPercentComplete == -1){ var jobList = getSavedList('jobsToDo'); if(jobList.length == 0){ DEBUG("There are no more jobs in the to-do list."); if(currentJobMastered) addToLog('info Icon', 'You have mastered '+ currentJob+'.'); else addToLog('info Icon', 'Job '+ currentJob+' is not available.'); // allow progression to next tier if skipping stamina jobs if( (tierPercent == 100) || (isGMChecked('skipfight')) ){ // Find the first job of the next tier. // NOTE: This assumes that the missions array is sorted by city and then by tier. var nextTierJob; for (i = selectMission + 1, iLength=missions.length; i < iLength; ++i){ if(missions[i][MISSION_CITY] != cityno){ nextTierJob = i; addToLog('info Icon', 'You have mastered the final job tier in ' + cities[cityno][CITY_NAME]+'! Moving to the next tier in ' + cities[missions[nextTierJob][MISSION_CITY]][CITY_NAME]+'.'); break; } if(missions[i][MISSION_TAB] != tabno){ nextTierJob = i; addToLog('info Icon', 'Current job tier is mastered. Moving to next tier in '+ cities[cityno][CITY_NAME]+'.'); break; } } if(!nextTierJob){ addToLog('info Icon', 'You have mastered all jobs!'); } else { GM_setValue('selectMission', nextTierJob); addToLog('info Icon', 'Job switched to '+ missions[GM_getValue('selectMission', 1)][MISSION_NAME]+'.'); } } else { GM_setValue('selectMission', firstUnmastered); addToLog('info Icon', 'Job switched to '+ missions[GM_getValue('selectMission', 1)][MISSION_NAME]+'.'); } } else { DEBUG("There are jobs in the to-do list."); } } else { DEBUG('Job is not mastered. Checking percent of mastery.'); if(GM_getValue('jobCompleteStatus') != (currentJob+'|'+ String(jobPercentComplete))){ GM_setValue('jobCompleteStatus', (currentJob+'|'+ String(jobPercentComplete))); DEBUG(currentJob+' is '+ jobPercentComplete+'% complete.'); } } } ////////////////////////////////////////// function customizeBrazilJobs(){ var brazilJobsPage = xpathFirst('.//div[@id="brazil_jobs"]', innerPageElt); if(!brazilJobsPage){ return false; } var currentTab = currentJobTab(); if(!currentTab) return false; var districtLinksContainer = xpathFirst('.//div[(@id="brazil_district_'+ currentBrazilDistrict+'")]', innerPageElt); // if(!districtLinksContainer){ // var districtLinksContainer = xpathFirst('.//div[@id="brazil_jobs_district_link"]', innerPageElt); // } var brazilJobs = $x('.//div[@class="job"]', districtLinksContainer); if(!brazilJobs) var brazilJobs = $x('.//div[@id="brazil_jobs"]//div[@class="job"]', innerPageElt); if(!brazilJobs || brazilJobs.length == 0) return false; DEBUG('Found '+ brazilJobs.length+' new '+ cities[city][CITY_NAME] +' jobs in customize '+ cities[city][CITY_NAME] +' jobs.'); var availableJobs = eval('({0:{},1:{},2:{},3:{},4:{},5:{},6:{},7:{},8:{}})'); var masteredJobs = eval('({0:{},1:{},2:{},3:{},4:{},5:{},6:{},7:{},8:{}})'); try { availableJobs = eval('('+ GM_getValue('availableJobs')+')'); masteredJobs = eval('('+ GM_getValue('masteredJobs')+')'); } catch (ex){} availableJobs[city][currentTab] = []; masteredJobs[city][currentTab] = []; // Display an experience to energy payoff ratio for each job. var bestJobs = [], worstJobs = []; var bestRatio = 0, worstRatio = 10; var bestStamJobs = [], worstStamJobs = []; var bestStamRatio = 0, worstStamRatio = 10; var masteryList = getSavedList('masteryJobsList'); var masteredJobsCount = 0; var jobsFound = 0; DEBUG('Customizing Brazil Job Page : Process '+brazilJobs.length+' found jobs ...'); for (var i = 0, iLength = brazilJobs.length; i < iLength; ++i){ var currentJob= brazilJobs[i]; var jobTitle = xpathFirst('.//div[@class="job_details clearfix"]//h4', currentJob); if(!jobTitle){ //colorDEBUG('Customizing Brazil Job Page : Job Title not Found ... skipping ...', cre); continue; } var jobName = xpathFirst('.//div[@class="job_details clearfix"]//h4', currentJob).innerHTML.clean().trim(); var jobCost = xpathFirst('.//ul[@class="uses clearfix"]', currentJob); var jobReward = xpathFirst('.//ul[@class="pays clearfix"]', currentJob); var reward = xpathFirst('.//ul[@class="pays clearfix"]/li[@class="experience"]', currentJob).innerHTML.clean().trim(); var jobPays = xpathFirst('.//ul[@class="pays clearfix"]/li[@class="cash_icon_jobs_7"]', currentJob); // innerhtml fails if link is not found if(jobPays){ var jobPays = xpathFirst('.//ul[@class="pays clearfix"]/li[@class="cash_icon_jobs_7"]', currentJob).innerHTML.clean().trim(); var money = jobPays ; } var jobAction = xpathFirst('.//a[contains(@id, "btn_dojob")]', currentJob); // Skip jobs not in missions array var jobMatch = missions.searchArray(jobName, 0)[0]; if(isNaN(jobMatch)){ if(!jobName.match(/Boss/i)) DEBUG(jobName+' not found in missions array. '); } jobsFound++; var jobPercentage = getBrazilJobMastery(currentJob, true); // Determine available jobs if(jobPercentage == 100){ if(masteryList.length > 0 && masteryList.indexOf(String(jobMatch)) != -1) masteredJobs[city][currentTab].push(jobMatch); masteredJobsCount++; } //if(jobPays) DEBUG('found job> '+ jobName+' needs '+ jobCost2+' energy, experience paid '+ reward+', $'+ jobPays+' cash, mastery '+ jobPercentage +'%' ); //else DEBUG('found job> '+ jobName+' needs '+ jobCost2+' energy, experience paid '+ reward+', no cash, mastery '+ jobPercentage+'%'); // Skip this for jobs without jobCost if(!jobCost) continue; // Skip this for jobs without cost var costElt = xpathFirst('.//li[@class="energy"]', jobCost); if(!costElt) costElt = xpathFirst('.//li[@class="stamina"]', jobCost); if(!costElt) continue; var cost; if(costElt.hasAttribute('current_value')) cost = parseInt(costElt.getAttribute('current_value')); else if(costElt.hasAttribute('base_value')) cost = parseInt(costElt.getAttribute('base_value')); //ignore job if we have do not have enough energy to perform the job, otherwise we set jobmastery to 100 to skip this job temporarely var skipCurrentJob = false; if(cost > energy){ skipCurrentJob = true; DEBUG('Required Energy: ' +cost+' - Current Energy: '+energy+'. Skipping'); } if(isJobLocked(jobAction) || skipCurrentJob){ if(isJobLocked(jobAction)) DEBUG('Skipping Job '+ jobName+' ('+ jobMatch+') : locked.'); if(skipCurrentJob) DEBUG('Skipping Job '+ jobName+' ('+ jobMatch+') : lack of energy.'); } else { availableJobs[city][currentTab].push(jobMatch); } var reward = 0; var ratio = 0; var xpTxt = ''; var expElt = xpathFirst('.//li[@class="experience"]', jobReward); if(expElt){ reward = parseInt(expElt.getAttribute("current_value")); ratio = Math.round (reward / cost * 100) / 100; xpTxt = ' ('+ ratio+')'; } var moneyTxt = ''; var mratio = 0; var money = 0; var moneyElt = xpathFirst('.//li[contains(@class, "cash_icon_jobs")]', jobReward); if(moneyElt){ money = parseCash(moneyElt.getAttribute("current_value")); mratio = Math.round(money / cost); if(mratio==0) mratio = Math.round(money / cost * 100)/100; moneyTxt = ' ('+ mratio+')'; } // Calculate time left for each job var timePerEnergy = isGMChecked('isManiac') ? 3 : 5; timePerEnergy = isGMChecked('hasHelicopter') ? timePerEnergy - .5: timePerEnergy; timePerEnergy = isGMChecked('hasGoldenThrone') ? timePerEnergy/2: timePerEnergy; var timeTxt = ' Time: 0 min'; if(cost > energy) timeTxt = ' Time: '+ getDecimalTime((cost - energy) * timePerEnergy); //playhere if(!xpathFirst('.//span[@id="timeLeft"]', costElt)) makeElement('span', costElt, {'id':'timeLeft','style':'color:green; font-size: 10px'}).appendChild(document.createTextNode(timeTxt)); if(!xpathFirst('.//span[@id="ratio_xp"]', expElt)) makeElement('span', expElt, {'id':'ratio_xp', 'style':'color:red; font-size: 12px;'}).appendChild(document.createTextNode(xpTxt)); var moneyElt = xpathFirst('.//li[contains(@class, "cash_icon_jobs")]', jobReward); if(!xpathFirst('.//span[@id="ratio_money"]', moneyElt)) makeElement('span', moneyElt, {'id':'ratio_money', 'style':'color:red; font-size: 12px;'}).appendChild(document.createTextNode(moneyTxt)); updateJobInfo(jobMatch, cost, reward, ratio); // Keep track of the best & worst payoffs for energy jobs. if(ratio > bestRatio){ bestRatio = ratio; bestJobs = [expElt]; } else if(ratio == bestRatio) bestJobs.push(expElt); if(ratio < worstRatio){ worstRatio = ratio; worstJobs = [expElt]; } else if(ratio == worstRatio) worstJobs.push(expElt); } var elt; // Highlight the best and worst energy jobs. if(worstRatio != bestRatio){ while (bestJobs.length){ elt = bestJobs.pop(); if(!xpathFirst('.//span[@id="job_best"]', elt)){ elt = makeElement('span', elt, {'id':'job_best', 'style':'color:#52E259; font-size: 12px;'}); elt.appendChild(document.createTextNode(' (BEST)')); var jobRow = elt.parentNode.parentNode.parentNode.parentNode; if(!running) jobRow.setAttribute('style', 'border:1px solid #52E259'); } } while (worstJobs.length){ elt = worstJobs.pop(); if(!xpathFirst('.//span[@id="job_worst"]', elt)){ elt = makeElement('span', elt, {'id':'job_worst', 'style':'color:#EC2D2D; font-size: 12px;'}); elt.appendChild(document.createTextNode(' (WORST)')); var jobRow = elt.parentNode.parentNode.parentNode.parentNode; if(!running) jobRow.setAttribute('style', 'border:1px solid #EC2D2D'); } } } GM_setValue('availableJobs', JSON.stringify(availableJobs)); GM_setValue('masteredJobs', JSON.stringify(masteredJobs)); // Set the job progress jobMastery(innerPageElt, true); tierMastery(jobsFound, masteredJobsCount, currentTab); return true; } function customizeVegasJobs(){ // Handle Las Vegas / Italy job layout var vegasJobs = $x('.//div[@id="map_panels"]//div[contains(@class, "job_info")]', innerPageElt); if(!vegasJobs || vegasJobs.length == 0) return false; DEBUG('Found '+ vegasJobs.length+' new '+ cities[city][CITY_NAME] +' jobs in customize '+ cities[city][CITY_NAME] +' jobs.'); var availableJobs = eval('({0:{},1:{},2:{},3:{},4:{},6:{},7:{},8:{}})'); var masteredJobs = eval('({0:{},1:{},2:{},3:{},4:{},6:{},7:{},8:{}})'); try { availableJobs = eval('('+ GM_getValue('availableJobs')+')'); masteredJobs = eval('('+ GM_getValue('masteredJobs')+')'); } catch (ex){} var currentTab = currentJobTab(); var currentTabPath = currentJobTabPath(); availableJobs[city][currentTab] = []; masteredJobs[city][currentTab] = []; // Display an experience to energy payoff ratio for each job. var bestJobs = [], worstJobs = []; var bestRatio = 0, worstRatio = 10; var bestStamJobs = [], worstStamJobs = []; var bestStamRatio = 0, worstStamRatio = 10; var masteryList = getSavedList('masteryJobsList'); var masteredJobsCount = 0; var jobsFound = 0; for (var i = 0, iLength = vegasJobs.length; i < iLength; ++i){ var currentJob = vegasJobs[i]; var jobName = xpathFirst('.//div[@class="job_title"]//h3', currentJob).innerHTML.clean().trim(); var jobCost = xpathFirst('.//div[@class="job_uses"]', currentJob); var jobReward = xpathFirst('.//div[@class="job_pays"]', currentJob); var jobAction = xpathFirst('.//a[contains(@class,"sexy_button_new")]', currentJob); // Skip jobs not in missions array var jobMatch = missions.searchArray(jobName, 0)[0]; if(isNaN(jobMatch)){ if(!jobName.match(/Boss/i)) DEBUG('--> jobInfo: '+jobName+' not found in missions array. '); continue; } jobsFound++; var isFightJob = isJobFight(currentJob); var jobPercentage = getJobMastery(currentJob, true); // Determine available jobs if(jobPercentage == 100){ if(masteryList.length > 0 && masteryList.indexOf(String(jobMatch)) != -1){ masteredJobs[city][currentTab].push(jobMatch); //DEBUG('--> jobInfo: '+ jobName+' - Marked as Mastered'); } masteredJobsCount++; } //ignore job if we have do not have enough energy / stamina to perform the job, otherwise we set jobmastery to 100 to skip this job temporarely var skipCurrentJob = false; stamElt = xpathFirst('.//dd[@class="stamina"]', currentJob); if(stamElt){ reqStam = parseInt(stamElt.innerHTML.untag()); if(reqStam > stamina){ skipCurrentJob = true; } } nrgElt = xpathFirst('.//dd[@class="energy"]', currentJob); if(!nrgElt) nrgElt = xpathFirst('.//td[@class="job_energy"]', currentJob); if(nrgElt){ reqNrg = parseInt(nrgElt.innerHTML.untag()); if(reqNrg > energy){ skipCurrentJob = true; } } var skipFightJob = false; if(isGMChecked('skipfight') && isFightJob){ skipFightJob = true; } // Skip locked jobs and optional fight jobs - more debugging since it seems to cause some troubles if(isJobLocked(jobAction) || skipCurrentJob || skipFightJob){ if(skipFightJob){ masteredJobs[city][currentTab].push(jobMatch); } } else { availableJobs[city][currentTab].push(jobMatch); } if(!jobCost) continue; // Skip this for jobs without cost var costElt = xpathFirst('.//dd[@class="energy"]', jobCost); if(!costElt) costElt = xpathFirst('.//dd[@class="stamina"]', jobCost); if(!costElt) continue; var cost = parseCash(costElt.innerHTML); var reward = 0; var ratio = 0; var xpTxt =''; var expElt = xpathFirst('.//dd[@class="experience"]', jobReward); if(expElt){ reward = parseInt(expElt.innerHTML); ratio = Math.round (reward / cost * 100) / 100; xpTxt = ' ('+ ratio+')'; } var moneyTxt = ''; var mratio = 0; var money = 0; var moneyElt = xpathFirst('.//dd[@class="vegas_cash_icon"]', jobReward); if(moneyElt){ money = parseCash(moneyElt.innerHTML.untag()); mratio = makeCommaValue(Math.round(money / cost)); moneyTxt = ' ('+ mratio+')'; } // Calculate time left for each job var timePerEnergy = isGMChecked('isManiac') ? 3 : 5; timePerEnergy = isGMChecked('hasHelicopter') ? timePerEnergy - .5: timePerEnergy; timePerEnergy = isGMChecked('hasGoldenThrone') ? timePerEnergy/2: timePerEnergy; var timeTxt = ' Time: 0 min'; if(cost > energy) timeTxt = ' Time: '+ getDecimalTime((cost - energy) * timePerEnergy); if(!xpathFirst('.//div[@class="timeLeft"]', currentJob)){ makeElement('div', currentJob, {'class':'timeLeft','style':'color:#52E259; font-size: 10px'}).appendChild(document.createTextNode(timeTxt)); } if(!xpathFirst('.//span[@id="ratio_xp"]', expElt)) makeElement('span', expElt, {'id':'ratio_xp', 'style':'color:red; font-size: 10px'}).appendChild(document.createTextNode(xpTxt)); if(!xpathFirst('.//span[@id="ratio_money"]', moneyElt)) makeElement('span', moneyElt, {'id':'ratio_money', 'style':'color:red; font-size: 10px'}).appendChild(document.createTextNode(moneyTxt)); updateJobInfo(jobMatch, cost, reward, ratio); // Is this a boss or fight job? if(!isFightJob){ // Keep track of the best & worst payoffs for energy jobs. if(ratio > bestRatio){ bestRatio = ratio; bestJobs = [currentJob]; } else if(ratio == bestRatio) bestJobs.push(currentJob); if(ratio < worstRatio){ worstRatio = ratio; worstJobs = [currentJob]; } else if(ratio == worstRatio) worstJobs.push(currentJob); } else { // Keep track of the best & worst payoffs for stamina jobs. if(ratio > bestStamRatio){ bestStamRatio = ratio; bestStamJobs = [currentJob]; } else if(ratio == bestStamRatio) bestStamJobs.push(currentJob); if(ratio < worstStamRatio){ worstStamRatio = ratio; worstStamJobs = [currentJob]; } else if(ratio == worstStamRatio) worstStamJobs.push(currentJob); } } var elt; // Highlight the best and worst energy jobs. if(worstRatio != bestRatio){ while (bestJobs.length){ elt = bestJobs.pop(); if(!xpathFirst('.//div[@class="job_best"]', elt)){ elt = makeElement('div', elt, {'class':'job_best', 'style':'color:#52E259; font-size: 10px'}); elt.appendChild(document.createTextNode(' (BEST)')); if(!running) elt.parentNode.setAttribute('style', 'border:1px solid #52E259'); } } while (worstJobs.length){ elt = worstJobs.pop(); if(!xpathFirst('.//div[@class="job_worst"]', elt)){ elt = makeElement('div', elt, {'class':'job_worst', 'style':'color:#EC2D2D; font-size: 10px'}); elt.appendChild(document.createTextNode(' (WORST)')); if(!running) elt.parentNode.setAttribute('style', 'border:1px solid #EC2D2D'); } } } // Highlight the best and worst stamina jobs. if(worstStamRatio != bestStamRatio){ while (bestStamJobs.length){ elt = bestStamJobs.pop(); if(!xpathFirst('.//div[@class="job_best_stam"]', elt)){ elt = makeElement('div', elt, {'class':'job_best_stam', 'style':'color:#52E259; font-size: 10px'}); elt.appendChild(document.createTextNode(' (BEST STAM)')); if(!running) elt.parentNode.setAttribute('style', 'border:1px dashed #52E259'); } } while (worstStamJobs.length){ elt = worstStamJobs.pop(); if(!xpathFirst('.//div[@class="job_worst_stam"]', elt)){ elt = makeElement('div', elt, {'class':'job_worst_stam', 'style':'color:#EC2D2D; font-size: 10px'}); elt.appendChild(document.createTextNode(' (WORST STAM)')); if(!running) elt.parentNode.setAttribute('style', 'border:1px dashed #EC2D2D'); } } } GM_setValue('availableJobs', JSON.stringify(availableJobs)); GM_setValue('masteredJobs', JSON.stringify(masteredJobs)); // Set the job progress jobMastery(innerPageElt, true); tierMastery(jobsFound, masteredJobsCount, currentTab); return true; } function customizeNewJobs(){ // Handle new job layout // FIXME: Change this once we encounter locked jobs for the new header var newJobs = $x('.//div[@id="new_user_jobs"]//div[contains(@class, "job clearfix")]', innerPageElt); if(!newJobs || newJobs.length == 0){ return false; } DEBUG('New - Found '+ newJobs.length+' new jobs.'); var availableJobs = eval('({0:{},1:{},2:{},3:{},4:{},5:{},6:{},7:{},8:{}})'); var masteredJobs = eval('({0:{},1:{},2:{},3:{},4:{},5:{},6:{},7:{},8:{}})'); try { availableJobs = eval('('+ GM_getValue('availableJobs')+')'); masteredJobs = eval('('+ GM_getValue('masteredJobs')+')'); } catch (ex){ // ignore } var currentTab = currentJobTab(); availableJobs[city][currentTab] = []; masteredJobs[city][currentTab] = []; // Display an experience to energy payoff ratio for each job. var bestJobs = [], worstJobs = []; var bestRatio = 0, worstRatio = 10; var masteryList = getSavedList('masteryJobsList'); var masteredJobsCount = 0; var jobsFound = 0; for (var i = 0, iLength = newJobs.length; i < iLength; ++i){ var currentJob = newJobs[i]; var jobName = xpathFirst('.//div[@class="title_results"]//h3', currentJob).innerHTML.clean().trim(); var jobCost = xpathFirst('.//div[@class="use_pay"]//dl[contains(.,"Uses")]', currentJob); var jobReward = xpathFirst('.//div[@class="use_pay"]//dl[contains(.,"Pays")]', currentJob); var jobAction = xpathFirst('.//a', currentJob); // Skip jobs not in missions array var jobMatch = missions.searchArray(jobName, 0)[0]; if(isNaN(jobMatch)){ DEBUG(jobName+' not found in missions array. '); continue; } jobsFound++; var jobPercentage = getJobMastery(currentJob, true); // Determine available jobs if(jobPercentage == 100){ if(masteryList.length > 0 && masteryList.indexOf(String(jobMatch)) != -1){ masteredJobs[city][currentTab].push(jobMatch); } masteredJobsCount++; // Skip locked jobs if(isJobLocked(jobAction)){ DEBUG('Job '+ jobName+'('+ jobMatch+') is locked. Skipping.'); } else { availableJobs[city][currentTab].push(jobMatch); } } // Skip this for jobs without jobCost if(!jobCost) continue; // Skip this for jobs without cost var costElt = xpathFirst('.//dd[@class="energy"]', jobCost); if(!costElt) continue; var cost = parseCash(costElt.innerHTML); var reward = 0; var ratio = 0; var xpTxt = ''; var expElt = xpathFirst('.//dd[@class="experience"]', jobReward); if(expElt){ reward = parseInt(expElt.innerHTML); ratio = Math.round(reward / cost * 100) / 100; xpTxt = '(XP: '+ ratio; } var moneyTxt = ''; var money = 0; var mratio = 0; var moneyElt = xpathFirst('.//dd[@class="cash cash_'+cities[city][CITY_ALIAS]+'"]', jobReward); if(moneyElt){ money = parseCash(moneyElt.innerHTML.untag()); mratio = makeCommaValue(Math.round(money / cost)); moneyTxt = ' - $$: '+ mratio+')'; } // Calculate time left for each job var timePerEnergy = isGMChecked('isManiac') ? 3 : 5; timePerEnergy = isGMChecked('hasHelicopter') ? timePerEnergy - .5: timePerEnergy; timePerEnergy = isGMChecked('hasGoldenThrone') ? timePerEnergy/2: timePerEnergy; var timeTxt = ' Time: 0 min'; if(cost > energy) timeTxt = 'Time: '+ getDecimalTime((cost - energy) * timePerEnergy); if(!xpathFirst('.//span[@id="reqText"]', expElt)) makeElement('span', costElt, {'id':'reqText', 'style':'color:red; font-size: 10px'}) .appendChild(document.createTextNode(' ['+ xpTxt + moneyTxt+']')); if(!xpathFirst('.//span[@id="timeLeft"]', costElt)) makeElement('span', costElt, {'id':'timeLeft','style':'color:green; font-size: 10px'}).appendChild(document.createTextNode(timeTxt)); updateJobInfo(jobMatch, cost, reward, ratio); // Keep track of the best & worst payoffs. if(ratio > bestRatio){ bestRatio = ratio; bestJobs = [costElt]; } else if(ratio == bestRatio){ bestJobs.push(costElt); } if(ratio < worstRatio){ worstRatio = ratio; worstJobs = [costElt]; } else if(ratio == worstRatio){ worstJobs.push(costElt); } } // Highlight the best and worst jobs. var elt; if(worstRatio != bestRatio){ while (bestJobs.length){ elt = bestJobs.pop(); makeElement('br', elt); elt = makeElement('span', elt, {'style':'color:#52E259; font-size: 10px'}); makeElement('img', elt, {'src':stripURI(yeahIcon), 'width':'12', 'height':'12', 'style':'vertical-align:middle'}); elt.appendChild(document.createTextNode(' BEST')); } while (worstJobs.length){ elt = worstJobs.pop(); makeElement('br', elt); elt = makeElement('span', elt, {'style':'color:#EC2D2D; font-size: 10px'}); makeElement('img', elt, {'src':stripURI(omgIcon), 'width':'12', 'height':'12', 'style':'vertical-align:middle'}); elt.appendChild(document.createTextNode(' WORST')); } } GM_setValue('availableJobs', JSON.stringify(availableJobs)); GM_setValue('masteredJobs', JSON.stringify(masteredJobs)); // Set the job progress jobMastery(innerPageElt, true); tierMastery(jobsFound, masteredJobsCount, currentTab); return true; } function isJobFight(jobRow){ var isFightJob = xpathFirst('.//div[@id="fight_opponents"]', jobRow); if(isFightJob) return true; return false; } function isJobLocked(jobAction){ return ((/lock/i.test(jobAction.innerHTML.untag()) || /complete/i.test(jobAction.innerHTML.untag())) && !/help/i.test(jobAction.innerHTML.untag())); } function customizeJobs(){ // Extras for jobs pages. var jobTables = $x('.//table[@class="job_list"]', innerPageElt); if(!jobTables || jobTables.length == 0) return false; var availableJobs = eval('({0:{},1:{},2:{},3:{},4:{},5:{},6:{},7:{},8:{}})'); var masteredJobs = eval('({0:{},1:{},2:{},3:{},4:{},5:{},6:{},7:{},8:{}})'); try { availableJobs = eval('('+ GM_getValue('availableJobs')+')'); masteredJobs = eval('('+ GM_getValue('masteredJobs')+')'); } catch (ex){ // ignore } var currentTab = currentJobTab(); availableJobs[city][currentTab] = []; masteredJobs[city][currentTab] = []; // Display an experience to energy payoff ratio for each job. var bestJobs = [], worstJobs = []; var bestRatio = 0, worstRatio = 10; var masteryList = getSavedList('masteryJobsList'); var masteredJobsCount = 0; var jobsFound = 0; for (var x = 0, xLength = jobTables.length; x < xLength; ++x){ //newlv var jobNames = xpath('.//td[@class="job_name" or @class="job_name job_no_border" or @class="job_name " or @class="job_title " or @class="job_name_oneline job_no_border" ]', jobTables[x]); for (var i = 0, iLength = jobNames.snapshotLength; i < iLength; ++i){ var jobName = jobNames.snapshotItem(i).innerHTML.split('
')[0].clean().trim(); // Skip this name if job row is not found var jobRow = getJobRow (jobName); if(!jobRow) continue; // Skip jobs not in missions array var jobMatch = missions.searchArray(jobName, 0)[0]; if(isNaN(jobMatch)){ DEBUG(jobName+' not found in missions array.'); continue; } jobsFound++; var jobPercentage = getJobMastery(jobRow, false); var jobInfo = xpathFirst('.//td[contains(@class,"job_name") and contains(.,"Master")]', jobRow); var jobCost = xpathFirst('.//td[contains(@class,"job_energy")]', jobRow); var jobReward = xpathFirst('.//td[contains(@class,"job_reward")]', jobRow); var jobAction = xpathFirst('.//td[contains(@class,"job_action")]', jobRow); // Determine available jobs // Ignore mastered jobs if(jobPercentage == 100){ if(masteryList.length > 0 && masteryList.indexOf(String(jobMatch)) != -1){ masteredJobs[city][currentTab].push(jobMatch); } masteredJobsCount++; } // Skip locked jobs if(isJobLocked(jobRow)) DEBUG('Job '+ jobName+'('+ jobMatch+') is locked. Skipping.'); else availableJobs[city][currentTab].push(jobMatch); var costElt = xpathFirst('.//span[@class="bold_number"]', jobCost); if(!costElt) costElt = xpathFirst('.//span[@class="energy"]', jobCost); // Skip this for jobs without cost if(!costElt) continue; var cost = parseInt(costElt.innerHTML); var expElt = xpathFirst('.//span[@class="bold_number"]', jobReward); if(!expElt) expElt = xpathFirst('.//span[@class="experience"]', jobReward); var reward = parseInt(expElt.innerHTML); var moneyElt = xpathFirst('.//span[@class="money"]/strong', jobReward); if(!moneyElt) moneyElt = xpathFirst('.//strong[@class="money"]', jobReward); // Display ratio and timer var ratio = Math.round(reward / cost * 100) / 100; if(!xpathFirst('.//span[@id="ratio_xp"]', costElt.parentNode)){ makeElement('br', costElt.parentNode); makeElement('span', costElt.parentNode, {'id':'ratio_xp', 'style':'color:#666666; font-size: 10px'}).appendChild(document.createTextNode('Pays '+ ratio+'x')); } updateJobInfo(jobMatch, cost, reward, ratio); if(moneyElt){ var money = parseCash(moneyElt.innerHTML); var currency = cities[city][CITY_CASH_SYMBOL]; var mratio = makeCommaValue(Math.round(money / cost)); if(!xpathFirst('.//span[@id="moneyCost"]', moneyElt.parentNode)) makeElement('span', moneyElt.parentNode, {'id':'moneyCost', 'style':'color:#666666; font-size: 10px'}).appendChild(document.createTextNode(' ('+ currency + mratio+')')); } // Keep track of the best & worst payoffs. if(ratio > bestRatio){ bestRatio = ratio; bestJobs = [costElt]; } else if(ratio == bestRatio){ bestJobs.push(costElt); } if(ratio < worstRatio){ worstRatio = ratio; worstJobs = [costElt]; } else if(ratio == worstRatio){ worstJobs.push(costElt); } // Calculate time left for each job and display under the do job button var timePerEnergy = isGMChecked('isManiac') ? 3 : 5; timePerEnergy = isGMChecked('hasHelicopter') ? timePerEnergy - .5: timePerEnergy; timePerEnergy = isGMChecked('hasGoldenThrone') ? timePerEnergy/2: timePerEnergy; if(cost > energy) jobTimeLeftText = 'Time: '+ getDecimalTime((cost - energy) * timePerEnergy); else jobTimeLeftText = 'Time: 0 min'; if(!xpathFirst('.//span[@id="timeLeft"]', jobAction)){ makeElement('br', jobAction); makeElement('br', jobAction); makeElement('span', jobAction, {'id':'timeLeft','style':'color:#666666; font-size: 10px'}).appendChild(document.createTextNode(jobTimeLeftText)); } } } // Highlight the best and worst jobs. var elt; if(worstRatio != bestRatio){ while (bestJobs.length){ elt = bestJobs.pop().parentNode; makeElement('br', elt); elt = makeElement('span', elt, {'style':'color:#52E259; font-size: 10px'}); makeElement('img', elt, {'src':stripURI(yeahIcon), 'width':'12', 'height':'12', 'style':'vertical-align:middle'}); elt.appendChild(document.createTextNode(' BEST')); } while (worstJobs.length){ elt = worstJobs.pop().parentNode; makeElement('br', elt); elt = makeElement('span', elt, {'style':'color:#EC2D2D; font-size: 10px'}); makeElement('img', elt, {'src':stripURI(omgIcon), 'width':'12', 'height':'12', 'style':'vertical-align:middle'}); elt.appendChild(document.createTextNode(' WORST')); } } GM_setValue('availableJobs', JSON.stringify(availableJobs)); GM_setValue('masteredJobs', JSON.stringify(masteredJobs)); // Set the job progress jobMastery(innerPageElt, false); DEBUG('Jobs found: '+ jobsFound+', Mastered jobs: '+ masteredJobsCount); tierMastery(jobsFound, masteredJobsCount, currentTab); return true; } function updateJobInfo(jobMatch, cost, reward, ratio){ var missionItem = missions[jobMatch]; // If values are not in synch, update mission array if(!isNaN(jobMatch) && (missionItem[MISSION_ENERGY] != cost || missionItem[MISSION_XP] != reward || missionItem[MISSION_RATIO] != ratio)){ missions[jobMatch][MISSION_ENERGY] = cost; missions[jobMatch][MISSION_XP] = reward; missions[jobMatch][MISSION_RATIO] = ratio; // Save joblist GM_setValue('missions', JSON.stringify(missions)); } } function tierMastery(jobsFound, jobsMastered, currentTab){ if(running && GM_getValue('selectTier','0.0') != '0.0'){ selectedTierValue = GM_getValue('selectTier','0.0').split('.'); masteryCity = parseInt(selectedTierValue[0]); masteryTier = parseInt(selectedTierValue[1]); if(city == masteryCity && masteryTier == currentTab && jobsFound <= jobsMastered){ selectTier = cities[masteryCity][0]+' - '+ missionTabs[masteryCity][masteryTier - 1]; addToLog('info Icon', 'Tier '+ selectTier+' is already mastered. Moving on to the next tier.'); // Move on the the next tier. if(missionTabs[masteryCity].length <= masteryTier){ // We have mastered all tiers. Disable tier mastery logic. if(cities.length < masteryCity){ GM_setValue('selectTier', '0.0'); // Next City } else { masteryCity++; while ( ( level < cities[masteryCity][CITY_LEVEL] ) && ( cities.length > masteryCity ) ){ masteryCity++; if (cities.length <= masteryCity ){ DEBUG('We are out of cities to check so turning off mastery ' ); GM_setValue('selectTier', '0.0'); return; } else { DEBUG(cities[(masteryCity-1)][CITY_NAME]+' Unavaliable, Checking '+ cities[masteryCity][CITY_NAME] ); } } masteryTier = 1; } // Next Tier } else { masteryTier++; } if(GM_getValue('selectTier','0.0') != '0.0'){ var mastery_jobs_list = []; for (i = 0, iLength = missions.length; i < iLength; i++){ if(masteryCity == missions[i][MISSION_CITY] && masteryTier == missions[i][MISSION_TAB]){ mastery_jobs_list.push(i); } } setSavedList('masteryJobsList', mastery_jobs_list); GM_setValue('selectTier', masteryCity+'.'+ masteryTier); } } } } function customizeFight(){ // No need to do this when AP is running if(running) return true; var opponents = getDisplayedOpponents(innerPageElt, true); if(!opponents) return false; // Customize the opponent list. var blacklist = getSavedList('fightListAvoid'); for (var i = 0, iLength=opponents.length; i < iLength; ++i){ var opponent = opponents[i]; if(!opponent.profile || !opponent.id) continue; // Mark targets that should be avoided. if(blacklist.indexOf(opponent.id) != -1){ var parentElt = opponent.profile.parentNode; var elt = makeElement('img', null, {'src':stripURI(omgIcon), 'width':'12', 'height':'12', 'style':'vertical-align:middle', 'title':'You have already lost to this opponent during automatic play.'}); parentElt.insertBefore(elt, parentElt.firstChild); } } return true; } function customizeHitlist(){ // No need to do this when AP is running if(running) return true; // Extras for hitlist. if(!onHitlistTab()) return false; // Get the displayed opponents. var opponents = getHitlist(innerPageElt, true); if(!opponents) return true; // Customize the opponent list. var blacklist = getSavedList('hitmanListAvoid').concat(getSavedList('fightListAvoid')); var kills = getSavedList('hitmanListKilled'); for (var i = 0, iLength=opponents.length; i < iLength; ++i){ var opponent = opponents[i]; if(!opponent.profile) continue; // Mark targets that should be avoided. var elt, parentElt; if(blacklist.indexOf(opponent.id) != -1){ parentElt = opponent.profile.parentNode; elt = makeElement('img', null, {'src':stripURI(omgIcon), 'width':'12', 'height':'12', 'style':'vertical-align:middle', 'title':'You have already lost to this opponent during automatic play.'}); parentElt.insertBefore(elt, parentElt.firstChild); } // Mark targets on which bounties have already been collected. if(kills.indexOf(opponent.id) != -1){ parentElt = opponent.profile.parentNode; elt = makeElement('img', null, {'src':stripURI(lootbagIcon), 'width':'12', 'height':'12', 'style':'vertical-align:middle', 'title':'You have already collected a bounty on this target during automatic play.'}); parentElt.insertBefore(elt, parentElt.firstChild); } } return true; } function setLevelUpRatioStats(){ var elt = document.getElementById('level_up_ratio_stats'); if(elt){ var ratioHTML = 'Level Up Ratio\'s: '; if(stamina || energy){ var ratio = Math.ceil((ptsToNextLevel) / (energy + stamina) * 100) / 100; ratioHTML += 'Combined: '+ (ratio > 25 ? '> 25' : ratio)+'x'; if(energy){ var ratioEnergy = Math.ceil((ptsToNextLevel) / energy * 100) / 100; ratioHTML += ' | Energy: '+ (ratioEnergy > 25 ? '> 25' : ratioEnergy)+'x'; } if(stamina){ var ratioStamina = Math.ceil((ptsToNextLevel) / stamina * 100) / 100; ratioHTML += ' | Stamina: '+ (ratioStamina > 25 ? '> 25' : ratioStamina)+'x'; } } elt.innerHTML = ratioHTML; if(ratio) elt.style.display = 'block'; else elt.style.display = 'none'; } if(!isGMChecked('noStats')){ var rate = getStaminaGainRate(); if(elt = xpathFirst('.//div[@id="expRate"]')) elt.firstChild.nodeValue = rate.toFixed(2); if(elt = xpathFirst('.//div[@id="expToNext"]')) elt.firstChild.nodeValue = makeCommaValue(ptsToNextLevel); if(elt = xpathFirst('.//div[@id="stamToNext"]')) elt.firstChild.nodeValue = rate? (ptsToNextLevel / rate).toFixed(0): 'n/a'; } } // Callback for clicking 'Add to Fight List' on profile page. function clickFightListAdd(){ addSavedListItem('pfightlist', this.id); this.firstChild.nodeValue = 'Remove from Fight List'; this.removeEventListener('click', clickFightListAdd, false); this.addEventListener('click', clickFightListRemove, false); var el = document.getElementById('pfightlist'); if(el) el.value = GM_getValue('pfightlist', ''); } // Callback for clicking 'Remove from Fight List' on profile page. function clickFightListRemove(){ while(removeSavedListItem('pfightlist', this.id)) this.firstChild.nodeValue = 'Add to Fight List'; this.removeEventListener('click', clickFightListRemove, false); this.addEventListener('click', clickFightListAdd, false); var el = document.getElementById('pfightlist'); if(el) el.value = GM_getValue('pfightlist', ''); } // Callback for clicking 'Add to AutoHit List' on profile page. function clickAutoHitListAdd(){ addSavedListItem('pautoHitOpponentList', this.id); this.firstChild.nodeValue = 'Remove from AutoHit List'; this.removeEventListener('click', clickAutoHitListAdd, false); this.addEventListener('click', clickAutoHitListRemove, false); var el = document.getElementById('pautoHitOpponentList'); if(el) el.value = GM_getValue('pautoHitOpponentList', ''); } // Callback for clicking 'Remove from AutoHit List' on profile page. function clickAutoHitListRemove(){ while(removeSavedListItem('pautoHitOpponentList', this.id)) this.firstChild.nodeValue = 'Add to AutoHit List'; this.removeEventListener('click', clickAutoHitListRemove, false); this.addEventListener('click', clickAutoHitListAdd, false); var el = document.getElementById('pautoHitOpponentList'); if(el) el.value = GM_getValue('pautoHitOpponentList', ''); } // Callback for clicking 'Add to War List' on profile page. function clickWarListAdd(){ addSavedListItem('autoWarTargetList', this.id); this.firstChild.nodeValue = 'Remove from War List'; this.removeEventListener('click', clickWarListAdd, false); this.addEventListener('click', clickWarListRemove, false); var el = document.getElementById('autoWarTargetList'); if(el) el.value = GM_getValue('autoWarTargetList', ''); } // Callback for clicking 'Remove from War List' on profile page. function clickWarListRemove(){ while(removeSavedListItem('autoWarTargetList', this.id)) this.firstChild.nodeValue = 'Add to War List'; this.removeEventListener('click', clickWarListRemove, false); this.addEventListener('click', clickWarListAdd, false); var el = document.getElementById('autoWarTargetList'); if(el) el.value = GM_getValue('autoWarTargetList', ''); } function getJobRow(jobName, contextNode){ var rowElt, conTxt = '', LVjob=0; try { // Retrieve by job number first var jobMatch = missions.searchArray(jobName, 0)[0]; if(!isNaN(jobMatch)){ var jobno = missions[jobMatch][MISSION_NUMBER]; rowElt = xpathFirst('.//table[@class="job_list"]//a[contains(@onclick, "job='+ jobno+'&")]', contextNode); if(!rowElt) rowElt = xpathFirst('.//table[@class="job_list"]//a[contains(@href, "job='+ jobno+'&")]', contextNode); //Fetching logic for Vegas jobs if(!rowElt && (city==LV || city==ITALY)){ var jobContainer = "job"+jobno; rowElt = xpathFirst('.//div[@id="'+jobContainer+'"]', contextNode); LVjob = 1; } } // cheat way to buy needed stuff and not wait for a reply works as is var elt = xpathFirst('.//a[contains(@onclick, "MapController.buyItems('+jobno+'); return false;")]') ; if(elt){ DEBUG('Cheating on buying for now found a link to click - - jobno='+ jobno ); clickElement(elt); } // If no rows found, retrieve by name if(!rowElt){ // Tokenize job name words var jobNameTokens = jobName.replace (/"/g,' ').replace(/'/g, ' ').split(' '); for (var i = 0; i < jobNameTokens.length; ++i){ if(jobNameTokens[i].length > 1){ if(conTxt.length > 0) conTxt += ' and '; conTxt += 'contains(., "'+jobNameTokens[i]+'")'; } } rowElt = xpathFirst('.//table[@class="job_list"]//tr//td['+conTxt+']', contextNode); } // Get the parent TR if(rowElt && !LVjob) while (rowElt.tagName != "TR") rowElt = rowElt.parentNode; // Fetching logic for new job rows if(!rowElt) rowElt = xpathFirst('.//div[@id="new_user_jobs"]//div[contains(@class, "job clearfix") and '+conTxt+']', contextNode); // Fetching logic for Brazil job rows if(!rowElt){ rowElt = xpathFirst('.//div[@class="job"]//a[contains(@href, "job='+ jobno+'&")]', contextNode); if(rowElt) rowElt = rowElt.parentNode.parentNode; } } catch(ex){ DEBUG('BUG DETECTED (getJobRow): [exception: '+ ex+'], [conTxt: '+ conTxt+'], [jobName: '+ jobName+']'); } if(!rowElt) return false; return rowElt; } //// function getJobRowItems(jobName){ try { var currentJob = jobName; var currentJobRow = getJobRow(currentJob, innerPageElt); if(!currentJobRow) return false; var inner = innerPageElt? innerPageElt.innerHTML : ''; var innerNoTags = inner.untag(); if(innerNoTags.match(/You do not have enough cash to buy/i)){ addToLog('warning Icon', 'You don\'t have enough cash to buy necessary equipment.'); var jobs = getSavedList('jobsToDo', ''); if(jobs.indexOf(currentJob) == -1){ jobs.push(currentJob); DEBUG('Saving '+ currentJob+' for later. Need to farm cash first.'); setSavedList('jobsToDo', jobs); return true; } return false; } var buyItemElts = $x('.//a[contains(@onclick, "xw_action=buy_item")]',currentJobRow); if(!buyItemElts) buyItemElts = $x('.//a[contains(@onclick, "MapController.buyItems")]',currentJobRow); // Click to buy items if(buyItemElts.length > 0){ addToLog('search Icon', 'Attempting to purchase required items.'); for (var i = 0, numItems=buyItemElts.length; i < numItems; ++i){ Autoplay.fx = function(){ clickAction = 'buy item'; clickElement(buyItemElts[i]); DEBUG('Clicked to buy item.'); }; break; } return true; } // New Job layout handling // if(isGMChecked('autoWithDraw')){ var amtElt = xpathFirst('.//strong[@class="cash cash_'+cities[city][CITY_ALIAS]+'"]', currentJobRow); if(!amtElt) amtElt = xpathFirst('.//div[@class="job_uses"]//dd[contains(@class,"cash_icon")]', currentJobRow); if(amtElt){ var cashDiff = parseCash(amtElt.innerHTML.untag().trim()) - cities[city][CITY_CASH]; // Withdraw the amount we need if(cashDiff > 0){ DEBUG('We need '+cashDiff+' for this job. Going to the bank/vault of '+city); suspendBank = true; return (autoBankWithdraw(cashDiff)); } } } // Logic to switch to the required job first var necessaryItems = $x('.//div[@class="req_item"]//img', currentJobRow); // Figure out which loot items are needed before this job can be attempted // again and, consequently, which jobs will have to be done to get them. if(necessaryItems.length > 0){ DEBUG('Some Items Required for this job - req_item'); // Save the current job for later. The current job should not already exist in the list, so check first. var items = getSavedList('itemList'); var jobs = getSavedList('jobsToDo', ''); if(jobs.indexOf(currentJob) == -1){ jobs.push(currentJob); DEBUG('Saving '+ currentJob+' for later. Need to fetch pre-req items first.'); setSavedList('jobsToDo', jobs); } var itemsFound = false; necessaryItems.forEach( function(i){ var itmSearch = i.alt; itmSearch = itmSearch.replace(/set of/i, ''); itmSearch = itmSearch.replace(/\[(.+?)\]/i, ''); itmSearch = itmSearch.trim(); DEBUG(itmSearch); var itemFound = false; // Try fetching the items from the job requirement array requirementJob.forEach( function(j){ if(level >= cities[j[2]][CITY_LEVEL] && j[0].toUpperCase().trim() == itmSearch.toUpperCase().trim()){ jobs.push(j[1]); items.push(itmSearch); itemFound = true; } } ); // Set the flag if at least one item is found if(itemFound) itemsFound = true; else DEBUG(itmSearch+' not found in the requirement job array.'); } ); // At least one item found if(itemsFound){ setSavedList('itemList', items.unique()); setSavedList('jobsToDo', jobs); popJob(); return true; } } else { necessaryItems = xpathFirst('.//span[@class="missing_req_items"]', currentJobRow); itmSearch=''; if(necessaryItems){ DEBUG('Some Items Required for this job - missing_req_items'); itmSearch = necessaryItems.innerHTML; if(itmSearch.match(/(.+?),/i)) itmSearch = RegExp.$1; DEBUG('Missing Item: '+ itmSearch); itmSearch = itmSearch.replace(/\(.+?\)/gi, '').trim(); DEBUG('Parsed Missing Item: '+ itmSearch); } else { necessaryItems = xpathFirst('.//div[@class="needed_gate_loot_container"]', currentJobRow); if(!necessaryItems) necessaryItems = xpathFirst('.//div[@class="needed_gate_loot"]', currentJobRow); if(necessaryItems){ DEBUG('Some Items Required for this job - needed_gate_loot'); messages = $x('.//img', necessaryItems); numMessages = messages.length; for (i = 0; i < numMessages; i++){ var item = messages[i].title; if(!item.match(/Gift this/i)){ if(itmSearch == '') itmSearch = item; else itmSearch = itmSearch+', '+ item; } } DEBUG('Missing Item(s): '+ itmSearch); } } if(itmSearch!=''){ DEBUG('Item(s) Required for this job : '+itmSearch); // Save the current job for later. The current job should not already exist in the list, so check first. var items = getSavedList('itemList'); var jobs = getSavedList('jobsToDo', ''); DEBUG('Current Job List: '+jobs); if(jobs.indexOf(currentJob) == -1){ jobs.push(currentJob); DEBUG('Saving '+ currentJob+' for later. Need to fetch pre-req items first.'); setSavedList('jobsToDo', jobs); } else { DEBUG(currentJob+' already saved for later. Need to fetch pre-req items first.'); } var itemFound = false; // Try fetching the items from the job requirement array requirementJob.forEach( function(j){ if(level >= cities[j[2]][CITY_LEVEL] && j[0].toUpperCase().trim() == itmSearch.toUpperCase().trim()){ jobs.push(j[1]); items.push(itmSearch.trim()); itemFound = true; jobFound = j[1]; } } ); // Set the flag if at least one item is found if(!itemFound) DEBUG(itmSearch+' not found in the requirement job array.'); else { setSavedList('itemList', items.unique()); setSavedList('jobsToDo', jobs); popJob(); return true; } } } // Withdraw money var amtElt = xpathFirst('.//td[contains(@class,"job_energy")]//span[@class="money" or @class="bad"]', currentJobRow); if(amtElt){ var cashDiff = parseCash(amtElt.innerHTML) - cities[city][CITY_CASH]; // Withdraw the amount we need if(cashDiff > 0){ suspendBank = true; return (autoBankWithdraw(cashDiff)); } } return false; } catch(reqError){ DEBUG('getJobRowItems Error :'+ reqError); } } function popJob(){ var jobs = getSavedList('jobsToDo', ''); // Set the very next job to perform. var doJob = jobs.pop(); setSavedList('jobsToDo', jobs); var i = 0; missions.forEach( function(f){ if(f[0].toUpperCase().trim() == doJob.toUpperCase().trim()){ GM_setValue('selectMission', i); addToLog('info Icon', 'Switching job to '+ doJob+'(popJob).'); } i++; } ); } // Set the next job to be done for job combination options function jobCombo(element){ var i; // Cycle jobs with the same ratio var availableJobs = eval('('+ GM_getValue('availableJobs', "{0:{},1:{},2:{},3:{},4:{},5:{},6:{},7:{},8:{}}")+')'); var multiple_jobs_list = getSavedList('selectMissionMultiple'); var cycle_jobs = new Object(); // Group selected jobs by ratio for (i = 0, iLength=multiple_jobs_list.length; i < iLength; ++i){ var job = multiple_jobs_list[i]; var mission = missions[job]; if(!mission) continue; // Put non-available jobs at the end of the queue if(availableJobs[mission[MISSION_CITY]][mission[MISSION_TAB]] != null && availableJobs[mission[MISSION_CITY]][mission[MISSION_TAB]].indexOf(parseInt(job)) == -1){ mission[MISSION_RATIO] = 0; } if(cycle_jobs[mission[MISSION_RATIO]] == null) cycle_jobs[mission[MISSION_RATIO]] = []; cycle_jobs[mission[MISSION_RATIO]].push(multiple_jobs_list[i]); } // Rebuild the job list array multiple_jobs_list = []; for (i in cycle_jobs){ if(cycle_jobs[i].length > 1){ // Only cycle the current job's ratio group if(missions[GM_getValue('selectMission', 1)][MISSION_RATIO] == i) cycle_jobs[i].push(cycle_jobs[i].shift()); for (var n = 0, nLength=cycle_jobs[i].length; n < nLength; ++n){ multiple_jobs_list.push(cycle_jobs[i][n]); } } else multiple_jobs_list.push(cycle_jobs[i][0]); } setSavedList('selectMissionMultiple', multiple_jobs_list); } function jobLoot(element){ var i, lootbag = []; var strLoot = ''; var strUsed='' // See what loot was gained. var messages = $x('.//td[class="message_body"]', element); var numMessages = messages.length; for (i = 1; i < numMessages; i++){ var innerNoTags = messages[i].innerHTML.untag(); if(innerNoTags.match(/you\s+?gained:\s+?an?\s+?(.+)\./i) || innerNoTags.match(/you\s+gained(?:\s+an?)?\s+(.+)\./i) || innerNoTags.match(/found(?:\s+an?)?\s+(.*?)\s+on\s+the/i) || innerNoTags.match(/earned(?:\s+an?)?\s+(.*?)\.\s+you\s+/i)){ var loot = RegExp.$1; if(loot.match(/(.+?)\s+?was(.+?)(\d+)/i)) loot = RegExp.$1+' x '+RegExp.$3; else if(loot.match(/(.+?)\s+?(\.|-)?\s+?used?(.+?)(\d+)/i)) loot = RegExp.$1+' x '+RegExp.$4; if(strLoot) strLoot += '
'+'Found '+loot+' in the job.'; else strLoot = 'Found '+ loot+' in the job.'; lootbag.push(loot); } } if(numMessages > 0 && strLoot !='') addToLog('lootbag Icon', strLoot); if(city==NY || city == CUBA){ //New NY Job Loot var messages = $x('.//dd[@class="message_item"]', element); var numMessages = messages.length; for (i = 0; i < numMessages; i++){ var loot = messages[i].innerHTML.untag(); if(loot.indexOf('remaining')==-1){ if(strLoot) strLoot += '
'+'Found '+loot+' in the job.'; else strLoot = 'Found '+ loot+' in the job.'; lootbag.push(loot); } else { if(strUsed) strUsed += '
'+'You used '+loot+' in the job.'; else strUsed = 'You used '+ loot+' in the job.'; } } if(numMessages > 0 && strLoot !='') addToLog('lootbag Icon', strLoot); if(numMessages > 0 && strUsed !='') addToLog('lootbag Icon', strUsed); } // Vegas Loot on jobs if(city == LV||city==ITALY){ var jobResults = xpathFirst('.//div[@class="job_results"]', element); strLoot = ''; messages = $x('.//img', jobResults); numMessages = messages.length; for (i = 0; i < numMessages; i++){ if(messages[i].title){ var loot = messages[i].title; var parentText = messages[i].parentNode.innerHTML.untag(); if(parentText.match(/(\d+)/)) parentText = ' x '+ RegExp.$1; if(loot.match(/(.+?)(\.|-)?\s+?(was|used?)/i)) loot = RegExp.$1; if(strLoot) strLoot += '
'+'Found '+loot+' ' +parentText+' in the job.'; else strLoot = 'Found '+ loot+' ' +parentText+' in the job.'; lootbag.push(loot); } } if(numMessages > 0 && strLoot !='') addToLog('lootbag Icon', strLoot); } if(city == BRAZIL || city == CHICAGO){ var strLoot=''; var loot = ''; var lootElt = ''; var lootTxt = ''; DEBUG('Checking for Brazil Loot'); var jobResults = $x('.//div[@class="job_additional_results"]//div[@class="loot_item"]', element) if(jobResults && jobResults.length>0){ for(j=0;j < jobResults.length;j++){ var jobParent = jobResults[j].parentNode; var myParentClass=''; if(jobParent) myParentClass = jobParent.className; DEBUG('ParentClass: '+myParentClass); if(myParentClass!='previous_loot'){ loot = ''; lootElt = ''; lootTxt = ''; messages = $x('.//div[contains(@class,"item_card_mini")]', jobResults[j]); numMessages = messages.length; for (i = 0; i < numMessages; i++){ lootID = messages[i].getAttribute('item_id') DEBUG('lootID '+lootID); if(lootID){ lootElt = xpathFirst('.//img[@item_id="'+lootID+'"]', element); if(lootElt) lootTxt = lootElt.title; else { lootElt = xpathFirst('.//img', messages[i]); lootAttack = xpathFirst('.//div[@class="attack"]', messages[i]); lootDefense = xpathFirst('.//div[@class="defense"]', messages[i]); if(lootElt){ lootTxt = lootElt.src; if(lootTxt.match(/item_(.+?)_/i)) lootTxt = RegExp.$1; } if(lootAttack) lootTxt += '(A: '+lootAttack.innerHTML; if(lootDefense) lootTxt += '/ D: '+lootDefense.innerHTML+')'; if(lootTxt=='') lootTxt = 'Item'; } if(strLoot) strLoot += '
'+'Found '+lootTxt+' ('+lootID+') in the job.'; else strLoot = 'Found '+ lootTxt+' ('+lootID+') in the job.'; lootbag.push(lootTxt); } } } } } if(strLoot !='') addToLog('lootbag Icon', strLoot); } DEBUG('Found '+ lootbag.length+' item(s) on this job.'); var items = getSavedList('itemList'); if(typeof(items[0]) == 'undefined' || items.length == 0){ DEBUG('No items in required item list.'); return; } var itemFound = false; var itemName; // NOTE: The single equal sign is intentional in this while() condition. while ((itemName = lootbag.pop())){ DEBUG('Looking for '+ itemName+' in needed items list. We need '+ items.length+' item(s).'); for (var i = 0; i < items.length; i++){ if(itemName.indexOf(items[i].trim()) != -1 ){ // we found some needed loot itemFound = true; DEBUG(''+ itemName+' is the item we were looking for!'); removeSavedListItem('itemList', itemName); removeJobForItem('jobsToDo', itemName); popJob(); return true; } } } } function debugDumpSettings(){ try{ // Use showIfUnchecked() to show 0 value as "un-checked", or showIfSelected() // to show 0 value as "not selected" (for radio buttons). var getJobList = function(listName){ var multiple_jobs_list = getSavedList(listName); var jobNames = []; for (var i=0, numJobs=multiple_jobs_list.length; i < numJobs; ++i){ jobNames.push(missions[multiple_jobs_list[i]][MISSION_NAME]); } return jobNames.join(', '); }; var ratioJobs = getJobList('selectMissionMultiple'); var selectTier = 'None'; if(GM_getValue('selectTier','0.0') != '0.0'){ selectedTierValue = GM_getValue('selectTier','0.0').split('.'); selectTier = cities[parseInt(selectedTierValue[0])][0]+' - '+ missionTabs[NY][parseInt(selectedTierValue[1]) - 1]; } if(GM_getValue('language', 'en') != 'en'){ DEBUG('Language is "'+ GM_getValue('language','undefined')+'".'); addToLog('warning Icon', 'Unfortunately, only the English version of the game is fully supported. If you experience problems, set your Facebook language to English and try again.'); } var BrowserDetect = { init: function (){ this.browser = this.searchString(this.dataBrowser) || "An unknown browser"; this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "an unknown version"; this.OS = this.searchString(this.dataOS) || "an unknown OS"; }, searchString: function (data){ for (var i=0;i' + 'Browser Name: '+ BrowserDetect.browser+'
' + 'Browser Version: '+ BrowserDetect.version+'
' + 'Operating System: '+ BrowserDetect.OS+'
' + 'New Layout: '+ new_header+'
' + 'Browser Window Size: '+ winW+' / ' +winH+'
' + '------------------ PS MWAP Settings---------------------
' + 'Script Version: '+ SCRIPT.version+'
' + 'Language: '+ GM_getValue('language')+'
' + 'isFlashed: '+ isFlashed+'
' + 'isRunning: '+ running+'
' + 'Player current level: '+ level+'
' + 'Player points to next level: '+ ptsToNextLevel+'
' + 'Player mafia size: '+ mafia+'
' + 'Player attack profile: '+ curAttack+'
' + 'Player defense profile: '+ curDefense+'
' + 'Player attack equip: '+ curAttackEquip+'
' + 'Player defense equip: '+ curDefenseEquip+'
' + 'Player health: '+ health+'/'+ maxHealth+'
' + 'Player energy: '+ energy+'/'+ maxEnergy+'
' + 'Player stamina: '+ stamina+'/'+ maxStamina+'
' + 'Player skill points: '+ stats+'
' + 'Energy pack waiting? '+ energyPack+'
' + 'Current location: '+ cities[city][CITY_NAME]+'
'; for(i=0,iLength=cities.length;i'+ (isUndefined(cities[i][CITY_CASH])) ? 'unknown
' : cities[i][CITY_CASH_SYMBOL] + makeCommaValue(cities[i][CITY_CASH])+'
'; } settingsDump+= '-------------------General Tab--------------------------
' + 'Enable auto-refresh: '+ showIfUnchecked(GM_getValue('autoClick'))+ '
' + '  -Refresh rate low: '+ GM_getValue('r1')+'
' + '  -Refresh rate high: '+ GM_getValue('r2')+'
' + 'Enable auto-pause: '+ showIfUnchecked(GM_getValue('autoPause'))+'
' + '  -After level up: '+ showIfSelected(GM_getValue('autoPauseAfter'))+'
' + '  -Before level up: '+ showIfSelected(GM_getValue('autoPauseBefore'))+'
' + '  -Exp to pause at: '+ GM_getValue('autoPauseExp')+'
' + 'Delay rate low: '+ GM_getValue('d1')+'
' + 'Delay rate high: '+ GM_getValue('d2')+'
' + 'Idle in City: '+ showIfUnchecked(GM_getValue('idleInCity'))+'
' + '  Selected city: '+ cities[GM_getValue('idleLocation', NY)][CITY_NAME]+'
' + 'Enable auto-Daily Chance: '+ showIfUnchecked(GM_getValue('autoLottoOpt'))+'
' + 'Enable collect Daily Chance bonus: '+ showIfUnchecked(GM_getValue('autoLottoBonus')) +' == '+ autoLottoBonusList[GM_getValue('autoLottoList', 0)]+'
' + 'Spend all: '+ showIfUnchecked(GM_getValue('burnFirst'))+' == '+ burnModes[GM_getValue('burnOption')]+'
' + 'Popup Processing: '+ showIfUnchecked(GM_getValue('autoProcessPopups'))+'
' + //'autoDailyTake: '+ showIfUnchecked(GM_getValue('autoDailyTake'))+'
' + '---------------------Display Tab--------------------
' + 'Show Text Labels: '+ showIfUnchecked(GM_getValue('textOnlyMode'))+'
' + 'Enable logging: '+ showIfUnchecked(GM_getValue('autoLog'))+'
' + '  -Logging length: '+ GM_getValue('autoLogLength')+'
' + 'Log player updates: '+ showIfUnchecked(GM_getValue('logPlayerUpdates'))+'
' + '  -Updates length: '+ GM_getValue('logPlayerUpdatesMax')+'
' + 'Enable log filtering: '+ showIfUnchecked(GM_getValue('filterLog'))+'
' + '  Filter mode: '+ GM_getValue('filterOpt')+'
' + '  Filter pass: '+ GM_getValue('filterPass')+'
' + '  Filter fail: '+ GM_getValue('filterFail')+'
' + 'Left-align main frame: '+ showIfUnchecked(GM_getValue('leftAlign'))+'
' + 'Elevate PS MWAP-Header: '+ showIfUnchecked(GM_getValue('mastheadOnTop'))+'
' + 'Hide All: '+ showIfUnchecked(GM_getValue('hideAll'))+'
' + 'Show pulse on the fight page: '+ showIfUnchecked(GM_getValue('showPulse'))+'
' + 'Show level on the hitlist page: '+ showIfUnchecked(GM_getValue('showLevel'))+'
' + 'Set window title to name on Facebook account: '+ showIfUnchecked(GM_getValue('fbwindowtitle'))+'
' + '---------------------Mafia Tab--------------------
' + 'Automatically asks for job help: '+ showIfUnchecked(GM_getValue('autoAskJobHelp'))+'
' + 'Minimum experience for job help: '+ GM_getValue('autoAskJobHelpMinExp')+'
' + 'Ask for Vegas help: '+ GM_getValue('selectVegasTier')+'
' + 'Ask for Italy help: '+ GM_getValue('selectItalyTier')+'
' + 'Miscellaneous publishing:
' + '  Global Publishing: '+ showIfUnchecked(GM_getValue('autoGlobalPublishing'))+'
' + '  Ice bonus: '+ showIfUnchecked(GM_getValue('autoIcePublish'))+'
' + '  Ice bonus Frequency: '+ GM_getValue('autoIcePublishFrequency')+'
' + '  Level-up bonus: '+ showIfUnchecked(GM_getValue('autoLevelPublish'))+'
' + '  Achievement bonus: '+ showIfUnchecked(GM_getValue('autoAchievementPublish'))+'
' + '  Automatically share wishlist: '+ showIfUnchecked(GM_getValue('autoShareWishlist'))+'
' + '  Hour interval for sharing wishlist: '+ GM_getValue('autoShareWishlistTime')+'
' + 'Accept mafia invitations: '+ showIfUnchecked(GM_getValue('acceptMafiaInvitations'))+'
' + 'Automatically ask to Join Brazil Crew: '+ showIfUnchecked(GM_getValue('autoAskCityCrew'))+'
' + 'Automatically ask to Join Chicago Crew: '+ showIfUnchecked(GM_getValue('autoAskChicagoCrew'))+'
' + 'Automatically ask for Help on Crew Collections: '+ showIfUnchecked(GM_getValue('autoAskHelponCC'))+'
' + 'Automatically Help on Jobs: '+ showIfUnchecked(GM_getValue('autoHelp'))+'
' + 'Automatically Help on Wars: '+ showIfUnchecked(GM_getValue('autoWarHelp'))+'
' + 'Automatically Help on Burners: '+ showIfUnchecked(GM_getValue('autoBurnerHelp'))+'
' + 'Automatically Help on Parts: '+ showIfUnchecked(GM_getValue('autoPartsHelp'))+'
' + 'Message Center : Auto Accept Gifts: '+ showIfUnchecked(GM_getValue('autoAcceptMsgGifts')) +'
' + 'Message Center : Auto Accept Boosts: '+ showIfUnchecked(GM_getValue('autoAcceptMsgBoosts')) +'
' + 'Message Center : Auto Accept Crew: '+ showIfUnchecked(GM_getValue('autoAcceptMsgCrew')) +'
' + 'Message Center : Auto Send Eneryg: '+ showIfUnchecked(GM_getValue('autosendMsgEnergyPack')) +'
' + 'Auto War: '+ showIfUnchecked(GM_getValue('autoWar')) +'
' + '  War Mode: '+ warModeChoices[GM_getValue('warMode', 0)] +'
' + '  Auto War Target List: '+ GM_getValue('autoWarTargetList', 0)+'
' + '  Publish war declaration: '+ showIfUnchecked(GM_getValue('autoWarPublish'))+'
' + '  Publish call for backup: '+ showIfUnchecked(GM_getValue('autoWarResponsePublish'))+'
' + '  Publish reward: '+ showIfUnchecked(GM_getValue('autoWarRewardPublish'))+'
' + '  Publish rally for help: '+ showIfUnchecked(GM_getValue('autoWarRallyPublish'))+'
' + '-----------------Missions/Help Tab-----------------
' + '  Enable Mafia Operations: '+ showIfUnchecked(GM_getValue('AutoMafiaMission'))+'
' + '  Ask Mission Help: '+ showIfUnchecked(GM_getValue('AskMissionHelp'))+'
' + '  Autostart Personal Operations: '+ showIfUnchecked(GM_getValue('AutoStartOperations'))+'
' + '  Autoretry Personal Operations: '+ showIfUnchecked(GM_getValue('AutoRetryOperations'))+'
' + '  Collect Operation Rewards: '+ showIfUnchecked(GM_getValue('AutoMafiaCollection'))+'
' + '  Do Mafia Operations: '+ showIfUnchecked(GM_getValue('AutoMafiaJob'))+'
' + '  Delete Operations Removed From: '+ showIfUnchecked(GM_getValue('AutoMafiaRemoved'))+'
' + '  CollectMissionsTimer: '+ getHoursTime('colmissionTimer')+'
' + '  CheckedMyMissionsTimer: '+ getHoursTime('checkedmymissionTimer')+'
' + '-------------------Autostat Tab--------------------
' + 'Enable auto-stat: '+ showIfUnchecked(GM_getValue('autoStat'))+'
' + 'Disable auto-stat: '+ showIfUnchecked(GM_getValue('autoStatDisable'))+'
' + '  -Attack Base: '+ GM_getValue('autoStatAttackBase')+'
' + '  -Defense Base: '+ GM_getValue('autoStatDefenseBase')+'
' + '  -Health Base: '+ GM_getValue('autoStatHealthBase')+'
' + '  -Energy Base: '+ GM_getValue('autoStatEnergyBase')+'
' + '  -Stamina Base: '+ GM_getValue('autoStatStaminaBase')+'
' + '  -Attack Ratio: '+ GM_getValue('autoStatAttackRatio')+'
' + '  -Defense Ratio: '+ GM_getValue('autoStatDefenseRatio')+'
' + '  -Health Ratio: '+ GM_getValue('autoStatHealthRatio')+'
' + '  -Energy Ratio: '+ GM_getValue('autoStatEnergyRatio')+'
' + '  -Stamina Ratio: '+ GM_getValue('autoStatStaminaRatio')+'
' + '  -Attack Mode: '+ GM_getValue('autoStatAttackMode')+'
' + '  -Defense Mode: '+ GM_getValue('autoStatDefenseMode')+'
' + '  -Health Mode: '+ GM_getValue('autoStatHealthMode')+'
' + '  -Energy Mode: '+ GM_getValue('autoStatEnergyMode')+'
' + '  -Stamina Mode: '+ GM_getValue('autoStatStaminaMode')+'
' + '  -Attack Prio: '+ GM_getValue('autoStatAttackPrio')+'
' + '  -Defense Prio: '+ GM_getValue('autoStatDefensePrio')+'
' + '  -Health Prio: '+ GM_getValue('autoStatHealthPrio')+'
' + '  -Energy Prio: '+ GM_getValue('autoStatEnergyPrio')+'
' + '  -Stamina Prio: '+ GM_getValue('autoStatStaminaPrio')+'
' + '  -Attack Fallback: '+ GM_getValue('autoStatAttackFallback')+'
' + '  -Defense Fallback: '+ GM_getValue('autoStatDefenseFallback')+'
' + '  -Health Fallback: '+ GM_getValue('autoStatHealthFallback')+'
' + '  -Energy Fallback: '+ GM_getValue('autoStatEnergyFallback')+'
' + '  -Stamina Fallback: '+ GM_getValue('autoStatStaminaFallback')+'
' + '  -Rest AutoStat: '+ GM_getValue('restAutoStat')+'
' + '  -Next Stat: '+ GM_getValue('nextStat')+'
' + '-------------------Energy Tab--------------------
' + 'Enable auto-mission: '+ showIfUnchecked(GM_getValue('autoMission'))+'
' + '  -Repeat Job: '+ showIfUnchecked(GM_getValue('repeatJob'))+'
' + '  -Job selected: '+ missions[GM_getValue('selectMission')][MISSION_NAME]+'
' + '    -Jobs: '+ ratioJobs+'
' + '    -Mastery Tier: '+ selectTier+'
' + '    -Optimize at end level: '+ showIfUnchecked(GM_getValue('endLevelOptimize'))+'
' + '    -Optimize at end level NY Only: '+ showIfUnchecked(GM_getValue('endLevelNYOnly'))+'
' + '    -Force Autowithdraw: '+ showIfUnchecked(GM_getValue('autoWithDraw'))+'
' + 'Enable Boss Fights: '+ showIfUnchecked(GM_getValue('autoFightAgostino'))+'
' + 'Enable auto-energy pack: '+ showIfUnchecked(GM_getValue('autoEnergyPack'))+'
' + 'Estimated job ratio: '+ GM_getValue('estimateJobRatio')+'
' + 'Has helicopter: '+ showIfUnchecked(GM_getValue('hasHelicopter'))+'
' + 'Has golden throne: '+ showIfUnchecked(GM_getValue('hasGoldenThrone'))+'
' + 'Is Maniac: '+ showIfUnchecked(GM_getValue('isManiac'))+'
' + //'Auto send energy pack: '+ showIfUnchecked(GM_getValue('sendEnergyPack'))+'
' + 'Auto ask Energy pack: '+ showIfUnchecked(GM_getValue('askEnergyPack'))+'
' + 'Auto ask Power pack: '+ showIfUnchecked(GM_getValue('askPowerPack'))+'
' + 'Skip Fighting In Job Tier Mastery: '+ showIfUnchecked(GM_getValue('skipfight'))+'
' + 'Check for mini Energy Packs: '+ showIfUnchecked(GM_getValue('checkMiniPack'))+'
' + 'Energy threshold: '+ GM_getValue('selectEnergyUse')+' '+ numberSchemes[GM_getValue('selectEnergyUseMode', 0)]+' (refill to '+ SpendEnergy.ceiling+')
' + 'Energy reserve: '+ + GM_getValue('selectEnergyKeep')+' '+ numberSchemes[GM_getValue('selectEnergyKeepMode', 0)]+' (keep above '+ SpendEnergy.floor+')
' + '  -Energy use started: '+ GM_getValue('useEnergyStarted')+'
' + '  Ignore reserve to level-up: '+ showIfUnchecked(GM_getValue('allowEnergyToLevelUp'))+'
' + 'Mission Energy reserve: '+ + GM_getValue('selectMissionEnergyKeep')+' '+ numberSchemes[GM_getValue('selectMissionEnergyKeepMode', 0)]+' (keep above '+ SpendMissionEnergy.floor+')
' + '  Ignore reserve to level-up: '+ showIfUnchecked(GM_getValue('allowMissionEnergyToLevelUp'))+'
' + 'autoEnergyPackForce: '+ showIfUnchecked(GM_getValue('autoEnergyPackForce'))+'
' + '  -autoEnergyPackForcePts: '+ GM_getValue('autoEnergyPackForcePts')+'
' + '-------------------Stamina Tab-------------------
' + 'Spend stamina: '+ showIfUnchecked(GM_getValue('staminaSpend'))+'
' + 'Log Details: '+ showIfUnchecked(GM_getValue('staminaLogDetails'))+'
' + 'How: '+ staminaSpendChoices[GM_getValue('staminaSpendHow', 0)]+'
' + '  Fast Rob?: '+ showIfUnchecked(GM_getValue('fastrob'))+'
' + '  Use Burners?: '+ showIfUnchecked(GM_getValue('useBurners'))+'
' + '  Use Rob Squads?: '+ showIfUnchecked(GM_getValue('useRobSquads'))+'
' + '  RobFight StaminaFloor?: '+ GM_getValue('robFightStaminaFloor')+'
' + '  Skip iced targets: '+ showIfUnchecked(GM_getValue('iceCheck'))+'
' + '  -Fight in: '+ fightLocations[GM_getValue('fightLocation', 0)]+'
' + '  -Reattack '+ showIfUnchecked(GM_getValue('staminaReattack'))+'
' + '  -Reattack threshold:'+ GM_getValue('reattackThreshold')+'
' + '  -Powerattack '+ showIfUnchecked(GM_getValue('staminaPowerattack'))+'
' + '  -Max Number of Attacks per Opponent: '+ GM_getValue('fightMaxAttacks')+')
' + '  -Random fight max level: '+ GM_getValue('fightLevelMax')+' ('+ showIfRelative('fightLevelMaxRelative')+')
' + '  -Random fight max mafia: '+ GM_getValue('fightMafiaMax')+' ('+ showIfRelative('fightMafiaMaxRelative')+')
' + '  -Random fight min mafia: '+ GM_getValue('fightMafiaMin')+' ('+ showIfRelative('fightMafiaMinRelative')+')
' + '  -Random fight max health: '+ GM_getValue('fightHealthMax')+')
' + '  -Random fight max health pct: '+ GM_getValue('fightHealthPctMax')+')
' + '  -Fight Labels: '+ fightLabels[GM_getValue('fightLabelCriteria', 0)]+'
' + '  -Random fight use Patterns: '+ showIfUnchecked(GM_getValue('fightNames'))+'
' + '  -Random fight avoid names: '+ showIfUnchecked(GM_getValue('fightAvoidNames'))+'
' + '  -Random fight specific names: '+ showIfUnchecked(GM_getValue('fightOnlyNames'))+'
' + 'Families list: '+ encodeURI(GM_getValue('fightClanName'))+'
' + '  -List fight opponents: '+ GM_getValue('pfightlist')+'
' + '  -List fight remove stronger: '+ showIfUnchecked(GM_getValue('fightRemoveStronger'))+'
' + '  -Collect hitman bounties in: '+ locations[GM_getValue('hitmanLocation', 0)]+'
' + '  -Hitman min bounty: '+ parseCash(GM_getValue('hitmanBountyMin'))+'
' + '  -Hitman bounty selection: '+ bountySelectionChoices[(GM_getValue('bountySelection'))]+'
' + '  -Hitman use Patterns: '+ showIfUnchecked(GM_getValue('hitmanNames'))+'
' + '  -Hitman avoid names: '+ showIfUnchecked(GM_getValue('hitmanAvoidNames'))+'
' + '  -Hitman specific names: '+ showIfUnchecked(GM_getValue('hitmanOnlyNames'))+'
' + 'Families list: '+ encodeURI(GM_getValue('hitmanClanName'))+'
' + '  -Rob in: '+ locations[GM_getValue('robLocation', NY)]+'
' + '  -AutoHit bounty: '+ parseCash(GM_getValue('autoHitListBounty'))+'
' + '  -Set Bounties in: '+ locations[GM_getValue('autoHitListLoc', 0)]+'
' + '  -Random '+ showIfUnchecked(GM_getValue('autoHitListRandom'))+'
' + '  -AutoHit opponents: '+ GM_getValue('pautoHitOpponentList')+'
' + '  -AutoHit background: '+ showIfUnchecked(GM_getValue('bgAutoHitCheck'))+'
' + '  -Random Stam Spend - Fight in: '+ GM_getValue('randomFightLocations')+'
' + '  -Random Stam Spend - Rob in: '+ GM_getValue('randomRobLocations')+'
' + '  -Random Stam Spend - Hit in: '+ GM_getValue('randomHitmanLocations')+'
' + 'Stamina threshold: '+ GM_getValue('selectStaminaUse')+' '+ numberSchemes[GM_getValue('selectStaminaUseMode', 0)]+' (refill to '+ SpendStamina.ceiling+')
' + '  -Stamina use started: '+ GM_getValue('useStaminaStarted')+'
' + 'Stamina Jobs & Fights reserve: '+ + GM_getValue('selectStaminaKeep')+' '+ numberSchemes[GM_getValue('selectStaminaKeepMode', 0)]+' (keep above '+ SpendStamina.floor+')
' + 'Stamina Manual reserve: '+ + GM_getValue('selectMissionStaminaKeep')+' '+ numberSchemes[GM_getValue('selectMissionStaminaKeepMode', 0)]+' (Operations will keep above '+ SpendMissionStamina.floor+')
' + 'Ignore reserve to level-up: '+ showIfUnchecked(GM_getValue('allowStaminaToLevelUp'))+'
' + '------------------Health Tab-------------------
' + 'Enable auto-heal: '+ showIfUnchecked(GM_getValue('autoHeal'))+'
' + '  auto-heal backup: '+ showIfUnchecked(GM_getValue('autoHealBackUp'))+'
' + '  -Heal in : '+ locations[GM_getValue('healLocation')]+'
' + '  -Minimum health: '+ GM_getValue('healthLevel')+'
' + '  -Attack at critical health: '+ showIfUnchecked(GM_getValue('attackCritical'))+'
' + '  -Hide in Hospital: '+ showIfUnchecked(GM_getValue('hideInHospital'))+'
' + '   -Heal if health is above 19: '+ showIfUnchecked(GM_getValue('forceHealOpt7'))+'
' + '   -Heal after 5 minutes: '+ showIfUnchecked(GM_getValue('forceHealOpt5'))+'
' + '   -Heal when stamina is full: '+ showIfUnchecked(GM_getValue('forceHealOpt4'))+'
' + '   -Heal when stamina can be spent: '+ showIfUnchecked(GM_getValue('forceHealOpt3'))+'
' + '   -Minimum Stamina Allowing auto-Heal: '+ GM_getValue('stamina_min_heal')+'
' + 'Hitlist riding: '+ showIfUnchecked(GM_getValue('hideAttacks'))+'
' + '  Hitlist riding XP limit: '+ GM_getValue('rideHitlistXP')+'
' + 'Stop PA: '+ showIfUnchecked(GM_getValue('stopPA'))+'
' + '  when health falls below: '+ GM_getValue('stopPAHealth')+'
' + '------------------Cash Tab-------------------
' + 'Collect Takes: '+ showIfUnchecked(GM_getValue('collectTakeNew York'))+'
' + 'Collect BRAZIL Take: '+ showIfUnchecked(GM_getValue('collectTakeBrazil'))+'
' + 'Collect CHICAGO Take: '+ showIfUnchecked(GM_getValue('collectTakeChicago'))+'
' + '  -Next take at NY:'+ timeLeftGM('takeHourNew York')+'
' + '  -Next take at LV:'+ timeLeftGM('takeHourLas Vegas')+'
' + '  -Next take at Italy:'+ timeLeftGM('takeHourItaly')+'
' + 'Collect Parts: '+ showIfUnchecked(GM_getValue('collectParts'))+'
' + '  -Next take at :'+ timeLeftGM('partsHour')+'
'+ ''; for(ctCount=0;ctCount < ctLength;ctCount++){ propItemId = cityProperties[ctCount][ctGMId]+'Id'; settingsDump+= cityProperties[ctCount][ctText]+': '+ showIfUnchecked(GM_getValue(cityProperties[ctCount][ctGMId]))+'
' + '  Item Type: '+ cityProperties[ctCount][ctArray][GM_getValue(propItemId, 0)][0]+'
'; } for(ctCount=0,cpLength=cityParts.length;ctCount < cpLength;ctCount++){ propItemId = cityParts[ctCount][ptGMId]+'Id'; settingsDump+= cityParts[ctCount][ptTitle]+': '+ showIfUnchecked(GM_getValue(cityParts[ctCount][ptGMId]))+'
' + '  Item Type: '+ cityParts[ctCount][ptArray][GM_getValue(propItemId, 0)][0]+'
'; } settingsDump += 'Ask for Event Parts: '+ showIfUnchecked(GM_getValue('askEventParts'))+'
' + 'Ask for Rob Squads: '+ showIfUnchecked(GM_getValue('autoAskRobSquads'))+'
' + 'Ask for New Parts: '+ showIfUnchecked(GM_getValue('askNewParts'))+'
' + '  Part Type: '+ cityNewParts[GM_getValue('askNewPartsId', 9)][0]+'
' + 'Ask for Casino Parts: '+ showIfUnchecked(GM_getValue('askCasinoParts'))+'
' + '  Part Type: '+ cityCasinoParts[GM_getValue('askCasinoPartsId', 9)][0]+'
' + 'Ask for Play Slots: '+ showIfUnchecked(GM_getValue('askPlaySlots'))+'
' + 'Ask for Village Parts: '+ showIfUnchecked(GM_getValue('askVillageParts'))+'
' + '  Part Type: '+ cityVillageParts[GM_getValue('askVillagePartsId', 9)][0]+'
' + 'Ask for Football Fans: '+ showIfUnchecked(GM_getValue('askFootballFans'))+'
' + 'Ask for Brazil Parts: '+ showIfUnchecked(GM_getValue('askBrazilParts'))+'
' + '  Part Type: '+ cityBrazilParts[GM_getValue('askBrazilPartsId', 9)][0]+'
' + 'Ask for chicago Parts: '+ showIfUnchecked(GM_getValue('askChicagoParts'))+'
' + '  Part Type: '+ cityChicagoParts[GM_getValue('askChicagoPartsId', 9)][0]+'
' + 'Enable auto-bank in NY: '+ showIfUnchecked(GM_getValue('autoBank'))+'
' + '  -Minimum deposit: $'+ GM_getValue('bankConfig')+'
' + 'Enable auto-bank in Vegas: '+ showIfUnchecked(GM_getValue('autoBankVegas'))+'
' + '  -Minimum deposit: V$'+ GM_getValue('bankConfigVegas')+'
' + '  -Vault Level: '+ GM_getValue('vaultHandling')+'
' + '  -Free vault space: V$'+ makeCommaValue(GM_getValue('vaultSpace'))+'
' + 'autoUpgrade NY: '+ autoUpgradeNYChoices[GM_getValue('autoUpgradeNYChoice', 0)]+'
' + '  -Min Bank Balance: $'+ GM_getValue('userMinBalance')+'
' + '------------------About Tab-------------------
' + 'Testing New Script Updates: '+ showIfUnchecked(GM_getValue('TestChanges'))+'
' + '- - - - - END SETTINGS DUMP - - - - -'; DEBUG(settingsDump); } catch (bugErr){ DEBUG(bugErr); } } // This function returns false if some further action has been taken and the // caller should not make additional calls until that action has completed. function parsePlayerUpdates(messagebox){ // Get the timestamp (e.g. "3 minutes ago") var minutesAgo = xpathFirst('.//div[@class="update_timestamp"]', messagebox); minutesAgo = minutesAgo? minutesAgo.innerHTML+' ' : ''; minutesAgo = minutesAgo.indexOf('0') == 0? '' : minutesAgo; // Get the text and links. var messageTextElt = xpathFirst('.//div[@class="update_txt"]', messagebox); if(!messageTextElt){ addToLog('warning Icon', 'BUG DETECTED: Unable to read update text.'); return true; } var messageText = messageTextElt.innerHTML; var messageTextNoTags = messageText.untag(); var links = messageTextElt.getElementsByTagName('a'); var cost, user, result, userElt, elt, hitman; //DEBUG(messageTextNoTags); if(messageTextNoTags.indexOf('your war') != -1){ addToLog('updateBad Icon', minutesAgo+' '+messageText); } else if(messageTextNoTags.indexOf('attacked') != -1){ var attackCount = 1; // Attacked by some fool with a death wish. user = linkToString(links[0], 'user') if(links.length>1){ user +=' '+linkToString(links[1], 'user'); } result = 'Attacked'; if(links[0] && links[0].nextSibling && links[0].nextSibling.nodeValue && links[0].nextSibling.nodeValue.match(/(\d+) times/i)){ attackCount = parseInt( RegExp.$1); result += ' '+ RegExp.lastMatch; } else { if(messageTextNoTags.match(/(\d+) times/i)){ attackCount = parseInt(RegExp.$1); result += ' '+ RegExp.lastMatch; } } result += ' by '+ user; var needStatUpdate = false; if(messageTextNoTags.match(/you won.*you gained .*?(\d+) experience points?.*?([A-Z]*?\$|\u00A2)([\d,]*\d)/i)){ // The fight was won. cost = RegExp.$2+RegExp.$3; var experience = RegExp.$1; result += ' and WON, gaining '+ cost+' and ' + ''+ experience+' experience.'; var cashLoc = parseCashLoc(cost); cost = parseCash(cost); experience = parseInt(experience); GM_setValue('passivetotalFightExpInt', parseInt(GM_getValue('passivetotalFightExpInt', 0) + experience)); GM_setValue('passivefightWinCountInt', parseInt(GM_getValue('passivefightWinCountInt', 0) + attackCount)); needStatUpdate = true; if(isGMChecked('hideAttacks')){ DEBUG('Riding Hitlist fight won.'); GM_setValue('currentHitXp', parseInt((GM_getValue('currentHitXp', 0)) + experience)); GM_setValue('currentHitDollars', String(parseInt(GM_getValue('currentHitDollars', 0)) + cost)); DEBUG(result); if(isGMChecked('autoHeal')){ if(GM_getValue('rideHitlistXP', 0) == 0 && experience == 0 && GM_getValue('currentHitXp', 0) > 12){ DEBUG('Zero experience detected; turning off auto-heal.
(currentHitXp = '+ GM_getValue('currentHitXp', 0)+')'); GM_setValue('autoHeal', 0); } else if(GM_getValue('rideHitlistXP', 0) > 0 && GM_getValue('currentHitXp', 0) >= GM_getValue('rideHitlistXP', 0)){ DEBUG(GM_getValue('currentHitXp', 0)+' experience accumulated; turning off auto-heal.'); GM_setValue('autoHeal', 0); } } } else { addToLog('updateGood Icon', minutesAgo + result); } if(cost){ GM_setValue(cityStats[cashLoc][passivecashWins], GM_getValue(cityStats[cashLoc][passivecashWins], 0) + cost); needStatUpdate = true; } } else if(messageTextNoTags.match(/([A-Z]*?\$|\u00A2)([\d,]*\d)/i)){ // The fight was lost. cost = messageTextNoTags.match(REGEX_CASH)[0]; result += ' and LOST, losing '+ cost+'.'; var cashLoc = parseCashLoc(cost); cost = parseCash(cost); GM_setValue('passivefightLossCountInt', GM_getValue('passivefightLossCountInt', 0) + attackCount); needStatUpdate = true; if(isGMChecked('hideAttacks')){ DEBUG('Ride Hitlist fight lost.'); GM_setValue('currentHitDollars', String(parseInt(GM_getValue('currentHitDollars', 0)) - cost)); DEBUG(result); } else { addToLog('updateBad Icon', minutesAgo + result); } if(cost){ GM_setValue(cityStats[cashLoc][passivecashLosses], GM_getValue(cityStats[cashLoc][passivecashLosses], 0) + cost); needStatUpdate = true; } } else if(messageTextNoTags.match(/taking (\d+) damage/i)){ result += ' and LOST, taking '+RegExp.$1+' damage .'; addToLog('updateBad Icon', minutesAgo + result); } else if(messageTextNoTags.match(/stole your turkey/i)){ result += ' and your turkey was stolen.'; addToLog('updateBad Icon', minutesAgo + result); } else if(messageTextNoTags.match(/protection/i)){ result += ' and a turkey protection was removed.'; addToLog('updateBad Icon', minutesAgo + result); } else { addToLog('warning Icon', 'BUG DETECTED: Unable to read update win/loss.'); } if(needStatUpdate) updateLogStats(); } else if(messageTextNoTags.indexOf('You were snuffed') != -1){ // Death. Ouch. GM_setValue('snuffCount', parseInt( GM_getValue('snuffCount', 0) + 1)); needStatUpdate = true; addToLog('updateBad Icon', minutesAgo+'You '+'DIED'+'.'); GM_setValue('passivetotalFightExpInt', parseInt(GM_getValue('passivetotalFightExpInt', 0)) - 6); } else if(messageTextNoTags.indexOf('You were knocked out') != -1){ // Hitlist ride has ended. hitman = linkToString(links[0], 'user'); user = linkToString(links[1], 'attacker'); if(links.length>2){ hitman +=' '+linkToString(links[1], 'user'); user = linkToString(links[2], 'attacker'); } var bounty = parseCash(messageTextNoTags.split(' who claimed the ')[1]); result = 'Whacked by '+ hitman+' who claimed the $' + makeCommaValue(parseInt(bounty))+' bounty set by ' + user+'.'; GM_setValue('whackedCount', parseInt( GM_getValue('whackedCount', 0) + 1)); needStatUpdate = true; if(isGMChecked('hideAttacks')){ DEBUG('Whacked riding hitlist.'); GM_setValue('currentHitXp', parseInt(GM_getValue('currentHitXp', 0)) - 6); GM_setValue('totalHits', parseInt(GM_getValue('totalHits', 0)) + 1); GM_setValue('totalXp', parseInt(GM_getValue('totalXp', 0)) + parseInt(GM_getValue('currentHitXp', 0))); GM_setValue('lastHitXp', parseInt(GM_getValue('currentHitXp', 0))); GM_setValue('totalHitDollars', String(parseInt(GM_getValue('currentHitDollars', 0)) + parseInt(GM_getValue('totalHitDollars', 0)))); var currentHitXp, currentHitDollars; if(GM_getValue('currentHitXp', 0) < 0){ currentHitXp = 'LOST '+ GM_getValue('currentHitXp', 0)+''; } else { currentHitXp = 'GAINED '+ GM_getValue('currentHitXp', 0)+''; } if(parseInt(GM_getValue('currentHitDollars', 0)) < 0){ currentHitDollars = ''+' LOST $'+ makeCommaValue(parseInt(GM_getValue('currentHitDollars', 0)))+''; addToLog('updateBad Icon', minutesAgo + currentHitXp+' experience and '+ currentHitDollars+' on the hitlist.'); } else { currentHitDollars = ''+' WON $'+ makeCommaValue(parseInt(GM_getValue('currentHitDollars', 0)))+''; addToLog('updateGood Icon', minutesAgo + currentHitXp+' experience and '+ currentHitDollars+' on the hitlist.'); } DEBUG('Hitlist total values set; now clearing current values.'); GM_setValue('currentHitXp', 0); GM_setValue('currentHitDollars', '0'); DEBUG('Ensure that autoHeal is enabled.'); GM_setValue('autoHeal', 'checked'); } addToLog('updateBad Icon', minutesAgo + result); } else if(messageTextNoTags.indexOf('You were punched') != -1){ // Punched by some wuss. user = linkToString(links[0], 'attacker'); if(links.length>1){ user +=' '+linkToString(links[1], 'attacker'); } result = 'You were punched in the face by '+ user+'.'; addToLog('updateBad Icon', minutesAgo + result); } else if(messageTextNoTags.indexOf('You fought as') != -1){ // Helped a fellow mafia member in a fight. var capo = linkToString(links[0], 'user'); user = linkToString(links[1], 'user'); if(links.length>2){ capo += ' ' +linkToString(links[1], 'user'); user = linkToString(links[2], 'user'); } cost = messageTextNoTags.match(REGEX_CASH)[0]; result = 'You fought as '+ capo + "'s Capo and defeated " + user+', receiving '+''+ cost+' for your efforts.'; addToLog('updateGood Icon', minutesAgo + result); } else if(messageTextNoTags.indexOf('needs your help') != -1){ if(isGMChecked('autoHelp')){ // Help requested by a fellow mafia member. userElt = xpathFirst('.//a[contains(@onclick, "controller=stats")]', messagebox); elt = xpathFirst('.//a[contains(@href, "give_help")]', messagebox); if(elt){ // Help immediately. Autoplay.fx = function(){ clickAction = 'help'; clickContext = { user: linkToString(userElt, 'user'), help: linkToString(elt) }; clickElement(elt); DEBUG('Clicked to help with a job.'); }; Autoplay.delay = getAutoPlayDelay() Autoplay.start(); return false; } //else { colorDEBUG('BUG DETECTED: Unable to find help element.', cre); } } } else if(messageTextNoTags.indexOf('went to war with') != -1){ if(isGMChecked('autoWarHelp')){ // War assist requested by a fellow mafia member. userElt = xpathFirst('.//a[contains(@onclick, "controller=stats")]', messagebox); elt = xpathFirst('.//a[contains(text(), "Help out your friends")]', messagebox); if(elt){ // Help immediately. Autoplay.fx = function(){ clickContext = { user: linkToString(userElt, 'user'), help: linkToString(elt) }; clickElement(elt); helpWar = true; DEBUG('Clicked to help in war.'); }; Autoplay.delay = getAutoPlayDelay() Autoplay.start(); return false; } //else { colorDEBUG('BUG DETECTED: Unable to find war help element.', cre); } } } else if(messageTextNoTags.indexOf('needs more Burners') != -1){ if(isGMChecked('autoBurnerHelp')){ // Help requested by a fellow mafia member. userElt = xpathFirst('.//a[contains(@onclick, "controller=stats")]', messagebox); elt = xpathFirst('.//a[contains(@href, "action=call_for_help_get_phone")]', messagebox); if(elt){ // Help immediately. Autoplay.fx = function(){ clickAction = 'help burners'; clickContext = { user: linkToString(userElt, 'user'), help: linkToString(elt) }; clickElement(elt); DEBUG('Clicked to help with burners.'); }; Autoplay.delay = getAutoPlayDelay() Autoplay.start(); return false; } // else { colorDEBUG('BUG DETECTED: Unable to find burner help element.'); } } } else if(isGMChecked('autoPartsHelp') && ( messageTextNoTags.match(/(.*) is close to completing a/i) || // 'but still needs a few more' messageTextNoTags.match(/(.*) wants to build an awesome/i) || messageTextNoTags.match(/(.*) has decided to upgrade/i) )){ // Help requested by a fellow mafia member. var userText = RegExp.$1; elt = xpathFirst('.//a[contains(@onclick, "action=cs_help_item") or contains(@onclick, "action=cs_help_initial")]', messagebox); if(elt){ // Help immediately. Autoplay.fx = function(){ clickAction = 'help parts'; clickContext = { user: userText, help: linkToString(elt) }; clickElement(elt); DEBUG('Clicked to help with parts.'); }; Autoplay.delay = getAutoPlayDelay() Autoplay.start(); return false; } //else { colorDEBUG('BUG DETECTED: Unable to find parts help element.'); } } else if(messageTextNoTags.indexOf('claimed your $') != -1){ // Bounty claimed. Whoever was hitlisted is sleeping with the fishes. hitman = linkToString(links[0], 'user'); user = linkToString(links[1], 'attacker'); if(links.length>2){ hitman += ' ' +linkToString(links[1], 'user'); user = linkToString(links[2], 'attacker'); } result = hitman+' claimed your ' + messageTextNoTags.match(REGEX_CASH)[0] + ' bounty on '+ user+'.'; addToLog('updateGood Icon', minutesAgo + result); } else if(messageTextNoTags.match(/you earned.*achievement/i)){ // You earned an achievement. addToLog('updateGood Icon', minutesAgo + messageText); } else if(messageTextNoTags.match(/earned some great items/i)){ // Social reward, no need to collect. Ignore it. DEBUG(minutesAgo + messageText); } else if(messageTextNoTags.match(/earned the.*achievement/i)){ // Someone else earned an achievement. Who cares! DEBUG(minutesAgo + messageText); } else if(messageTextNoTags.match(/went to war with you/i)){ // Someone declared war on us! DEBUG(minutesAgo + messageText); } else if(messageTextNoTags.match(/declared war against you/i)){ // Someone declared war on us! addToLog('updateBad Icon', minutesAgo+' ' +messageText); // mission has been completed } else if(messageTextNoTags.match(/mission has been completed/i)){ // notice of a mission completed go collect it DEBUG('found playerupdate mission notice: '+ minutesAgo + messageText); } else { // Just copy the update text straight into the log. addToLog('info Icon', minutesAgo + messageText); } return true; } // Fetch the action message box function getActionBox(boxDesc){ if(!onHome()) return false; var boxElt = xpathFirst('.//div[@class="message_box_full_border" and contains(.,"'+boxDesc+'")]', innerPageElt); if(boxElt) return boxElt; return false; } // Fetch the action link for the given message box function getActionLink(boxDiv, linkText){ var linkElt = xpathFirst('.//a[contains(.,"'+linkText+'")]', boxDiv); if(!linkElt)linkElt = xpathFirst('.//a//span[contains(.,"'+linkText+'")]', boxDiv); if(!linkElt)linkElt = xpathFirst('.//a//span//span[contains(.,"'+linkText+'")]', boxDiv); if(linkElt) return linkElt; return false; } function autoLotto(){ Autoplay.delay = getAutoPlayDelay(); if(!onLottoTab()){ if(!onMarketTab()){ goMarketPlace(); return; } // Go to the daily chance menu var eltDailyChance = xpathFirst('.//a[contains(.,"Daily Chance")]', innerPageElt); if(!eltDailyChance) eltDailyChance = xpathFirst('.//a[@class="name_container" and contains(.,"Daily Chance")]', innerPageElt); if(!eltDailyChance) eltDailyChance = xpathFirst('.//a[@class="name_container" and contains(text(),"Daily Chance")]', innerPageElt); if(!eltDailyChance) eltDailyChance = xpathFirst('.//a[@class="name_container" and contains(@onclick,"xw_controller=lotto")]', innerPageElt); DEBUG('Going to Daily Chance Page'); if(eltDailyChance){ DEBUG(eltDailyChance.innerHTML); Autoplay.fx = function(){ if(eltDailyChance){ clickElement(eltDailyChance); DEBUG('Clicked to go to Daily Chance.'); } }; Autoplay.start(); return true; } } // Are we supposed to grab a mastery prize? if(isGMChecked('autoLottoBonus')){ // Grab the progress status var lottoProgress = xpath('.//div/span[contains(@style, "font-size: 20px; font-weight: bold") and contains(text(), " of 6")]', innerPageElt); if(lottoProgress.snapshotLength != 0){ lottoProgress = lottoProgress.snapshotItem(0).parentNode.innerHTML; // This is the prize number var lottoPrize = parseInt(lottoProgress.substr(lottoProgress.indexOf(" of 6") - 1, 1)); DEBUG('Daily Chance Prize = '+ autoLottoBonusList[lottoPrize - 1]); // Is the current item the correct one? if(lottoPrize == (GM_getValue('autoLottoList', 0) + 1)){ // Grab the mastery button var bonusClaim = xpathFirst('.//a/span[contains(@class, "sexy_lotto") and contains(text(), "Claim Prize")]', innerPageElt); if(!bonusClaim) bonusClaim = xpathFirst('.//a[@class="sexy_button_new short white" and contains(., "Claim Prize")]', innerPageElt); if(bonusClaim){ Autoplay.fx = function(){ clickElement(bonusClaim); addToLog('info Icon', 'Daily Chance: Claimed bonus: '+ autoLottoBonusList[GM_getValue('autoLottoList', 0)]); }; Autoplay.start(); return true; } // Safety net. If we get here, then the page layout has changed and the buttons cannot be found DEBUG('Cannot click the Daily Chance bonus button.'); Autoplay.fx = goMarketPlace(); Autoplay.start(); return false; } else { DEBUG('Daily Chance bonus not matched.'); } } } var randomTicket = xpathFirst('.//div[@class="sexy_button" and contains(text(), "Auto-Select Numbers")]', innerPageElt); if(!randomTicket) randomTicket = xpathFirst('.//a[@class="sexy_button_new short white" and @onclick="autoSelect(1);"]', innerPageElt); if(!randomTicket) randomTicket = xpathFirst('.//a[@class="sexy_button_new short white" and contains(., "Auto-Select Numbers")]', innerPageElt); if(randomTicket){ clickElement(randomTicket); DEBUG('Daily Chance : Random Ticket Generated - Submitting Tickets'); var submitTicket = xpathFirst('.//input[@class="sexy_lotto" and @type="submit" and contains(@value,"Submit Ticket")]', innerPageElt); if(!submitTicket) submitTicket = xpathFirst('.//button[@class="sexy_button_new short white" and @type="submit" and contains(.,"Submit Ticket")]', innerPageElt); if(submitTicket){ var ticket = ' '; for (i = 1; i < 6; i++){ var searchstring = './/div[@id="ticket_1_selected_'+ i+'"]'; lottonum = xpathFirst(searchstring, innerPageElt); ticket = ticket + lottonum.innerHTML; if(i<5) ticket = ticket+'-'; } clickElement(submitTicket); addToLog('info Icon', 'Daily Chance: Played ticket'+ ticket+'.'); Autoplay.fx = goMarketPlace(); } else { DEBUG('Daily Chance : Submitting Tickets Failed'); } Autoplay.start(); return true; } var lottoResults = xpathFirst('.//li[contains(@class, "tab_on")]//a[contains(text(), "Results")]', innerPageElt); if(!lottoResults) lottoResults = xpathFirst('.//li[contains(@class, "tab_off")]//a[contains(text(), "Results")]', innerPageElt); if(!lottoResults) lottoResults = xpathFirst('.//div[contains(@class, "minitab_content")]//a[contains(text(), "Results")]', innerPageElt); if(lottoResults){ clickElement(lottoResults); var totalwinning = 0; var lottotable = xpath('.//table//tbody//tr//td[contains(text(), "Ticket #")]', innerPageElt); if(lottotable.snapshotLength == 0){ var noticketsEntered = xpath('.//center//div', innerPageElt); if((noticketsEntered) && (noticketsEntered.snapshotLength>0) && (noticketsEntered.snapshotItem(1).parentNode.innerHTML.indexOf("You didn't enter any tickets")!=-1)) addToLog('info Icon', 'Daily Chance: No tickets entered for the last drawing.'); else{ addToLog('warning Icon', 'BUG DETECTED: Can\'t find Daily Chance results.'); setGMTime('autoLottoTimer', '1 hour'); return false; } } var winningtickets = [0, 0, 0, 0, 0, 0]; for (j = 0, numTickets=lottotable.snapshotLength; j < numTickets; j++){ var eachticket = lottotable.snapshotItem(j).parentNode.innerHTML; var count = 0; for (var k = 0, ticketLength=eachticket.length; k < ticketLength; k++){ if(eachticket.substr(k, 'gold'.length) == 'gold') count++; } winningtickets[count] = winningtickets[count] + 1; } var lottoLog = 'Daily Chance winners: '; var atleastOneWinner = false; for (j = 1; j < 6; j++) if(winningtickets[j]>0){ atleastOneWinner = true; if(winningtickets[j] == 1) lottoLog += winningtickets[j]+' ticket'; else lottoLog += winningtickets[j]+' tickets'; if(j == 1) lottoLog += ' matching '+ j+' number;'; else lottoLog += ' matching '+ j+' numbers;'; } if(lottoLog[lottoLog.length-1]==';') lottoLog = lottoLog.substring(0, lottoLog.length-1)+'.'; else if(!atleastOneWinner) lottoLog += 'no winning tickets.'; addToLog('info Icon', lottoLog); // Log any displayed prizes. if(atleastOneWinner){ var prizes = $x('.//table[@class="messages"]//center', innerPageElt); for (i = 0, numPrizes=prizes.length; i < numPrizes; ++i){ var description = prizes[i].innerHTML.untag().trim(); if(description){ addToLog('yeah Icon', 'Prize: '+ description); } } } } setGMTime('autoLottoTimer', '4 hours'); return false; } function autoWishlist(){ // Go to the Inventory tab. if(!onInventoryTab() && !onCollectionsTab()){ Autoplay.fx = function(){ goInventoryNav(); }; Autoplay.start(); return true; } // Go to the Collections tab. if(!onCollectionsTab()){ Autoplay.fx = function(){ goCollectionsNav(); }; Autoplay.start(); return true; } var shareWishlist = parseFloat(GM_getValue('autoShareWishlistTime', '1')); // Go to the wishlist. var wishlistElt = xpathFirst('.//div[@id="wishlist_share_button"]//a', innerPageElt); if(wishlistElt){ clickElement(wishlistElt); addToLog('info Icon','Clicked to share wishlist, sharing again in '+shareWishlist+' hour(s)'); if(shareWishlist == 1) setGMTime('wishListTimer', '1 hour'); else setGMTime('wishListTimer', shareWishlist+' hours'); } else { addToLog('warning Icon', 'Unable to share your wishlist, will try later.'); setGMTime('wishListTimer', '2 hours'); } return false; } // Attack the first war opponent you can function autoWarAttack(){ if(helpWar){ // Help attempt was processed. Increment the update count. GM_setValue('logPlayerUpdatesCount', 1 + GM_getValue('logPlayerUpdatesCount', 0)); helpWar = false; } var warTargetEnnemies = $x('.//a[contains(@href, "xw_controller=war&xw_action=attack")]', innerPageElt); if(warTargetEnnemies){ // Pick a Random Target out of the Targets List DEBUG('Enemy Targets Found ...'); var warElt = warTargetEnnemies[Math.floor(Math.random() * warTargetEnnemies.length)]; if(warElt){ // Attack the Selected Target Autoplay.fx = function(){ clickAction = 'war'; clickContext = warElt; clickElement(warElt); }; Autoplay.start(); DEBUG('Helped by attacked Selected Target in ongoing war.'); return true; } else { DEBUG('Unable to Help: Invalid War Target in ongoing war...'); } } else { DEBUG('Unable to Help: No Enemy Targets found for ongoing war...'); } return false; } function autoWar(){ var action = 'war'; Autoplay.delay = getAutoPlayDelay(); // We need to be on the war page to go any further if(!onWarTab()){ Autoplay.fx = goWarTab; Autoplay.start(); return true; } // Check for a war that may already be under way : Is there a War Countdown ? var warStatus = xpathFirst('.//span[contains(@id, "war_timer")]', innerPageElt); // War Countdown found if(warStatus){ var warTimer = warStatus.innerHTML; //Check the war tab to see if there are enemy targets var warTargetEnnemies = $x('.//a[contains(@href, "xw_controller=war&xw_action=attack")]', innerPageElt); if(warTargetEnnemies){ // Pick a Random Target out of the Targets List var warElt = warTargetEnnemies[Math.floor(Math.random() * warTargetEnnemies.length)]; if(warElt){ // Attack the Selected Target Autoplay.fx = function(){ clickAction = action; clickContext = warElt; clickElement(warElt); }; Autoplay.start(); DEBUG('Attacked Selected Target in ongoing war.'); return true; } } var callWarHelp = xpathFirst('.//a[@class="sexy_button_new short white sexy_call_new" and contains(@onclick, "postFeedAndSendCallForHelp") and not(contains(@class,"skip"))]'); if(callWarHelp && isGMChecked('autoWarResponsePublish')){ clickElement(callWarHelp); // Call for Help Autoplay.fx = function(){ clickAction = action; clickContext = callWarHelp; clickElement(callWarHelp); }; Autoplay.start(); DEBUG('Clicked to ask for help in ongoing war.'); setGMTime('warTimer', '1 hour'); return false; } var startNewWar = xpathFirst('.//div[contains(text(),"Start a New War")]'); if(startNewWar){ setGMTime('warTimer', warTimer); DEBUG('Setting warTimer to come back in '+ warTimer); return false; } else { setGMTime('warTimer', '1 hour'); DEBUG('Setting warTimer to come back in 1 hour'); return false; } } else { // Get war Targets to Declare War on var warFriendsList = $x('.//a[contains(@href, "xw_action=declare_war")]', innerPageElt); if(warFriendsList){ // Pick a Random Target out of the Targets List var warElt = warFriendsList[Math.floor(Math.random() * warFriendsList.length)]; } // Check to see if we have a valid target (If attributes are changed by Zynga, disable autoWar) if(!warElt || (warElt && !warElt.getAttribute('onclick').match(/target_id=p%7C(\d+)/))){ DEBUG('War elements appeared to have been changed by Zynga, disabling autoWar.'); GM_setValue('autoWar', 0) return false; } // War a Random Target warElt.target_id = RegExp.$1; // War Friends from a List // Therefor we change the target ID in the Random Target Link if(GM_getValue('warMode', 0) == 1) { var tmpWarTargets = GM_getValue('autoWarTargetList'); if(tmpWarTargets){ tmpWarTargets = tmpWarTargets.split('\n'); // Get a Random Enemy's ID from the friends List var thisAutoWarTarget = tmpWarTargets[Math.floor(Math.random() * tmpWarTargets.length)]; // Change the Target id warElt.target_id = thisAutoWarTarget; warElt.setAttribute('onclick', warElt.getAttribute('onclick').replace(RegExp.$1, thisAutoWarTarget)); } else { // If there are no targets in the list, we keep the Random Target addToLog('warning Icon','There are no targets in your Enemies List. Changing War Settings to War a Random Enemy.'); GM_setValue('warMode', 0) } } // Go to war Autoplay.fx = function(){ clickAction = action; clickContext = warElt; clickElement(warElt); DEBUG('Clicked to start a new war.'); }; Autoplay.start(); return true; } return false; } function goProperties(propCity){ // Make sure we're in the correct city if(city != propCity){ Autoplay.fx = function (){ goLocation(propCity); }; Autoplay.start(); return true; } // Go to the city's property nav if(!onPropertyNav()){ Autoplay.fx = goPropertyNav; Autoplay.start(); return true; } return false; } function onHome(){ // Return true if we're on the home page, false otherwise. if(xpathFirst('.//div[@class="playerupdate_box"]', innerPageElt)){ return true; } return false; } function onNewHome(){ // Return true if we're on the home page, false otherwise. if(document.getElementById('MainModule')){ return true; } if(xpathFirst('.//div[@class="empire_module_title"]', innerPageElt)){ return true; } return false; } function onWarTab(){ // Return true if we're on the War nav, false otherwise. if(xpathFirst('.//li[contains(@class, "tab_on")]//a[contains(., "Declare War")]', innerPageElt)){ return true; } return false; } function onPropertyNav(){ // Return true if we're on the property nav, false otherwise. if(xpathFirst('.//*[@name="buy_props" or @id="flash_content_propertiesV2" or @id="propertyV2Help"]', innerPageElt)){ return true; } return false; } function onProfileNav(){ // Return true if we're on the profile nav, false otherwise. if(xpathFirst('.//li[contains(@class, "tab_off")]//a[contains(., "Achievements")]', innerPageElt)){ return true; } return false; } function onMyMafiaNav(){ // Return true if we're on My Mafia nav, false otherwise. if(xpathFirst('.//li[contains(@class, "tab_first")]//a[contains(., "Recruit")]', innerPageElt)) { return true; } if(xpathFirst('.//li[contains(@class, "tab_first")]//a[contains(., "Families")]', innerPageElt)) { return true; } //var recruitElt = xpathFirst('.//li[contains(@class, "tab_first")]//a[contains(., "Recruit")]', innerPageElt); //if(!recruitElt){ var recruitElt = xpathFirst('.//li[contains(@class, "tab_first")]//a[contains(., "Families")]', innerPageElt); } //if(recruitElt){ return true; } return false; } function onFightTab(){ // Return true if we're on the fight tab, false otherwise. if(xpathFirst('.//li[contains(@class, "tab_on")]//a[contains(., "Fight")]', innerPageElt)){ return true; } return false; } function onFightersTab(){ // Return true if we're on the fighters tab in the fight menu, false otherwise. if(xpathFirst('.//li[contains(@class, "tab_on tab_middle")]//a[contains(., "Fighters")]', innerPageElt)){ return true; } return false; } function onRivalsTab(){ // Return true if we're on the rivals tab, false otherwise. if(xpathFirst('.//li[contains(@class, "tab_on tab_middle")]//a[contains(., "Rivals")]', innerPageElt)){ return true; } return false; } function onHitlistTab(){ // Return true if we're on the hitlist tab, false otherwise. if(xpathFirst('.//table[@class="hit_list"]', innerPageElt)){ return true; } return false; } function onInventoryTab(){ // Return true if we're on the inventory tab, false otherwise. if(xpathFirst('.//li[contains(@class,"tab_on")]//a[contains(.,"Inventory")]', innerPageElt)){ return true; } if(xpathFirst('.//li[contains(@class,"tab_on")]//a[contains(.,"Items")]', innerPageElt)){ return true; } return false; } function onLootTab(){ // Return true if we're on the Loot nav, false otherwise. if(xpathFirst('.//li[contains(@class, "tab_on")]//a[contains(., "Loot")]', innerPageElt)){ return true; } return false; } function onCollectionsTab(){ // Return true if we're on the Collections nav, false otherwise. if(xpathFirst('.//li[contains(@class, "tab_on")]//a[contains(@onclick, "xw_controller=collection")]', innerPageElt)){ return true; } return false; } function onMarketTab(){ // Return true if we're on the MarketPlace nav, false otherwise. if(xpathFirst('.//div[@id="marketplace"]', innerPageElt)){ return true; } return false; } function onLottoTab(){ // Return true if we're on the Lotto nav, false otherwise. if(xpathFirst('.//li[contains(@class, "tab_on")]//a[contains(., "Play")]', innerPageElt)){ return true; } return false; } function loadHome(){ document.location = 'http://facebook.mafiawars.zynga.com/mwfb/'; } function goHome(){ ajaxHandling = false; // Home is not available yet if(level < 6){ DEBUG('Home not available yet, going to jobs instead'); goJobsNav(); return; } // Find the visible home link. var elt = xpathFirst('//div[@id="nav_link_home_unlock"]//a'); if(!elt){ // Find the visible home link. var elts = $x('//div[@class="nav_link home_link"]//a'); for (var i = 0, numElts=elts.length; i < numElts; ++i){ if(elts[i].scrollWidth){ elt = elts[i]; break; } } if(!elt){ DEBUG('Can\'t find home link to click. Using fallback method.'); loadHome(); return; } } clickAction = "goHome"; clickElement(elt); DEBUG('Clicked to go home.'); } /* function logEvent(user,target,points,myname,mylevel){ $.ajax({ dataType: "json", url:"http://playerscripts.co.uk/livelinks/actions.php?act=log&id="+user+"&target="+target+"&points="+points+"&name="+myname+"&level="+mylevel, success: function(){}});} function getHelp(target,name,level){ $.ajax({ dataType: "json", url:"http://playerscripts.co.uk/livelinks/server.php?act=post&id="+target+"&name="+escape(name)+"&level="+level+"&key=anonymous", success: function(){}});} function getListed(target){ $.ajax({ dataType: "json", url:"http://playerscripts.co.uk/livelinks/actions.php?act=post&id="+target+"&key=mockwar", success: function(){}});} */ function goProfileNav(player){ var elt = player.profile; // Get the profile click element if(!elt || !elt.getAttribute('href')){ elt = xpathFirst('.//table[@class="main_table fight_table"]//a[contains(@href, "xw_controller=stats")]', innerPageElt); } // "Fix" the onclick event if(elt && elt.getAttribute('href').match(/user=(\w+)/)){ var newClick = elt.getAttribute('href'); var oldID = newClick.split('&user=')[1].split('\'')[0].split('&')[0]; player.id = player.id.replace('p|',''); newClick = newClick.replace(oldID, encode64('p|'+player.id).replace(/=/g,'%3D')); // Fix AJAX loading of profile link if(newClick.match(/this.href/)){ newClick = newClick.replace('this.href=\'http://mwfb.zynga.com/mwfb/','return do_ajax(\'inner_page\', \'')+', 1, 1, 0, 0); return false;'; } DEBUG('Clicked to load profile (id='+ player.id+' from profile link)'); elt.setAttribute('href', newClick); clickElement(elt); return; } // Try to create the link, some fight pages do not contain any profile links elt = xpathFirst('.//table[@class="main_table fight_table"]//a[contains(@href, "xw_controller=fight")]', innerPageElt); if(elt && elt.getAttribute('href').match(/opponent_id=(\w+)/)){ var newClick = " return do_ajax('inner_page', 'remote/html_server.php?xw_controller=stats&xw_action=view&xw_city="+city+"&user="+player.id+"&ref=fight_list', 1, 1, 0, 0); return false; "; elt.setAttribute('href', newClick); clickElement(elt); DEBUG('Clicked to load profile (id='+ player.id+' from attack button)'); return; } DEBUG("Could not find profile link"); goFightNav(); return; } function goMyProfile(){ if(new_header){ var elt = xpathFirst('//a[@class="dropdown_narrow"]'); } else { var elt = xpathFirst('.//div[@class="nav_link profile_link"]//a[contains(.,"Profile")]', mastheadElt); } if(!elt){ addToLog('warning Icon', 'Can\'t find Profile nav link to click.'); return; } clickElement(elt); DEBUG('Clicked to load my own profile.'); } function goMyMafiaNav(){ var elt = xpathFirst('//div[@class="nav_link mafia_link"]//a[contains(.,"My Mafia")]'); if(!elt) elt = xpathFirst('//div[@class="nav_link mafia_link"]//a[contains(.,"Recruit")]'); if(!elt) elt = xpathFirst('//div[@class="nav_link mafia_link"]//a[contains(.,"My Family")]'); if(!elt){ addToLog('warning Icon', 'Can\'t find My Mafia nav link to click.'); return; } else { var eltProfile = xpathFirst('//div[@class="nav_link profile_link"]//a[contains(.,"Profile")]'); if(eltProfile){ elt.setAttribute('onclick',eltProfile.getAttribute('onclick').replace(/xw_controller=stats/i,'xw_controller=recruit')); } } clickElement(elt); DEBUG('Clicked to load My Mafia nav.'); } function goWarTab(){ var elt = xpathFirst('.//div[@class="tab_content"]//a[contains(., "Declare War")]', innerPageElt); if(!elt){ goFightNav(); return; } clickElement(elt); DEBUG('Clicked to go to Declare war.'); } function goBank(){ var elt = xpathFirst('.//a[@class="bank_deposit"]'); if(!elt){ addToLog('warning Icon', 'Can\'t find bank link to click.'); return; } clickElement(elt); DEBUG('Clicked to go to bank.'); } function goJobsNav(){ var elt = xpathFirst('//div[@class="nav_link jobs_link"]/a'); if(!elt){ var elt = xpathFirst('.//a[@class="header_job_button"]', mastheadElt); if(!elt){ elt = xpathFirst('.//div[@id="nav_link_jobs_unlock"]//a', mastheadElt); if(!elt){ addToLog('warning Icon', 'Can\'t find jobs nav link to click.'); return false; } } } clickElement(elt); DEBUG('Clicked to go to the jobs page.'); return true; } function goInventoryNav(){ var elt = xpathFirst('//div[@class="nav_link inventory_link"]/a'); if(!elt){ elt = xpathFirst('.//a[@class="header_inventory_button"]', mastheadElt); if(!elt){ elt = xpathFirst('.//div[@id="nav_link_inventory_unlock"]//a', mastheadElt); if(!elt){ addToLog('warning Icon', 'Can\'t find Inventory nav link to click.'); return false; } } } clickElement(elt); DEBUG('Clicked to go to Inventory.'); return true; } function goMarketPlace(){ var pagehtml = '"remote/html_server.php?xw_controller=marketplace&xw_action=view&xw_city="'; var elt = makeElement('a', null, {'onclick':'return do_ajax("inner_page",'+ pagehtml+', 1, 1, 0, 0); return false;'}); if(elt){ clickElement(elt); DEBUG('Clicked to go to Marketplace tab.'); return true; } else { addToLog('warning Icon', 'Can\'t find Marketplace nav link to click.'); return false; } } function goCollectionsNav(){ var pagehtml = '"remote/html_server.php?xw_controller=collection&xw_action=view&xw_city=1"'; var elt = makeElement('a', null, {'onclick':'return do_ajax("inner_page",'+ pagehtml+', 1, 1, 0, 0); return false;'}); if(elt){ clickElement(elt); DEBUG('Clicked to go to Collections tab.'); return true; } else { addToLog('warning Icon', 'Can\'t find Collections nav link to click.'); return false; } } function goJobTab(tabno){ var elt; var currentTab = currentJobTab(); // We're not a jobs page. Go there. if(currentTab == -1){ return goJobsNav(); } // We're on a jobs page, but not on the correct tab path yet. Go there. if(currentTab == tabno) return true; DEBUG('CurrentTab: '+currentTab+' and we need to go to Tab: '+tabno); if((city == BRAZIL) || (city == CHICAGO)){ //if((tabno > 8) && (city == BRAZIL)) tabno += 98; //if((tabno > 6) && (city == CHICAGO)) tabno += 101; var elt = makeElement('a', null, {'onclick':'return do_ajax("inner_page","remote/html_server.php?xw_controller=job&xw_action=view&xw_city='+cities[city][CITY_NUMBER]+'&tab='+tabno+'", 1, 1 ,0, 0); return false;'}); if(elt){ clickElement(elt); return true; } } // No job tab. Make sure we're on the correct job bar. // For NY and BK we look for the 'more jobs' or 'more episodes' tab to move between job bars // NY has jobs_bar0 and jobs_bar1 where as BK has only jobs_bar0, account for this later var barno = 0; if(city == NY) barno = (tabno < 6 ? 0 : 1); var currentBar = 0; if(city == NY) currentBar = (currentTab < 6 ? 0 : 1); DEBUG('goJobTab: city='+ city+' currentBar='+ currentBar+' currentTab='+ currentTab+' barno='+ barno+' tabno='+ tabno); if(currentBar != barno){ var jobWord; if(city == NY) jobWord = currentBar == 1 ? "Easy Jobs" : "More Jobs"; elt = xpathFirst('.//ul[contains(@id,"jobs_bar")]'+'//a[contains(text(), "'+jobWord+'")]', innerPageElt); DEBUG('Clicked to go to job bar '+ barno+'. '); clickElement(elt); return true; } // Handle old and new tab param names elt = xpathFirst('.//ul[@id="jobs_bar'+ barno+'"]//a[' + 'contains(@onclick, "&story_tab='+ tabno+'") or ' + 'contains(@onclick, "&episode_tab='+ tabno+'") or ' + 'contains(@onclick, "&tab='+ tabno+'")]', innerPageElt); if(!elt) elt = xpathFirst('.//li[@id="tab_'+ barno+'"]//a[' + 'contains(@onclick, "&story_tab='+ tabno+'") or ' + 'contains(@onclick, "&episode_tab='+ tabno+'") or ' + 'contains(@onclick, "&tab='+ tabno+'")]', innerPageElt); if(!elt) elt = xpathFirst('.//li[@id="tab_'+ tabno+'"]//a[' + 'contains(@onclick, "&story_tab='+ tabno+'") or ' + 'contains(@onclick, "&episode_tab='+ tabno+'") or ' + 'contains(@onclick, "&tab='+ tabno+'")]', innerPageElt); if(!elt){ elt = xpathFirst('.//li[@id="tab_'+ tabno+'"]//span[contains(text(), "Locked")]',innerPageElt); if(!elt){ DEBUG('BUG DETECTED: Can\'t find job bar '+ barno+', tab '+ tabno+' link to click. Currently on job bar '+ currentBar+', tab '+ currentTab+'.'); } return false; } clickElement(elt); DEBUG('Clicked to go to job tab '+ tabno+'.'); return true; } function goJobTabPath(tabnopath){ var elt; var currentTabPath = currentJobTabPath(); colorDEBUG('goJobTabPath - current: '+currentTabPath+' / needed :'+tabnopath); if(currentTabPath == tabnopath) return true; elt = xpathFirst('.//a[contains(@onclick, "ExpertMapController.changePath('+tabnopath+');")]'); if(!elt) return false; clickElement(elt); DEBUG(' job, Clicked to go to tab '+ tabnopath+'in gojobtabpath elt-b='+ elt.innerHTML ); return true; } function goJob(jobno){ try { // Retrieve the jobRow var jobName = missions[GM_getValue('selectMission')][MISSION_NAME]; var jobNo = missions[GM_getValue('selectMission')][MISSION_NUMBER]; var jobTab = missions[GM_getValue('selectMission')][MISSION_TAB]; DEBUG(' using jobNo/jobName : '+jobNo+ ' / '+jobName); var jobRow = getJobRow(jobName, innerPageElt); var elt; var tmp = 1 ; if(jobRow) elt = xpathFirst('.//a[contains(@onclick, "job='+jobNo+'") and not(contains(@onclick, "xw_controller=marketplace"))]', jobRow); if(!elt){ elt = xpathFirst('.//a[contains(@href, "job='+jobNo+'") and not(contains(@onclick, "xw_controller=marketplace"))]', jobRow); } if(!elt){ elt = xpathFirst('.//a[contains(@onclick, "MapController.doFightJob('+jobNo+',\'p|")]', jobRow); tmp = 5 ; } if(!elt){ elt = xpathFirst('.//a[contains(@onclick, "xw_action=dojob")]', jobRow) ; tmp = 2 ;} // first 2 are above line broke down if(!elt){ elt = xpathFirst('.//a[contains(@onclick, "MapController.panelButtonDoJob('+jobNo+');")]') ; tmp = 3 ;} // lv jobs if(!elt){ elt = xpathFirst('.//a[contains(@onclick, "xw_action=fight_job")]', jobRow) ; tmp = 4 ;} // i forget :) may not need if(isJobLocked(elt)) { colorDEBUG('Job: '+jobName+' is not availalbe yet !',cre); return false; } if(city==BRAZIL || city==CHICAGO){ var rowElt = xpathFirst('.//div[@class="job"]//a[contains(@href, "job='+ jobNo+'&")]', innerPageElt); if(rowElt){ var useJob_href; if(rowElt.hasAttribute('href')){ useJob_href = rowElt.getAttribute('href'); } else { useJob_href = 'remote/html_server.php?xw_controller=job&xw_action=dojob&xw_city='+cities[city][CITY_NUMBER]+'&mwcom=1&job='+jobNo+'&tab='+jobTab+'&clkdiv=btn_dojob_'+jobNo; } var jobUsed = rowElt.parentNode.parentNode; var ajaxID = createAjaxPage(true); rowElt.setAttribute('onclick', 'do_ajax("'+ ajaxID+'",\''+useJob_href+'\',1);return false;'); Autoplay.fx = function(){ tmp=7; clickAction = 'braziljob'; clickContext = jobUsed; suspendBank = false; DEBUG('BRAZIL/CHICAGO JOB - Clicked to perform job: '+ jobName+' jobNo '+ jobNo+' : job string used was 7'); clickElement(rowElt); }; Autoplay.delay = getAutoPlayDelay() Autoplay.start(); return true; } DEBUG(' no brazil/chicago job row elt - - - - '); return false; } if(tmp == 5){ // lv fight jobs targetElts = $x('.//a[contains(@onclick, "MapController.doFightJob('+jobNo+',\'p|")]', jobRow); tmp = 5 ; numTargets = targetElts.length; DEBUG('Fight job, Number of Fight Targets Found : '+ numTargets); if(numTargets){ var opponentLevelMax = parseInt(GM_getValue('fightLevelMax', 100)); var opponentMafiaMax = parseInt(GM_getValue('fightMafiaMax', 501)); if(GM_getValue('fightLevelMaxRelative', false)) opponentLevelMax = opponentLevelMax + level; if(GM_getValue('fightMafiaMaxRelative', false)) opponentMafiaMax = opponentMafiaMax + mafia; DEBUG('Fight job, Only performing if Level <= '+opponentLevelMax+' and mafia <= '+opponentMafiaMax); var OppName, OppSize, OppLevel; //ignore job if we have do not have enough energy / stamina to perform the job, otherwise we set jobmastery to 100 to skip this job temporarely var skipCurrentJob = false; StamReqElt = xpathFirst('.//dd[@class="stamina"]', jobRow); if(StamReqElt){ StamReq = parseInt(StamReqElt.innerHTML.untag()); DEBUG(' job Requires Stamina:' +StamReq+':'); if(StamReq > stamina){ skipCurrentJob = true; DEBUG(' job stamina required :'+StamReq+': have :'+stamina+': not enough stamina, leave for now'); return false; } else DEBUG(' job stamina required :'+StamReq+': have :'+stamina+': have enough stamina do job'); } else DEBUG(' job Current Stamina: '+stamina+'. Skipping - StamReq NOT FOUND'); var smallestMafia = opponentMafiaMax; var lowestLevel = opponentLevelMax; var foundOpp = false; for(i=0;i= (cities.length)) toCity = 0 ; return toCity; } function goLocation(toCity){ // Already in this city if(toCity == city){ DEBUG('Already in '+ cities[toCity][CITY_NAME]+'.'); return true; } // Check if level allows traveling to certain cities if(level < cities[toCity][CITY_LEVEL]){ addToLog('warning Icon', 'WARNING: Current level does not allow travel to '+ cities[toCity][CITY_NAME]+'. '); DEBUG('Staying in '+ cities[city][CITY_NAME]); return false; } // Find and click the travel element for the given destination. var elt = xpathFirst('//div[@id="travel_menu"]//a[contains(., "'+ cities[toCity][CITY_NAME]+'")]'); if(elt){ clickElement(elt); DEBUG('Clicked to travel to '+ cities[toCity][CITY_NAME]+'.'); return true; } DEBUG('Unable to find '+ cities[toCity][CITY_NAME]+' travel link. '); return false; } function takeFightStatistics(experience, winCount, lossCount, cashStr){ var loc = city; var xp = parseInt(experience); var cashInt = parseCash(cashStr); var cashLoc = parseCashLoc(cashStr); if(xp){ GM_setValue('totalExpInt', GM_getValue('totalExpInt', 0) + xp); GM_setValue(cityStats[loc][fightExp], GM_getValue(cityStats[loc][fightExp], 0) + xp); } if(winCount > 0){ // WON at least one fight GM_setValue('fightWinCountInt', GM_getValue('fightWinCountInt', 0) + winCount); GM_setValue('totalWinDollarsInt', String(parseInt(GM_getValue('totalWinDollarsInt', 0)) + cashInt)); GM_setValue(cityStats[loc][fightWins], GM_getValue(cityStats[loc][fightWins], 0) + xp); GM_setValue(cityStats[cashLoc][cashWins], GM_getValue(cityStats[cashLoc][cashWins], 0) + cashInt); } if(lossCount > 0){ // LOST at least one fight GM_setValue('fightLossCountInt', GM_getValue('fightLossCountInt', 0) + lossCount); GM_setValue(cityStats[loc][fightLosses], GM_getValue(cityStats[loc][fightLosses], 0) + lossCount); } // LOST all fights, money is 'Loss $' if(winCount == 0){ GM_setValue('totalLossDollarsInt', String(parseInt(GM_getValue('totalLossDollarsInt', 0)) + cashInt)); GM_setValue(cityStats[cashLoc][cashLosses], GM_getValue(cityStats[cashLoc][cashLosses], 0) + cashInt); } } function logFightOutcome(context, respJSON){ try{ var cityMultiplier = (city == BRAZIL || city == CHICAGO) ? 5 : 1; var fight_wrapper = xpathFirst('.//div[@id="fight_wrapper"]' , innerPageElt); var fightResults = xpathFirst('.//div[@id="wrapper_items_won"]' , fight_wrapper); fightResultsInner = fightResults.innerHTML.untag().toLowerCase(); var v2Won = xpathFirst('.//div[@id="attacker_fight_status" and contains(@class,"good") and contains(text(),"Won")]' , fight_wrapper); var v2Lost = xpathFirst('.//div[@id="attacker_fight_status" and contains(@class,"bad") and (contains(text(),"LOST") or contains(text(),"Lost"))]' , fight_wrapper); var cashGainTxt="0"; var xpGainTxt="0"; var targetIced, targetKilled, iceStolen, iceScored; var stealerID=""; var stealerLevel=""; var stealerName=""; var stealerLevelTxt=""; var stealerClanElt = ""; var stealerNameElt = ""; var stealerInMafia=false; var revengeButton = ""; var bragCounter = 0; var bragTarget = 0; var bragCountEltTxt = ""; var result='You fought '; // defender details var user=""; var userID=0; var userLevel=""; var defenderDetails = xpathFirst('.//div[@id="wrapper_defender"]', fight_wrapper); var defenderStatElt = xpathFirst('.//div[contains(@id,"fv2_defender") and contains(@style,"block")]', defenderDetails); if(defenderDetails){ var defenderClanElt = xpathFirst('.//a[contains(@href,"xw_controller=clan")]' , defenderDetails); var defenderNameElt = xpathFirst('.//a[contains(@href,"xw_controller=stats")]' , defenderDetails); var defenderLevelElt = xpathFirst('.//div[contains(text(),"Level")]' , defenderDetails); if(defenderClanElt) user = linkToString(defenderClanElt, 'user')+' '; if(defenderNameElt) user += linkToString(defenderNameElt, 'user'); if(defenderLevelElt) userLevel = defenderLevelElt.innerHTML.untag(); result += user+', a '+userLevel; /* var logName = 'Default Don'; var logLevel = document.getElementById('user_level').innerHTML; var userDetails = document.getElementById('wrapper_attacker'); if(userDetails){ var userInner = userDetails.innerHTML; userInner = userInner.replace(/<[^>]*>/g,''); logName = (/(Won|Lost|won|lost|WON|LOST)*\s*?(.+)\s*?Level/.exec(userInner))[2]; } */ } if(respJSON){ if(typeof respJSON.fight_result !== undefined) fightResult = respJSON.fight_result; var fightOutcome = (fightResult.isWin ? 1 : 0); if(fightResult.is_power_attack){ winCount = parseInt(fightResult.power_attack.won); lossCount = parseInt(fightResult.power_attack.lost); fightsWon = winCount*cityMultiplier; fightsLost = lossCount*cityMultiplier; } if(fightResult.cash){ var cashCity = parseInt(fightResult.cash_city) - 1; cashGainTxt = cities[cashCity][CITY_CASH_SYMBOL]+makeCommaValue(fightResult.cash); } else { var cashCity = parseInt(fightResult.cash_city) - 1; cashGainTxt = cities[cashCity][CITY_CASH_SYMBOL]+makeCommaValue(0); } if(fightResult.experience){ xpGainTxt = fightResult.experience; } if(fightResult.defender.is_iced){ targetIced = true; } if(fightResult.defender.is_killed){ targetKilled = true; } if(fightResult.defender.you_iced || fightResult.you_just_iced || fightResult.you_just_killed){ iceScored = true; bragCounter = parseInt(fightResult.ices_so_far); bragTarget = parseInt(fightResult.ices_target); bragCountEltTxt = bragCounter; if(bragTarget) bragCountEltTxt +=' of '+bragTarget; } if(fightResult.ice_was_just_stolen){ iceStolen = true; stealerID = fightResult.thief_id; stealerInMafia = fightResult.thief_isInMafia; stealerName = fightResult.thief_name; stealerLevelTxt = ', a '+fightResult.thief_class; if(stealerLevelTxt.match(/(\d+)/)) stealerLevel = RegExp.$1; stealerLevel = (isNaN(stealerLevel)) ? 9999 : parseInt(stealerLevel); //colorDEBUG('Ice Stolen by '+stealerName, cli); } //Backup for differences between JSONresponse and screen output if(targetIced || targetKilled){ if(defenderStatElt){ defenderStatEltId = defenderStatElt.id; switch(defenderStatEltId){ case "fv2_defender_overlay_stolen": iceStolen = true; break; case "fv2_defender_overlay_iced": iceScored = true; targetIced = true; break; case "fv2_defender_overlay_killed": iceScored = true; targetKilled = true; break; case "fv2_defender_iced_self": case "fv2_defender_was_iced": targetIced = true; break; } if(iceScored){ var bragCountElt = xpathFirst('.//div[@class="fv2_defender_overlay_next_count"]' , defenderStatElt); if(bragCountElt){ bragCountEltTxt = bragCountElt.innerHTML; if(bragCountEltTxt.match(/(\d+)\//)){ bragCounter = parseInt(RegExp.$1); } } } } } } else { // determin win or loose var fightOutcome=0; fightResultElt = xpathFirst('.//img[contains(@src,"youwin")]', fightResults); if(v2Won || fightResultElt) fightOutcome = 1; //non-power attack results var winCount = fightOutcome > 0 ? 1 : 0; var lossCount = fightOutcome == 0 ? 1 : 0; var wonFights = xpathFirst('.//span[@class="good" and contains(text(),"Win")]' , fightResults); if(wonFights){ wonFightsTxt = wonFights.innerHTML.untag(); if(wonFightsTxt.match(/(\d+)/)) winCount = parseInt(RegExp.$1); } var lostFights = xpathFirst('.//span[@class="bad" and contains(text(),"Loss")]' , fightResults); if(lostFights){ lostFightsTxt = lostFights.innerHTML.untag(); if(lostFightsTxt.match(/(\d+)/)) lossCount = parseInt(RegExp.$1); } fightsWon = winCount*cityMultiplier; fightsLost = lossCount*cityMultiplier; var cashGainElt = xpathFirst('.//td[contains(@class,"cash_icon")]' , fightResults); if(cashGainElt){ cashGainTxt = cashGainElt.innerHTML.untag(); cashGainTxt = (cashGainTxt.match(REGEX_CASH)? RegExp.lastMatch : cashGainTxt); } var xpGainElt = xpathFirst('.//td[@class="experience"]', fightResults); if(xpGainElt) xpGainTxt = xpGainElt.innerHTML.untag(); if(defenderStatElt){ defenderStatEltId = defenderStatElt.id; switch(defenderStatEltId){ case "fv2_defender_overlay_stolen": iceStolen = true; break; case "fv2_defender_overlay_iced": iceScored = true; targetIced = true; break; case "fv2_defender_overlay_killed": iceScored = true; targetKilled = true; break; case "fv2_defender_iced_self": case "fv2_defender_was_iced": targetIced = true; break; } if(iceScored){ var bragCountElt = xpathFirst('.//div[@class="fv2_defender_overlay_next_count"]' , defenderStatElt); if(bragCountElt){ bragCountEltTxt = bragCountElt.innerHTML; if(bragCountEltTxt.match(/(\d+)\//)) bragCounter = parseInt(RegExp.$1); } } } } if(winCount){ result += '. You WON '; (winCount==1) ? result+= ' the fight' : result+= winCount+' fights'; } if(lossCount){ result += '. You LOST '; (lossCount==1) ? result+= 'the fight' : result+= lossCount+' fights'; } if(fightOutcome){ result += ' and gained '+ xpGainTxt+' experience and '+''+ cashGainTxt+'.'; addToLog('yeah Icon', result); } else { if(cashGainTxt!="0"){ result += ', losing '+ cashGainTxt+'. You still gained '+ xpGainTxt+' experience.'; } else { if(xpGainTxt!=0){ result += '. You still gained '+ xpGainTxt+' experience.'; } else { result += '.'; } } if(isGMChecked('fightRemoveStronger')) result += '
Too strong: Avoiding!'; addToLog('omg Icon', result); } result = ''; if(!isGMChecked('noStats')){ var experience = 0; if(!isNaN(xpGainTxt)) experience = parseInt(xpGainTxt); takeFightStatistics(experience, fightsWon, fightsLost, cashGainTxt); updateLogStats(); } if(iceScored){ var iceScoredIcon = ""; if(targetIced){ //logEvent(xw_user, context.id.replace('p|',''), 1, logName, logLevel); result=' You ICED '+user; iceScoredIcon = 'iced Icon'; } else if(targetKilled){ //logEvent(xw_user, context.id.replace('p|',''), 2, logName, logLevel); result=' You KILLED '+user; iceScoredIcon = 'killedMobster Icon'; } if(bragCountEltTxt){ result+=', bringing your current iceCount to '+ bragCountEltTxt+'.'; if(bragCounter && defenderStatElt){ var publishFrequency = parseInt(GM_getValue('autoIcePublishFrequency')) ? parseInt(GM_getValue('autoIcePublishFrequency')) : 1; var logFrequency = parseInt(bragCounter % publishFrequency); if(logFrequency==0 && isGMChecked('autoIcePublish')){ var bragElt = xpathFirst('.//div[@class="fv2_defender_overlay_brag_action" and not(contains(@style,"opacity: 0.5;"))]', defenderStatElt); if(bragElt &&isGMChecked('autoGlobalPublishing')){ var bragLink = xpathFirst('.//a[@class="sexy_button_new medium white sexy_announce_gray"]', bragElt); if(bragLink){ clickElement(bragLink); result+=' (Icing published: '+ publishFrequency+ ' / ' +publishFrequency+')'; } } } else { result+=' (Icing not published: '+ logFrequency+ ' / ' +publishFrequency+')'; } } } else { result +='.'; } addToLog(iceScoredIcon, result); } else if(iceStolen){ if(isGMChecked('fightIceStealers') && !inClanBattle){ if(!defenderStatElt){ defenderDetails = xpathFirst('.//div[@id="wrapper_defender"]', innerPageElt); defenderStatElt = xpathFirst('.//div[@id="fv2_defender_overlay_stolen" and contains(@style,"block")]', defenderDetails); } if(defenderStatElt && defenderStatElt.id=="fv2_defender_overlay_stolen"){ stealerClanElt = xpathFirst('.//a[contains(@href,"xw_controller=clan")]' , defenderStatElt); stealerNameElt = xpathFirst('.//a[contains(@href,"xw_controller=stats")]', defenderStatElt); if(stealerClanElt){ stealerName = linkToString(stealerClanElt, 'user')+' '; } if(stealerNameElt){ stealerName += linkToString(stealerNameElt, 'user'); } var stealerLevelElt = xpathFirst('.//div[@class="fv2_defender_overlay_level"]' , defenderStatElt); if(!stealerLevelElt) stealerLevelElt = xpathFirst('.//div[contains(text(),"Level")]', defenderStatElt); if(stealerLevelElt){ stealerLevelTxt = ', a '+stealerLevelElt.innerHTML.untag(); if(stealerLevelTxt.match(/(\d+)/)) stealerLevel = RegExp.$1; stealerLevel = (isNaN(stealerLevel)) ? 9999 : parseInt(stealerLevel); } addToLog('iceStolen Icon','Your ICE was stolen by '+stealerName+''+stealerLevelTxt+'.'); if(stealerInMafia){ addToLog('omg Icon', 'Skipping the Revenge on '+stealerName+stealerLevelTxt+' for stealing your Ice ... part of your mafia'); } else { revengeButton = xpathFirst('.//div[@id="fv2_defender_overlay_stolen_btn"]//a' , defenderStatElt); if(!revengeButton) revengeButton = xpathFirst('.//div[@id="fv2_defender_overlay_stolen"]//a[contains(.,"Attack)]' , defenderDetails); if(revengeButton){ var opponentLevelMax = parseInt(GM_getValue('fightLevelMax', 100)); // Make any relative adjustments (if enabled). if(GM_getValue('fightLevelMaxRelative', false)){ opponentLevelMax = opponentLevelMax + level; } if(stealerLevel <= opponentLevelMax){ opponent = new Player(); // Get the opponent's details. opponent.profile = stealerNameElt; opponent.familyElt = stealerClanElt; opponent.nameElt = stealerNameElt; if(stealerID){ opponent.id = stealerID.replace('p|',''); } else { var onClickText; if(opponent.profile.hasAttribute('href')) onClickText = opponent.profile.getAttribute('href'); if(onClickText.match(/(user|opponent_id)\=(.+)/)){ opponent.id = decodeID(RegExp.$2); } } opponent.attack = revengeButton; opponent.level = stealerLevel; opponent.name = stealerName; opponent.linkedName = stealerName; //opponent.faction = ''; opponent.mafia = '501'; var fightNames = isGMChecked('fightNames'); var avoidNames = isGMChecked('fightAvoidNames'); if(fightNames && avoidNames && isFamily(decodeHTMLEntities(opponent.name),STAMINA_HOW_FIGHT_RANDOM)){ addToLog('process Icon', 'Skipping the Revenge on '+stealerName+stealerLevelTxt+' for stealing your Ice ... isFamily'); } else { opponent.fightsDone=0; autoFight.revengeTarget = opponent; Autoplay.fx = function(){ if(city==BRAZIL || city == CHICAGO) clickAction = 'multifight'; else clickAction = 'fight'; clickContext = opponent; colorDEBUG('autoFight - Revenge: Clicked to '+revengeButton.innerHTML+' '+ stealerName+'.', cye); clickElement(revengeButton); addToLog('process Icon', 'Clicked to take Revenge on '+stealerName+stealerLevelTxt+' for stealing your Ice ...'); }; Autoplay.delay = noDelay; Autoplay.start(); return true; } } else { addToLog('process Icon', 'Skipping the Revenge on '+stealerName+stealerLevelTxt+' for stealing your Ice ... deemed to strong (max. level: '+opponentLevelMax+')'); } } else { colorDEBUG('Revenge Button not Found !', cre); } } } else { colorDEBUG('Revenge Overlay Ice Stolen not Found !', cre); } } else { colorDEBUG('fightIceStealers unchecked or in famliy battle - no revenge'); } } else if(context.iced){ addToLog('iceStolen Icon', user+' was already ICED. Getting next target ...'); } else { addToLog('info Icon', 'Getting next target ...'); } } catch(fightErr){ colorDEBUG('fightErr:'+fightErr); } } function logLootDrops(statGainTxt){ var lootDrops = $x('.//div[@class="fightV2_items_won"]/div[contains(@id,"fv2_gained_loot")]', innerPageElt); if(lootDrops && lootDrops.length>0){ var lootDropTxt=''; var lootDropItems=''; for(i=0,iLength = lootDrops.length;i'; else lootDropItems = 'Loot Found:
'+lootDiv.innerHTML+'
'; } } } } if(lootDropTxt) addToLog('lootbag Icon', lootDropTxt); if(lootDropItems) addToLog('lootbag Icon', lootDropItems); } if(statGainTxt) addToLog('process Icon', statGainTxt); } function logFightResponse(rootElt, resultElt, context, multifight, respJSON){ try{ var fightResult=false; var v2Won; var v2Lost; //General Settings if(!resultElt) resultElt = rootElt; var inner = resultElt.innerHTML; var innerNoTags = inner.untag(); //Fight Settings var isNormalFightResponse = false; var reAttackOpponent = false; var fightMaxAttacks = GM_getValue('fightMaxAttacks',0); var fightHealthMax = GM_getValue('fightHealthMax',0); var fightHealthPctMax = GM_getValue('fightHealthPctMax',0); var fightMaxAttacks = GM_getValue('fightMaxAttacks',0); var minHealth = isGMChecked('attackCritical') ? 21 : 29; // 20 works on fight page, need 21 to hit from profile page. var cashGainTxt; var cityMultiplier = (city == BRAZIL || city == CHICAGO) ? 5 : 1; //Opponent Settings var lastOpponent = context; if(isNaN(lastOpponent.fightsDone)){ lastOpponent.fightsDone = cityMultiplier; } else { lastOpponent.fightsDone += cityMultiplier; } if(isNaN(lastOpponent.totalCash)){ lastOpponent.totalCash = 0; } if(isNaN(lastOpponent.targetHealth)){ lastOpponent.targetHealth = 0; } if(isNaN(lastOpponent.targetEstimatedHealth)){ lastOpponent.targetEstimatedHealth = 0; } if(isNaN(lastOpponent.targetHealthCnt)){ lastOpponent.targetHealthCnt = 0; } if(isNaN(lastOpponent.targetHealthPct)){ lastOpponent.targetHealthPct = 0; } if(isNaN(lastOpponent.targetPrevHealthPct)){ lastOpponent.targetPrevHealthPct = 0; } if(isNaN(lastOpponent.targetStartHealthPct)){ lastOpponent.targetStartHealthPct = 0; } if(isNaN(lastOpponent.totaldamage)){ lastOpponent.totaldamage = 0; } if(respJSON){ try{ reAttackOpponent = true; isNormalFightResponse = true; if(respJSON.user_fields && respJSON.fight_result){ var userFields = respJSON.user_fields; fightResult = respJSON.fight_result; if(typeof respJSON.user_fields.user_health !== undefined) health = parseInt(respJSON.user_fields.user_health); if(typeof respJSON.user_fields.user_stamina !== undefined) stamina = parseInt(respJSON.user_fields.user_stamina); if(fightResult !== false && respJSON.fight_result.defender !== undefined){ if(respJSON.fight_result.defender.is_iced || respJSON.fight_result.defender.is_killed){ lastOpponent.iced = true; reAttackOpponent = false; if(respJSON.fight_result.defender.you_iced || respJSON.fight_result.you_just_iced){ colorDEBUG('SKIPPING the attack on '+ lastOpponent.name+' - You ICED : fight_result.defender.you_iced || respJSON.fight_result.you_just_iced', caq); } else if(respJSON.fight_result.you_just_killed){ colorDEBUG('SKIPPING the attack on '+ lastOpponent.name+' - You KILLED : fight_result.you_just_killed', caq); } else if(respJSON.fight_result.ice_was_just_stolen){ colorDEBUG('SKIPPING the attack on '+ lastOpponent.name+' - ICE STOLEN : fight_result.ice_was_just_stolen', cre); } else { colorDEBUG('SKIPPING the attack on '+ lastOpponent.name+' : IS ICED : fight_result.defender.is_iced || fight_result.defender.is_killed', cre); } } if(!fightResult.isWin && isGMChecked('fightRemoveStronger')){ reAttackOpponent = false; lastOpponent.toStrong=true; colorDEBUG('SKIPPING the attack on '+ lastOpponent.name+' : LOST', cre); } lastOpponent.damage = parseInt(respJSON.fight_result.defender.damage_dealt); lastOpponent.totaldamage += lastOpponent.damage; lastOpponent.targetHealthPct = parseInt(respJSON.fight_result.defender.current_health_pct); if(!lastOpponent.targetStartHealthPct) lastOpponent.targetStartHealthPct = lastOpponent.targetHealthPct; if(fightHealthPctMax && lastOpponent.targetHealthPct > fightHealthPctMax){ reAttackOpponent = false; colorDEBUG('SKIPPING the attack on '+ lastOpponent.name+' : lastOpponent.targetHealthPct > fightHealthPctMax - '+lastOpponent.targetHealthPct+' vs '+fightHealthPctMax, cre); } if(lastOpponent.targetHealthPct < lastOpponent.targetStartHealthPct){ var healthChange = parseInt(lastOpponent.targetStartHealthPct - lastOpponent.targetHealthPct); if(healthChange) lastOpponent.targetEstimatedHealth = parseInt((100/healthChange)*lastOpponent.totaldamage); if(fightHealthMax && lastOpponent.targetEstimatedHealth > fightHealthMax){ if(lastOpponent.targetHealthCnt>2){ reAttackOpponent = false; colorDEBUG('SKIPPING the attack on '+ lastOpponent.name+' : lastOpponent.targetEstimatedHealth > fightHealthMax - '+lastOpponent.targetEstimatedHealth+' vs '+fightHealthMax, cre); } lastOpponent.targetHealthCnt++; } } lastOpponent.targetPrevHealthPct = lastOpponent.targetHealthPct; if(fightResult.is_power_attack){ fightsWon = parseInt(fightResult.power_attack.won); fightsLost = parseInt(fightResult.power_attack.lost); lastOpponent.fightsDone = (fightsWon+fightsLost)*cityMultiplier; } if(fightResult.cash){ var cashCity = parseInt(fightResult.cash_city) - 1; if(lastOpponent.totalCash) lastOpponent.cashGained = parseInt(fightResult.cash)-lastOpponent.totalCash; else lastOpponent.cashGained = parseInt(fightResult.cash); lastOpponent.totalCash = parseInt(fightResult.cash); cashGainTxt = cities[cashCity][CITY_CASH_SYMBOL]+makeCommaValue(lastOpponent.cashGained); } else { var cashCity = parseInt(fightResult.cash_city) - 1; cashGainTxt = cities[cashCity][CITY_CASH_SYMBOL]+makeCommaValue(0); } var totalGainTxt = cities[cashCity][CITY_CASH_SYMBOL]+makeCommaValue(lastOpponent.totalCash); if(fightResult.experience) xpGainTxt = fightResult.experience; if(isGMChecked('staminaLogDetails')){ addToLog('process Icon','Target - '+lastOpponent.linkedName+'
Fights - Won : '+fightsWon+', Lost: '+fightsLost+', Cash: '+totalGainTxt+', Exp: '+xpGainTxt); } var statGainTxt = ""; if(typeof respJSON.fightbar !== undefined){ var fightBar = respJSON.fightbar; curAttack = parseInt(fightBar.skill_atk.replace(',','')); curDefense = parseInt(fightBar.skill_def.replace(',','')); curAttackEquip = parseInt(fightBar.group_atk.replace(',','')); curDefenseEquip = parseInt(fightBar.group_def.replace(',','')); var attackEquipGain = curAttackEquip - prevAttackEquip; var defenseEquipGain = curDefenseEquip - prevDefenseEquip; if(attackEquipGain) statGainTxt += 'Equipment Attack Strength: ' +curAttackEquip+' (was: '+prevAttackEquip+')
'; if(defenseEquipGain) statGainTxt += 'Equipment Defense Strength: ' +curDefenseEquip+' (was: '+prevDefenseEquip+')
'; prevAttackEquip = curAttackEquip; prevDefenseEquip = curDefenseEquip } if(fightResult.loot[0] || fightResult.socialMessageCards[0]) logLootDrops(statGainTxt) } else { colorDEBUG('logFightResponse fightResult === false || respJSON.fight_result.defender === undefined', cre); } } else { colorDEBUG('logFightResponse invalid JSON response for fighting', cre); colorDEBUG(respJSON); } } catch(jsonErr){ colorDEBUG('jsonErr: '+jsonErr); } } else if(resultElt.id == "fv2_widget_wrapper"){ var curHealth = xpathFirst('.//span[@id="user_health"]'); health = parseInt(curHealth.innerHTML); isNormalFightResponse = true; reAttackOpponent = true; var fight_wrapper = xpathFirst('.//div[@id="fight_wrapper"]' , innerPageElt); if(!fight_wrapper) fight_wrapper = resultElt; var fv2_defender_was_iced = xpathFirst('.//div[@id="fv2_defender_was_iced" and contains(@style,"block")]', fight_wrapper); var fv2_defender_you_iced = xpathFirst('.//div[@id="fv2_defender_you_iced" and contains(@style,"block")]', fight_wrapper); v2Won = xpathFirst('.//div[@id="attacker_fight_status" and contains(@class,"good") and contains(text(),"Won")]', fight_wrapper); v2Lost = xpathFirst('.//div[@id="attacker_fight_status" and contains(@class,"bad") and (contains(text(),"LOST") or contains(text(),"Lost"))]', fight_wrapper); if(v2Won || v2Lost){ logLootDrops(); var defenderHealthBar = xpathFirst('.//div[@id="defender_hp"]', fight_wrapper); if(defenderHealthBar){ var defenderHealthBarValue=0; var defenderHealthBarStyle = defenderHealthBar.getAttribute('style'); if(defenderHealthBarStyle.match(/width:(.+)px/)) defenderHealthBarValue = RegExp.$1; if(!isNaN(defenderHealthBarValue)){ lastOpponent.HealthBar=parseFloat(defenderHealthBarValue); } } if((!v2Won || v2Lost) && isGMChecked('fightRemoveStronger')){ reAttackOpponent = false; lastOpponent.toStrong = true; colorDEBUG('SKIPPING the attack on '+ lastOpponent.name+' : LOST', cre); } if(fv2_defender_was_iced || fv2_defender_you_iced){ reAttackOpponent = false; lastOpponent.iced = true; if(fv2_defender_you_iced) colorDEBUG('SKIPPING the attack on '+ lastOpponent.name+' : fv2_defender_you_iced', caq); else colorDEBUG('SKIPPING the attack on '+ lastOpponent.name+' : fv2_defender_was_iced', cre); } var cashGainElt = xpathFirst('.//td[contains(@class,"cash_icon")]' , resultElt); if(cashGainElt){ cashGainTxt = cashGainElt.innerHTML.untag(); cashGainTxt = cashGainTxt.match(REGEX_CASH)? RegExp.lastMatch : cashGainTxt; lastOpponent.totalCash += parseCash(cashGainTxt); } if(isGMChecked('staminaLogDetails')){ if(v2Won) fightTxt = 'Fight WON'; else fightTxt = 'Fight LOST'; addToLog('process Icon','Target - '+lastOpponent.linkedName+': '+ fightTxt); } } else { colorDEBUG('logFightResponse no v2Won / v2Lost element', cre); reAttackOpponent = false; isNormalFightResponse = true; } } else { if(resultElt.hasAttribute('class')){ if(resultElt.getAttribute('class') == "fight_results"){ reAttackOpponent = false; isNormalFightResponse = false; } } } if(reAttackOpponent && (!canSpendStamina() || ptsToNextLevel <= 6 || health < minHealth)){ reAttackOpponent = false; colorDEBUG('SKIPPING the attack on '+ lastOpponent.name+' : !canSpendStamina() || ptsToNextLevel <= 6 || health < minHealth', cre); } if(reAttackOpponent && fightMaxAttacks && lastOpponent.fightsDone > fightMaxAttacks){ reAttackOpponent = false; colorDEBUG('SKIPPING the attack on '+ lastOpponent.name+' : '+lastOpponent.fightsDone+' > '+GM_getValue('fightMaxAttacks',0), cre); } if(reAttackOpponent){ var how = getStaminaMode(); if(how == STAMINA_HOW_FIGHT_LIST){ reAttackOpponent = isGMChecked ('staminaReattackList') && ( (GM_getValue('reattackThresholdList') == 0) || (parseCash(cashGainTxt) >= GM_getValue('reattackThresholdList') && cashGainTxt.indexOf(cities[city][CITY_CASH_SYMBOL]) != -1) ); } else { reAttackOpponent = isGMChecked ('staminaReattack') && ( (GM_getValue('reattackThreshold') == 0) || (parseCash(cashGainTxt) >= GM_getValue('reattackThreshold') && cashGainTxt.indexOf(cities[city][CITY_CASH_SYMBOL]) != -1) ); } if(!reAttackOpponent) colorDEBUG('SKIPPING the attack on '+ lastOpponent.name+' INVALID cashGainTxt: '+cashGainTxt, cre); } //fall back method if(lastOpponent.iced || (lastOpponent.toStrong && isGMChecked('fightRemoveStronger'))) reAttackOpponent == false; if(reAttackOpponent!==false){ var fv2_btncontainer; var fv2_btn_div; var fightv2_atkbtn; fv2_btncontainer = xpathFirst('.//div[@class="fv2_btncontainer"]', resultElt); if(fv2_btncontainer){ var paStamina = cityMultiplier * 5; if (isGMChecked('staminaPowerattack') && stamina >=paStamina && ((isGMChecked('stopPA') && health >= GM_getValue('stopPAHealth')) || !isGMChecked('stopPA'))) { fv2_btn_div = xpathFirst('.//div[@id="fv2_button_row2"]/div[contains(@style,"block")]', fv2_btncontainer); } else { fv2_btn_div = xpathFirst('.//div[@id="fv2_button_row1"]/div[contains(@style,"block")]', fv2_btncontainer); } if(fv2_btn_div){ fightv2_atkbtn = xpathFirst('.//a[contains(@class,"fightV2AttackBtn")]', fv2_btn_div); if (!fightv2_atkbtn){ fightv2_atkbtn = xpathFirst('.//a[contains(@class,"fightV2PowerAtkBtn")]', fv2_btn_div); } if(!fightv2_atkbtn){ colorDEBUG('SKIPPING the attack on '+ context.name+' : fightv2_atkbtn NOT FOUND.', cre); } else { var v2attackhref = fightv2_atkbtn.getAttribute('href'); if(GM_getValue('checkMWAPSum', Math.floor(Math.random()*78)+78) != mwapValidation()){ // colorDEBUG('MWAP Lite: RX6 not enabled', cre); } else { v2attackhref = v2attackhref.replace(/click_amt=\d+/, "click_amt=6"); } var ajaxID = createAjaxPage(true); fightv2_atkbtn.setAttribute('onclick', 'do_ajax("'+ ajaxID+'",\''+v2attackhref+'\',1);return false;'); autoReload(false, 'fight box attacking'); lastOpponent.attackAgain = fightv2_atkbtn; Autoplay.fx = function() { if(city==BRAZIL || city == CHICAGO || fightv2_atkbtn.innerHTML.match(/\d/i)) clickAction = 'multifight'; else clickAction = 'fight'; clickContext = context; clickElement(fightv2_atkbtn); colorDEBUG('autoFight - Clicked to REPEAT the '+fightv2_atkbtn.innerHTML+' attack on '+ context.name+'.', cye); }; Autoplay.delay = noDelay; Autoplay.start(); return true; } } else { colorDEBUG('SKIPPING the attack on '+ context.name+' : fv2_btn_div / row INVALID / NOT FOUND.', cre); } } else { colorDEBUG('SKIPPING the attack on '+ context.name+' : fv2_btncontainer NOT FOUND.', cre); } } if(isNormalFightResponse){ if(lastOpponent.toStrong){ setFightOpponentAvoid(lastOpponent); /* fv2_btncontainer = xpathFirst('.//div[@class="fv2_btncontainer"]', resultElt); if(fv2_btncontainer){ fv2_btncontainer_inner = fv2_btncontainer.innerHTML.untag(); if(fv2_btncontainer_inner.indexOf('Attack Again') != -1 && lastOpponent.id.indexOf('p|') != -1){ var liveTarget = lastOpponent.id.replace('p|','') getHelp(liveTarget, lastOpponent.name, lastOpponent.level); DEBUG('Fight Response : liveTarget detected and LiveLinks feed entry sent'); } } */ } try { if(fightResult || v2Won || v2Lost) logFightOutcome(lastOpponent, respJSON); if(isGMChecked('autoHeal') && health < GM_getValue('healthLevel', 0) && (stamina >= GM_getValue('stamina_min_heal')) && canForceHeal() ){ colorDEBUG('Health: '+ health+' vs '+ GM_getValue('healthLevel', 0), cpu); if(canautoheal()) quickHeal(2); } if(!autoFight.revengeTarget){ var closeWrapperBtn = xpathFirst('.//a[@class="close" and contains(@onclick,"CloseJS")]', fight_wrapper); if(closeWrapperBtn){ clickElement(closeWrapperBtn); var close_wrapper = xpathFirst('.//div[@id="fv2_widget_wrapper" and contains(@style,"none")]' , innerPageElt); if(close_wrapper) destroyByID('fv2_widget_wrapper'); } } //Ask for boosts if(isGMChecked('autoGlobalPublishing') && !timeLeftGM('askFightBoostsTimer')){ var boostsAllowedElt = xpathFirst('.//div[@class="fv2_boost_ask_allowed" and not(contains(@style,"none"))]',fight_wrapper); if(boostsAllowedElt){ var boostsElt = xpathFirst('.//div[@class="fv2_boost_ask_action"]//a' , fight_wrapper); if(boostsElt){ clickElement(boostsElt); setGMTime('askFightBoostsTimer', '01:00:05'); } } } if(GM_getValue('staminaSpendHow') == getStaminaMode()) cycleSavedList('pfightlist'); randomizeStamina(); Autoplay.delay = getAutoPlayDelay(); return false; } catch (ex){ //colorDEBUG('A BUG DETECTED in log data for new fight box : '+ ex,cre ); } } else if(innerNoTags.match(/you won/i)){ var fightresstats = xpathFirst('.//div[@class="fightres_stats"]', resultElt); if(fightresstats) { var cashResult = xpathFirst('.//div[@class="sexy__cash good"]', fightresstats); var xpResult = xpathFirst('.//div[@class="fightres_experience good"]', fightresstats); var killResult = xpathFirst('.//div[@class="fightres_damage"]', fightresstats); addToLog('yeah Icon', 'You'+killResult.innerHTML+', gaining '+cashResult.innerHTML+' and '+xpResult.innerHTML+''); } } else if(innerNoTags.match(/you cannot fight|part of your mafia/i)){ if(context.id){ DEBUG('Opponent ('+ context.id+') is part of your mafia. Avoiding.'); setFightOpponentAvoid(context); } } else if(innerNoTags.match(/You just set/)){ cycleSavedList('pautoHitOpponentList'); addToLog('yeah Icon', inner); if(isGMChecked('bgAutoHitCheck')) setGMTime("bgAutoHitTime", "01:00"); var fbPopupElt = xpathFirst('//a[@id="fb_dialog_cancel_button"]'); if(fbPopupElt){ Autoplay.fx = function(){ clickElement(fbPopupElt); DEBUG('Clicked Dismissed Popup!'); }; Autoplay.start(); return true; } } else if(innerNoTags.match(/There is already a bounty/) || innerNoTags.match(/You can\'t add/)){ cycleSavedList('pautoHitOpponentList'); if(isGMChecked('bgAutoHitCheck')) setGMTime("bgAutoHitTime", "01:00"); } else if(innerNoTags.indexOf('too weak') != -1){ addToLog('info Icon', ''+'Too weak to fight.'+ ''); } else { DEBUG('Unrecognized fight response:'+ innerNoTags); } randomizeStamina(); if(GM_getValue('staminaSpendHow') == getStaminaMode()) cycleSavedList('pfightlist'); } catch(respError){ colorDEBUG('respError: '+respError); } return false; } // Spend Stamina successful, change fight location and spend mode function randomizeStamina(){ if(isGMEqual('staminaSpendHow', STAMINA_HOW_RANDOM)){ var randomModes = GM_getValue('randomSpendModes'); var spendMode = Math.floor(Math.random() * STAMINA_HOW_ROBBING); while(randomModes[spendMode]!='1'){ spendMode = Math.floor(Math.random() * STAMINA_HOW_ROBBING); } DEBUG('Stamina Spend Mode Randomize set to : '+ spendMode+' was ' +newStaminaMode); newStaminaMode = spendMode; var randomCities = GM_getValue('randomFightLocations'); // Randomize fight location while (spendMode == STAMINA_HOW_FIGHT_RANDOM || spendMode == STAMINA_HOW_FIGHT_LIST){ var stamLoc = Math.floor(Math.random()*(cities.length-1)); DEBUG('Fight City Randomize set to : '+ stamLoc+' was ' +GM_getValue('fightLocation')); if(randomCities[stamLoc]=='1'){ GM_setValue('fightLocation', stamLoc); DEBUG('Fight location set to : '+ cities[stamLoc][CITY_NAME]); break; } else { DEBUG('Fight location did not qualify'); } } // Randomize robbing location randomCities = GM_getValue('randomRobLocations'); while (spendMode == STAMINA_HOW_ROBBING){ var stamLoc = Math.floor(Math.random()*(cities.length-1)); DEBUG('Rob City Randomize set to : '+ stamLoc+' was ' +GM_getValue('robLocation')); if(randomCities[stamLoc]=='1'){ GM_setValue('robLocation', stamLoc); DEBUG('Robbing location set to : '+ cities[stamLoc][CITY_NAME]); break; } else { DEBUG('Rob location did not qualify'); } } // Randomize hitman location randomCities = GM_getValue('randomHitmanLocations'); while (spendMode == STAMINA_HOW_HITMAN){ var stamLoc = Math.floor(Math.random()*(cities.length-1)); DEBUG('Hitman City Randomize set to : '+ stamLoc+' was ' +GM_getValue('hitmanLocation')); if(randomCities[stamLoc]=='1'){ GM_setValue('hitmanLocation', stamLoc); DEBUG('Hitman location set to : '+ cities[stamLoc][CITY_NAME]); break; } else { DEBUG('Hitman location did not qualify'); } } } } /* Handle our private do_ajax response pages. // case 1: autoplay==false for async clicks; please pass the variable(s) action (and optionally context) // case 2: autoplay==true for sync clicks for use with Autoplay.start(); action and context are set with Autoplay.fx // ajaxAction/ajaxContext are only used internally for async clicks, for sync clicks please use the default clickAction/clickContext vars. */ function createAjaxPage(autoplay, action, context){ if(autoplay) ajaxHandling = true; //function do_ajax(div, url, liteLoad, alignTop, precall, callback, callback_params, noIncrement) var ajaxID = autoplay ? SCRIPT.ajaxIDSync : SCRIPT.ajaxIDAsync; var elt = document.getElementById(ajaxID); if(elt){ elt.removeEventListener('DOMSubtreeModified', handleAjaxModified, false); elt.parentNode.removeChild(elt); } elt = makeElement('div', null, {'id':ajaxID, 'style':'display: none;'}); if(!autoplay){ ajaxAction = action; ajaxContext = context; } elt.addEventListener('DOMSubtreeModified', handleAjaxModified, false); document.getElementById('verytop').appendChild(elt); return ajaxID; } function handleAjaxModified(e){ var ajaxElt = e.target; // Remove event listener ajaxElt.removeEventListener('DOMSubtreeModified', handleAjaxModified, false); // Set result parsing timer window.setTimeout(function(){ajaxPageChanged(ajaxElt);}, 350); } function ajaxPageChanged(ajaxElt){ if(!ajaxElt) return; // Determine which of our private AJAX pages has changed and get the result. var ajaxSync = ajaxElt.id == SCRIPT.ajaxIDSync ? true : false; var ajaxResponse = ajaxElt.innerHTML; // Remove ajax response element ajaxElt.parentNode.removeChild(ajaxElt); // Handle changes to the ajax pages. // If a click or ajax action was taken, check the response. var action, context; if(ajaxSync){ action = clickAction; context = clickContext; clickAction = undefined; clickContext = undefined; } else { action = ajaxAction; context = ajaxContext; ajaxAction = undefined; ajaxContext = undefined; } ajaxHandling = false; if(!logJSONResponse(ajaxSync, ajaxResponse, action, context)){ // No further action was taken. Kick off auto-play. try { doAutoPlay(); } catch (ex){ DEBUG('BUG DETECTED (ajaxPageChanged->doAutoPlay): '+ ex+'. Reloading.'); autoReload(true, 'error !logJSONResponse'); } } } // Interpret the response from an ajax request, return false in case Autoplay isn't used: function logJSONResponse(autoplay, response, action, context){ if(action=="goHome") return false; try { colorDEBUG('logJSONResponse ('+action+') default fx: goHome, delay: '+Autoplay.delay, cfu); //if(action=='fight' || action =='multifight') autoReload(false, 'logJSONResponse'); // stops the forced reload page var responseText = response.untag(); var cashLeft, acctBalance; var respJSON, respData; if(IsJsonString(responseText)) { respJSON = JSON.parse(responseText); if(respJSON.data) if(IsJsonString(respJSON.data)) respData = JSON.parse(respJSON.data); } // Analyze money related responses (collect take, check vault, deposit and withdraw) if(action == 'collect take' || action == 'check vault' || action == 'quick deposit' || action == 'quick withdraw'){ if(!isNaN(context)){ context = parseInt(context); cashElt = document.getElementById('user_cash_'+ cities[context][CITY_ALIAS]); } if(typeof respJSON.user_fields.user_group_size != undefined){ var oSize = respJSON.user_fields.user_group_size; mafia = GM_getValue('userMafiaSize', 0); if(!mafia || mafia < oSize ){ mafia = oSize; GM_setValue('userMafiaSize', mafia); DEBUG('User Mafia Size set to :'+mafia); } } // Parse cash left for depositing anywhere but LV if(action == 'quick deposit' && context != LV) cashLeft = isNaN(respJSON.user_cash) ? null : parseInt(respJSON.user_cash); // Parsing stuff for the remaining cases else { //colorDEBUG('Check Vault :'+respData+'
'+JSON.stringify(respData)); cashLeft = isNaN(respData.cash) ? null : parseInt(respData.cash); if(action != 'collect take'){ acctBalance = parseInt(respData.acct_balance); // Parse vault level and set free vault space //if(GM_getValue('vaultHandling', 0) || action == 'check vault'){ if(GM_getValue('vaultHandling', 0) || action == 'check vault'){ try{ colorDEBUG('parsing json response for \'check vault\''); var respProp = respData.properties; if( (typeof respData.success_message) === undefined){ //colorDEBUG('respProp:'+JSON.stringify(respProp)); //if(respJSON.data.match(/"name":"Vault","level":"?([0-9]+)"?,/i)){ //var vaultLevel = parseInt(RegExp.$1); var vaultLevel = parseInt(respProp[5].level); var vaultCapacity = vaultLevels[vaultLevel][1]; var vaultSpace = vaultCapacity - acctBalance; if(action == 'check vault' && (vaultLevel != GM_getValue('vaultHandling', 0) || vaultSpace != GM_getValue('vaultSpace', 0))) addToLog(cities[LV][CITY_CASH_CSS], 'Parsed new vault status: Level '+ vaultLevel+', free vault space: V$'+ makeCommaValue(vaultSpace)); else if(action == 'check vault') addToLog(cities[LV][CITY_CASH_CSS], 'No change in your vault: Level '+ vaultLevel+', free vault space: V$'+ makeCommaValue(vaultSpace)); GM_setValue('vaultHandling', vaultLevel); GM_setValue('vaultSpace', String(vaultSpace)); //} } else { addToLog(cities[LV][CITY_CASH_CSS], 'Check vault status : '+respData.success_message); } } catch(vaultErr){ colorDEBUG('vaultErr: '+vaultErr); } } } } // Attempt to correct the displayed cash value if(cashLeft != null){ if(cashElt) cashElt.innerHTML = cities[context][CITY_CASH_SYMBOL] + makeCommaValue(cashLeft); cities[context][CITY_CASH] = cashLeft; } } switch (action){ // Parse Skill Point Allocation responses case 'autoStatAllocation': DEBUG('autoStatAllocation results '+ responseText); return false; break; case 'load battlepage': return false; break; case 'collect slotbonus': slotBonus = 0; // Reset this addToLog('info Icon', 'Slot Bonus Collect Result: ' + respData.json_data.dialog_message+' itemName: '+ respData.json_data.itemName ); break; case 'collect slot': slotSpins = respData.json_data.freeSpins; slotBonus = respData.json_data.bonusMeter; var slotText = ''; if(respData.json_data.isJackpot){ slotText += 'You won on the slots! Payout: '+ respData.json_data.payout+' jackpotWinAmt: '+ respData.json_data.jackpotWinAmt; } else { slotText += 'You did not win on this slot pull. Remaining Spins: '+ slotSpins; } addToLog('info Icon', slotText ); DEBUG('Result: ' +respData.json_data.result+' bonusMeter:'+ respData.json_data.bonusMeter+' payout:'+ respData.json_data.payout + ' isJackpot:'+ respData.json_data.isJackpot+' jackpotWinAmt:'+ respData.json_data.jackpotWinAmt+' freeSpins'+ respData.json_data.freeSpins); break; case 'autoStatReward': DEBUG('autoStatReward results '+ responseText); return false; break; case 'autoUpgradeNY_getBalance': var userBankBalance = respJSON.user_fields.user_bank_balance+''; GM_setValue('userBankBalance', userBankBalance); addToLog('updateGood Icon', 'Current NY Bank Balance: $'+userBankBalance); return false; break; case 'autoUpgradeNY': var upgradeResponse = JSON.stringify(respData); var upgradeResponseMsg=""; var userBankBalance = respJSON.user_fields.user_bank_balance+''; GM_setValue('userBankBalance', userBankBalance); if(upgradeResponse.indexOf('description') != -1){ upgradeResponseMsg = respData.description; if(upgradeResponseMsg.indexOf('You have purchased') != -1){ var currentLevel = parseInt(GM_getValue(context, 999)); currentLevel++; GM_setValue(context, currentLevel); addToLog('updateGood Icon', upgradeResponseMsg+ '. Current Level: '+currentLevel+'. Current NY Bank Balance: $'+userBankBalance+'.'); } } else { addToLog('updateBad Icon', upgradeResponseMsg+'. Current NY Bank Balance: $'+userBankBalance+'.'); GM_setValue(context, 999); } return false; break; // Parse Ice Check responses. case 'icecheck profile': var alive = !/is already dead or too weak!/.test(responseText); if(context){ context.setAttribute('style', 'background: '+ (alive ? 'green;' : 'red;')); context.setAttribute('title', (alive ? 'Target is alive' : 'Target is iced')+', click to refresh.'); context.addEventListener('click', customizeProfile, false); DEBUG('Successfully set target status: '+ (alive ? 'alive.' : 'iced.')); } return false; break; case 'fight': //colorDEBUG(responseText, caq); var fight_wrapper = xpathFirst('.//div[@id="fv2_widget_wrapper"]' , innerPageElt); return logFightResponse(innerPageElt, fight_wrapper, context, 0, respJSON); break; case 'multifight': //colorDEBUG(responseText, caq); var fight_wrapper = xpathFirst('.//div[@id="fv2_widget_wrapper"]' , innerPageElt); return logFightResponse(innerPageElt, fight_wrapper, context, 1, respJSON); break; case 'braziljob': var pushNextJob = false; var jobCity; var jobName; var xpGain; var cashGain; var cashUsed; var jobLoot; var jobMastery; if(!IsJsonString(responseText)){ jobName = xpathFirst('.//h4',context).innerHTML.untag();; xpGain = xpathFirst('.//ul[contains(@class,"pays")]//li[@class="experience"]',context).getAttribute('base_value'); cashGain = xpathFirst('.//ul[contains(@class,"pays")]//li[contains(@class,"cash_icon_jobs")]',context).getAttribute('base_value'); cashUsed = xpathFirst('.//ul[contains(@class,"uses")]//li[contains(@class,"cash_icon_jobs")]',context); if(cashUsed) { cashUsed = parseInt(cashUsed.getAttribute('base_value')); logTxt = 'You performed '+jobName+', earning '+xpGain+' experience. You spend '+cities[city][CITY_CASH_SYMBOL]+makeCommaValue(cashUsed)+''; } else logTxt = 'You performed '+jobName+', earning '+cities[city][CITY_CASH_SYMBOL]+makeCommaValue(cashGain)+' and '+xpGain+' experience'; if(logTxt) addToLog('process Icon', logTxt); } else { try { if( (typeof respJSON.jobResult) !== undefined){ var jobCity = respJSON.jobResult.city; jobCity = jobCity-1; var jobName = respJSON.jobResult.name; var xpGain = respJSON.jobResult.experience; var cashGain = makeCommaValue(parseCash(respJSON.jobResult.cash)); var cashUsed = makeCommaValue(parseCash(respJSON.jobResult.cashUsed)); var jobLoot = respJSON.jobResult.loot[0]; var jobMastery = parseInt(respJSON.jobResult.masteryTotal); var jobMasteryInc = parseInt(respJSON.jobResult.masteryIncrease); var jobMastered = respJSON.jobResult.mastered; var jobMasteryTxt = jobMastery+' % Mastered'; var jobMasteryLeft = 100-jobMastery; if(jobMastery == 100 || jobMastered) pushNextJob = true; if(cashGain && cashGain !="0"){ logTxt = 'You performed '+jobName+', earning '+cities[jobCity][CITY_CASH_SYMBOL]+cashGain+' and '+xpGain+' experience'; } else { if(xpGain) logTxt = 'You performed '+jobName+', earning '+xpGain+' experience. You spend '+cities[jobCity][CITY_CASH_SYMBOL]+cashUsed+''; else logTxt = 'You performed '+jobName+''; } if( (typeof respJSON.jobResult.itemsUsed) !== undefined){ itemsUsed = respJSON.jobResult.itemsUsed; var iLength = itemsUsed.length; if(iLength>0){ var usedAnd = ''; logTxt +=' and used '; for(i=0;i'+usedItem+''; } else { usedItem = itemsUsed[i].item.name; logTxt += usedAnd+''+usedQty+' x '+usedItem+''; } usedAnd = ' and '; } } } logTxt=logTxt+'.'; if(jobMasteryInc && !pushNextJob) logTxt+=' Job Mastery Increased by '+jobMasteryInc+'%.'; if(logTxt) addToLog('process Icon', logTxt); if(jobLoot){ var lootDrops = $x('.//div[@class="job_additional_results"]/div[@class="loot_item"]', context); if(lootDrops && lootDrops.length>0){ var lootDropTxt=''; var lootDropItems=''; for(i=0,iLength = lootDrops.length;i'; else lootDropItems = 'Loot Found:
'+lootDiv.innerHTML+'
'; } } } if(lootDropItems) addToLog('lootbag Icon', lootDropItems); } var itemName; var reqloot = false; var itemFound = true; //We assume the job dropped the correct loot var lootBag = new Array(); // Try fetching the item name from the job requirement array requirementJob.forEach( function(j){ if(j[1].toUpperCase().trim() == jobName.toUpperCase().trim()){ lootBag.push(j[0]); DEBUG('Matching Item: '+j[0]+' from '+j[1]); itemName = j[0]; } } ); var items = getSavedList('itemList'); if(typeof(items[0]) == 'undefined' || items.length == 0 || itemFound == false){ DEBUG('No found / needed items in required item list.'); } else { // NOTE: The single equal sign is intentional in this while() condition. while ((itemName = lootBag.pop())){ DEBUG('Looking for '+ itemName+' in needed items list. We still need '+ items.length+' item(s).'); for (var i = 0; i < items.length; i++){ if(itemName.indexOf(items[i].trim()) != -1 ){ // we found some needed loot reqLoot = true; removeSavedListItem('itemList', itemName); removeJobForItem('jobsToDo', itemName); popJob(); return false; } } } } if(reqLoot) addToLog('found Icon','We assume the job dropped the item we were looking for ('+ itemName+')!'); } } } catch (ex){ //colorDEBUG('jobResult Error: '+ ex, cre); } try { if( (typeof respJSON.data.impulseBuy.message) !== undefined){ var jobMessage; jobMessage = respJSON.data.impulseBuy.message; if(jobMessage.indexOf('loot drops') !=-1){ var currentJobTitle = xpathFirst('.//h4', context); var currentJob = currentJobTitle.innerHTML.trim(); var currentJobRow = context; var itmSearch = (/p>(.+)buy/i.exec(jobMessage))[1]; if(itmSearch!=''){ itmSearch = itmSearch.substring(0, itmSearch.length-2); DEBUG('Item(s) Required for this job : '+itmSearch); // Save the current job for later. The current job should not already exist in the list, so check first. var items = getSavedList('itemList'); var jobs = getSavedList('jobsToDo', ''); DEBUG('Current Job List: '+jobs); if(jobs.indexOf(currentJob) == -1){ jobs.push(currentJob); DEBUG('Saving '+ currentJob+' for later. Need to fetch pre-req items first.'); setSavedList('jobsToDo', jobs); } else { DEBUG(currentJob+' already saved for later. Need to fetch pre-req items first.'); } var itemFound = false; // Try fetching the items from the job requirement array requirementJob.forEach( function(j){ if(level >= cities[j[2]][CITY_LEVEL] && j[0].toUpperCase().trim() == itmSearch.toUpperCase().trim()){ jobs.push(j[1]); items.push(itmSearch.trim()); itemFound = true; jobFound = j[1]; } } ); // Set the flag if at least one item is found if(!itemFound) DEBUG(itmSearch+' not found in the requirement job array.'); else { setSavedList('itemList', items.unique()); setSavedList('jobsToDo', jobs); popJob(); return false; } } } if(jobMessage.indexOf('following items') !=-1){ jobMessage = jobMessage.wipe(); var jobButton = xpathFirst('.//a[contains(@id, "btn_dojob")]', context); DEBUG(jobButton.innerHTML.untag()+' : '+jobButton.id); var JobId = jobButton.id; if(JobId.match(/dojob_(\d+)/i)) JobId=RegExp.$1; DEBUG(' - - brazil Message results jobMessage:'+ jobMessage+' for '+ jobButton.id+' -> '+JobId); addToLog('warning Icon', jobMessage); SelectedJob = jobButton.getAttribute('href'); colorDEBUG('Need items for '+JobId+' - '+SelectedJob+' in '+cities[city][CITY_NAME]); if(SelectedJob && JobId){ colorDEBUG('Need Items - BUILDING LINK ELT in '+cities[city][CITY_NAME]+'-'+cities[city][CITY_NUMBER]); var JobTab = (/tab=([\d]+)/.exec(SelectedJob))[1]; var JobTmp = (/tmp=([\da-f]+)/.exec(SelectedJob))[1]; var JobCb = (/cb=([\da-f]+)/.exec(SelectedJob))[1]; var JobPerson = (/xw_person=([\d]+)/.exec(SelectedJob))[1]; var ajaxID = createAjaxPage(true); // building buy link form: html_server.php?xw_controller=job&xw_action=buy_required_items&xw_city=7&tmp=8b435d14be762b9fc799f029177a4095&cb=b17fb490555e11e0bcbc6101d420c937&xw_person=43398787&jobId=29&cityId=7&xw_client_id=8 var elt = makeElement('a', null, {'onclick':'return do_ajax("'+ ajaxID+'","remote/html_server.php?xw_controller=job&xw_action=buy_required_items&xw_city='+cities[city][CITY_NUMBER]+'&tmp='+JobTmp+'&cb='+JobCb+'&xw_person='+JobPerson+'&jobId='+JobId+'&cityId='+cities[city][CITY_NUMBER]+'&xw_client_id=8", 1, 1, 0, 0); return false;' } ) ; if(elt){// Buy Items! colorDEBUG('Need Items - LINK ELT created '+cities[city][CITY_NAME]); clickAction = 'buy Brazil'; clickContext = city; clickElement(elt); colorDEBUG(' - - Message results : Clicked to buy Brazil/Chicago Items needed for jobs', cli); return false; } else { colorDEBUG('Need Items - Failed to create LINK ELT for '+cities[city][CITY_NAME], cre); } } else { colorDEBUG('Need Items - Missing JobId or SelectedJob in '+cities[city][CITY_NAME], cre); } } } } catch (ex){ //colorDEBUG('Error no MessageResult: '+ ex, cre); } if(pushNextJob && !isGMChecked('repeatJob'))goJobsNav(); } return false; break; case 'buy Brazil': DEBUG(' - - brazil buy results
'+ responseText); try { if( (typeof respJSON.data.impulseBuy.message) !== undefined){ var jobMessage; jobMessage = respJSON.data.impulseBuy.message; jobMessage = jobMessage.wipe(); DEBUG(' - - brazil Message results jobMessage:'+ jobMessage); addToLog('info Icon', jobMessage); } } catch (ex){ //colorDEBUG('Error no MessageResult: '+ ex, cre); } return false; break; // Log quickHeal() response. case 'quick heal': //colorDEBUG('QuickHeal: '+responseText); // Attempt to correct the displayed health value if(healthElt && responseText.match(/,"user_health":"?([0-9]+)"?,/i)){ healthElt.innerHTML = RegExp.$1; } if(responseText.match(/doctor healed ([0-9]+) health (.+?)\./i)){ if(autoplay) GM_setValue('healWaitStarted',false); var addHealth = RegExp.$1; var cost = ""; if(RegExp.$2.match(REGEX_CASH)) cost = RegExp.$1+makeCommaValue(RegExp.$2); addToLog('health Icon', ''+' Restored +'+ addHealth+' health for '+ cost+'.'); setGMTime('healTimer','00:00:30'); //getListed(xw_user); } else if(/you cannot heal so fast/i.test(responseText)){ addToLog('warning Icon', ''+'Attempted to heal too quickly.'+''); } else if(/have enough/i.test(responseText)){ var healCity = parseInt(respJSON.user_fields.current_city_id)-1; if(GM_getValue('autoHealBackup', 0)){ addToLog('warning Icon', ''+'You don\'t have enough money to heal in '+cities[healCity][CITY_NAME]+'.
Trying to heal in NY.
'); quickHeal(autoplay, true); } else { GM_setValue('autoHeal', 'unchecked'); addToLog('warning Icon', ''+'You don\'t have enough money to heal in '+cities[healCity][CITY_NAME]+'.
Disabling auto-heal.
'); } } return false; break; // Parse and Save property status case 'check property': switch(context){ case LV : GM_setValue('casinoReport', JSON.stringify(respData)); case ITALY: GM_setValue('villageReport', JSON.stringify(respData)); case BRAZIL: GM_setValue('brazilReport', JSON.stringify(respData)); case CHICAGO: GM_setValue('chicagoReport', JSON.stringify(respData)); } colorDEBUG('Saved Property Status for :'+cities[context][CITY_NAME]); return false; break; // Casino Parts case 'casino parts': setGMTime('askCasinoPartsTimer', '2 hours'); DEBUG('Parsed JSONResponse for clicking AskCasinoParts. Timer Reset for 2 hours.'); return false; break; // Play Slots case 'play slots': setGMTime('askPlaySlotsTimer', '4 hours'); DEBUG('Parsed JSONResponse for clicking AskPlaySlots. Timer Reset for 4 hours.'); return false; break; // Village Parts case 'village parts': setGMTime('askVillagePartsTimer', '2 hours'); DEBUG('Parsed JSONResponse for clicking AskVillageParts. Timer Reset for 2 hours.'); return false; break; // Football Fans case 'football fans': setGMTime('askFootballFansTimer', '4 hours'); DEBUG('Parsed JSONResponse for clicking AskFootballFans. Timer Reset for 4 hours.'); return false; break; // New Parts case 'new parts': colorDEBUG('new parts: '+responseText); setGMTime('askNewPartsTimer', '2 hours'); DEBUG('Parsed JSONResponse for clicking AskNewParts. Timer Reset for 2 hours.'); return false; break; // Brazil Parts case 'brazil parts': setGMTime('askBrazilPartsTimer', '2 hours'); DEBUG('Parsed JSONResponse for clicking AskBrazilParts. Timer Reset for 2 hours.'); return false; break; // Chicago Parts case 'chicago parts': setGMTime('askChicagoPartsTimer', '2 hours'); DEBUG('Parsed JSONResponse for clicking AskChicagoParts. Timer Reset for 2 hours.'); return false; break; // Save NY 'active' properties case 'save properties': return false; break; // Build from NY Limited Properties case 'build limited' : var propCount = context.propCount; buildProp = cityProperties[propCount][ctPropName]; timerName = cityProperties[propCount][ctPropTimer]; if(responseText!=""){ addToLog('process Icon', buildProp+': '+responseText); setGMTime(timerName, '18 hours'); } else { addToLog('warning Icon', buildProp+': You can not craft yet.'); setGMTime(timerName, '1 hour'); } return false; break; // Build ? Purcahse from ITALY / BRAZIL / CHICAGO Properties case 'build other': var propCount = context.propCount; var buildItem = cityProperties[propCount][ctGMId]; var buildProp = cityProperties[propCount][ctPropName]; var timerName = cityProperties[propCount][ctPropTimer]; var buildCity = cityProperties[propCount][ctPropCity]; var cityName = cities[buildCity][CITY_NAME]; DEBUG('Make '+cityName+': '+context.itemName+' - '+context.buildType+'.') var refreshRate = 0; var timeStamp = 0; var respMessage = respData.purchase_message; addToLog('lootbag Icon', respMessage); if(responseText.match(/cannot be purchased/i)){ DEBUG(context.itemName+' can not be build, disabling'); GM_setValue(buildItem, 0); return false; } if(responseText.match(/available_purchases(.+?)(\d+?),/i)){ refreshRate = parseFloat(RegExp.$2); DEBUG('Available Purchases Left: '+RegExp.$2); if(refreshRate){ return false; break; } } if(responseText.match(/purchase_refresh_rate(.+?)(\d+?),/i)){ refreshRate = parseFloat(RegExp.$2); DEBUG('Refresh Rate: '+RegExp.$2); } if(responseText.match(/last_purchase_time_stamp(.+?)(\d+?),/i)){ timeStamp = parseFloat(RegExp.$2); DEBUG('timeStamp: '+RegExp.$2); } if(refreshRate && timeStamp){ var dueTime = timeStamp + refreshRate; var currentTime = Math.round(new Date().getTime()/1000.0); DEBUG('Current: '+currentTime); if(currentTime < dueTime){ var timeLeft = parseFloat(dueTime) - parseFloat(currentTime)+10; DEBUG('timeLeft: '+timeLeft); var timeLeftTxt = secondsToHMS(timeLeft); (timeLeftTxt ==1) ? timeLeftTxt+= ' hour' : timeLeftTxt+= ' hours'; setGMTime(timerName, timeLeftTxt); DEBUG('Parsed JSONResponse for '+cityName+' Item. Timer '+timerName+' reset for '+timeLeftTxt+'.'); } else { setGMTime(timerName, '2 hours'); DEBUG('Parsed JSONResponse for '+cityName+' Item. Timer reset for 2 hours.'); colorDEBUG(responseText); } } else { setGMTime(timerName, '2 hours'); DEBUG('Parsing JSONResponse for '+cityName+' Item FAILED. Timer reset for 2 hours.'); colorDEBUG(responseText); } return false; break; // Log any message from collecting property take. case 'collect take': var collectResponse = JSON.stringify(respData); var collectResponseMsg=""; DEBUG('Collect string take :'+collectResponse); if(collectResponse.indexOf('description') != -1) collectResponseMsg = respData.description; else collectResponseMsg = respData.success_message; if(collectResponseMsg.match(/collected (.+?) from your properties/i)){ var collectString = 'You have collected '+ RegExp.$1+' from your properties.'; addToLog(cities[context][CITY_CASH_CSS], collectString); } if(collectResponseMsg.match(/you have also received:/i)){ var collectXtras = respData.success_image_names; if(collectXtras.length>0){ collectString = 'You have also received : '; collectHelp = ''; for(i=0,iLength=collectXtras.length;i0){ collectString = 'You also collected '; collectHelp = ''; for(i=0,iLength=shopAmounts.length;i' +shopAmounts[i]+' '+ shopParts[i]+' items from your '+ shopNames[i]+''; if(i==iLength-1) collectHelp = ', '; else collectHelp = ' and '; } addToLog(cities[context][CITY_CASH_CSS], collectString); } } break; } setGMTime('takeHour'+ cities[context][CITY_NAME], '1 hour'); // collect every 1 hour return false; break; // Log any message from withdrawing money. case 'quick withdraw': var logBalance = '
Remaining Bank Balance: '+ cities[context][CITY_CASH_SYMBOL] + makeCommaValue(acctBalance); if(/You Withdrew/i.test(respData.success_message)){ addToLog('cashVegas Icon', respData.success_message + logBalance); } else { addToLog('warning Icon', 'Disabling autoMission:
You don\'t have enough money to do ' + missions[GM_getValue('selectMission', 1)][MISSION_NAME]+'.'+ logBalance); GM_setValue('autoMission', 0); update_nrg_stam(); // update the icon to show energy spend is off } return false; break; // Log any message from depositing money. case 'quick deposit': // Log if city has changed after banking if(city != context){ addToLog('warning Icon', 'Warning! You have traveled from '+ cities[context][CITY_NAME]+' to '+ cities[city][CITY_NAME]+' while banking. Check your money.'); } var respDeposit=''; if(context == LV) respDeposit = respData.success_message; else respDeposit = respJSON.deposit_message; // Money deposited (all cities) if(respDeposit.match(/([0-9,,]+).+?was deposited/i) || // success for all cities except LV respDeposit.match(/You Deposited .\$([0-9,,]+) into your Vault/i)){ // success for LV quickBankFail = false; var cashDeposit = RegExp.$1; addToLog(cities[context][CITY_CASH_CSS], ''+ cities[context][CITY_CASH_SYMBOL] + cashDeposit+' was deposited '+ (context == LV ? 'into your vault.' : 'in your account after the bank\'s fee.')); // Las Vegas: too much money } else if(/cannot deposit this much/i.test(respDeposit) || /cannot deposit that much/i.test(respDeposit)){ quickBankFail = false; var logText = 'You can\'t deposit this much (you don\'t have enough cash or your vault is to small).'; if(!GM_getValue('vaultHandling', 0)) logText += '
Please consider enabling PS MWAP vault handling.'; addToLog(cities[context][CITY_CASH_CSS], logText); // Las Vegas: vault full } else if(/cannot deposit any more/i.test(respDeposit)){ quickBankFail = false; var logText = 'You can\'t deposit anymore, your vault is full!'; if(!GM_getValue('vaultHandling', 0)) logText += '
Please consider enabling PS MWAP vault handling.'; addToLog(cities[context][CITY_CASH_CSS], logText); if(GM_getValue('vaultHandling', 0)) GM_setValue('vaultSpace', '0'); // Las Vegas: invalid amount } else if(/invalid amount/i.test(respDeposit)){ quickBankFail = false; // Not enough money } else if(/have enough money/.test(respDeposit)){ quickBankFail = false; // Minimum deposit not met ($10) } else if(/deposit at least/.test(respDeposit) && respDeposit.match(/([0-9,,]+)/)){ quickBankFail = false; // Las Vegas: no vault? } else if(respData.result == null || acctBalance == 0){ quickBankFail = false; addToLog(cities[context][CITY_CASH_CSS], 'Depositing failed without a response; if you are in Las Vegas, perhaps you don\'t have a vault yet?'); if(GM_getValue('vaultHandling', 0)) GM_setValue('vaultSpace', '0'); // Unknown JSON response } else { quickBankFail = true; addToLog('warning Icon', 'Quick Deposit failed: Unknown JSON response:
'+ responseText); } return false; break; case 'marketplace': var responseContainer = xpathFirst('.//div[@id="responseContainer"]'); if(!responseContainer){ responseContainer = makeElement('div', document.getElementById('final_wrapper'), {'id':'responseContainer','style':'display:none;'}); } responseContainer.innerHTML = response; var eltContainer = makeElement('div', null, {'id':'marketInfo','style':'clear:both; width: 745px;','class':'clearfix'}); var eltHeader = makeElement('div', eltContainer, {'id':'FightClubModule','style':'float: left; width: 735px;','class':'empire_module_header'}); var eltTitle = makeElement('div', eltHeader, {'class':'empire_module_title'}); var eltTitleSpan = makeElement('span', eltTitle); eltTitleSpan.appendChild(document.createTextNode('Fight Club')); var vcEltImg = xpathFirst('.//img[contains(@src,"victory_icon.gif")]', responseContainer); if(vcEltImg){ vcElt = vcEltImg.parentNode; if(vcElt){ var eltVC = makeElement('div', eltTitle, {'style':'float:right;margin-right:15px'}); eltVC.innerHTML += vcElt.innerHTML; } } var masteryBarElt = xpathFirst('.//div[@class="fightmastery_meter"]', responseContainer); if(masteryBarElt){ var eltMasteryBar = makeElement('div', eltTitle, {'class':'fightmastery_meter','style':'float:right;margin-right:45px;margin-top:-1px;'}); eltMasteryBar.innerHTML += masteryBarElt.innerHTML; } var marketList = xpathFirst('.//div[@id="full_list"]', responseContainer); if(marketList){ var eltSubContainer = makeElement('div', eltHeader, {'style':'width: 729px; padding: 5px; float: none;','class':'playerupdate_box'}); var eltMarketList = makeElement('div', eltSubContainer); var itemListElts = $x('.//div[contains(@style,"relative")]', marketList); if(itemListElts.length>0){ var j=0; for(i=itemListElts.length-1;i>=0;i--){ if(j>=9 && i > 1) continue; secondElt = itemListElts[i].firstChild.nextSibling; fourthElt = itemListElts[i].firstChild.nextSibling.nextSibling.nextSibling; if(i>1){ itemListElt = makeElement('div', null, {'style':'float: left; width: 220px;height:135px;border:1px dotted #484848;padding:10px;'}); eltMarketList.appendChild(itemListElt); } else { itemListElt = makeElement('div', null, {'style':'float: left; width: 340px;height:125px;border:1px dotted #484848;padding:10px;'}); eltMarketList.insertBefore(itemListElt, eltMarketList.firstChild); } itemListElt.innerHTML = secondElt.innerHTML+fourthElt.innerHTML; j++; } var eltShadow = makeElement('div', eltContainer, {'style':'float: left; background: url("http://mwfb.static.zgncdn.com/mwfb/graphics/empire/shadow_upper_right.png") no-repeat scroll 0% 0% transparent; height: 8px; width: 8px;'}); eltShadow = makeElement('div', eltContainer, {'style':'float: left; background: url("http://mwfb.static.zgncdn.com/mwfb/graphics/empire/shadow_right_side.png") repeat-y scroll 0% 0% transparent; height: 310px; width: 8px;'}); eltShadow = makeElement('div', eltContainer, {'style':'float: left; background: url("http://mwfb.static.zgncdn.com/mwfb/graphics/empire/shadow_lower_left.png") repeat scroll 0% 0% transparent; height: 8px; width: 8px;'}); eltShadow = makeElement('div', eltContainer, {'style':'float: left; background: url("http://mwfb.static.zgncdn.com/mwfb/graphics/empire/shadow_bottom.png") repeat scroll 0% 0% transparent; height: 8px; width: 727px;'}); eltShadow = makeElement('div', eltContainer, {'style':'float: left; background: url("http://mwfb.static.zgncdn.com/mwfb/graphics/empire/shadow_lower_right.png") repeat scroll 0% 0% transparent; height: 8px; width: 8px;'}); } } context.appendChild(eltContainer); postSize(); return false; break; default: colorDEBUG('BUG DETECTED: Unrecognized JSON action "'+ action+'".
'+ responseText); return false; } } catch (ex){ DEBUG('Exception (logJSONResponse): '+ ex+', autoplay: '+ autoplay+', action: '+ action+', context: '+ context+', response:
'+ response); } } // Interprets the response to an action that was taken. // // rootElt: An element whose descendents contain the response to interpret. // action: The action taken, such as 'fight', 'heal', 'hitlist', etc. // context: (optional) Any further data needed to describe the action // Returns: true if something has been done that will cause the inner page // to change, such as clicking somewhere or loading another page. function logResponse(rootElt, action, context){ if(action == 'goHome') return false; var messagebox; // Set default timer properties. Autoplay.fx = goHome; Autoplay.delay = getAutoPlayDelay(); colorDEBUG('logResponse ('+action+') default fx: goHome, delay: '+Autoplay.delay, cfu); if(action=='fight' || action =='multifight'){ //autoReload(false, 'logResponse'); // stops the forced reload page var fight_wrapper = xpathFirst('.//div[@id="fv2_widget_wrapper"]' , rootElt); if(!fight_wrapper) fight_wrapper = xpathFirst('.//div[@class="fight_results"]', rootElt); if(!fight_wrapper){ if(GM_getValue('staminaSpendHow') == getStaminaMode()){ cycleSavedList('pfightlist'); return false; } } switch (action){ case 'fight': return logFightResponse(innerPageElt, fight_wrapper, context, 0); break; case 'multifight': return logFightResponse(innerPageElt, fight_wrapper, context, 1); break; } } if(action=='load clan'){ DEBUG('Are we on the clan page we want to be on?'); if(onClanNav(GM_getValue('AutoBattleClanID',0))){ DEBUG('Looking for Challenge Link'); var challenge = xpathFirst('.//a[contains(@href,"xw_controller=epicBattle&xw_action=challengePop")]', rootElt); if(challenge){ DEBUG('We found the challenge button, clicking it'); setGMTime('autoBattleTimer', '60:00'); clickAction = 'battlePop'; clickElement(challenge); } else { DEBUG('No Challenge Popup found check again in 10 minutes'); setGMTime('autoBattleTimer', '10:00'); Autoplay.delay = getAutoPlayDelay() Autoplay.start(); return true; } } } if(action=='load battlepage'){ return false; } if(action=='load battlecollect'){ if(onBattlePage(1)){ DEBUG('Looking for Battle Collect Link'); var collectLink = xpathFirst('.//a[contains(@onclick,"xw_controller=epicBattle&xw_action=getResults") and contains(.,"Collect")]');// if(collectLink){ DEBUG('Found a Battle Collect link clicking it'); setGMTime('autoBattleCollectTimer', '05:00'); clickElement(collectLink); Autoplay.delay = getAutoPlayDelay() Autoplay.start(); return true; } else { // no collect to link found, set the timer to 60 minutes from now.. DEBUG('No Battle Collect link found'); setGMTime('autoBattleCollectTimer', '60:00'); Autoplay.delay = getAutoPlayDelay() Autoplay.start(); return true; } } } // Crate selling pop-up message if(!messagebox){ messagebox = xpathFirst('.//div[@id="default_id_box"]', rootElt); } // New NY job layout message result if(!messagebox){ messagebox = xpathFirst('.//div[contains(@class,"message_body")]', rootElt); } // New job layout message result if(!messagebox){ messagebox = xpathFirst('.//div[@class="job_results"]', rootElt); } // BRAZIL job layout message result if(!messagebox){ messagebox = xpathFirst('.//div[contains(@class,"job_controller")]', contentRoweElt); } // New message box message if(!messagebox){ messagebox = xpathFirst('.//div[@id="msg_box_div_1"]', rootElt); } // Message box (new header) if(!messagebox){ messagebox = xpathFirst('.//div[@id="mbox_generic_1"]', rootElt); } // Bank message if(!messagebox){ messagebox = xpathFirst('.//div[@id="bank_messages"]', appLayoutElt); } // Hospital message if(!messagebox){ messagebox = xpathFirst('.//div[@id="hospital_message"]', appLayoutElt); } // Rob message if(!messagebox){ messagebox = xpathFirst('.//div[@id="'+ context +'" and @class="rob_slot"]', rootElt); } if(!messagebox){ messagebox = xpathFirst('.//div[@class="rob_board"]', rootElt); } // Build Car/Weapon success popup if(!messagebox){ messagebox = xpathFirst('.//div[@class="chop_build_final"]', appLayoutElt); } // Operations Message : shows total mastery result } if(!messagebox){ messagebox = xpathFirst('.//div[ contains (@id,"missionTask_'+Miss_Slot+'_'+Miss_ID+'_module")]', rootElt); } // Normal message if(!messagebox){ messagebox = xpathFirst('.//table[@class="messages"]', rootElt); } if(action=='withdraw' && context){ autoBankWithdraw(context); Autoplay.start(); return true; } if(!messagebox){ //if(action == 'help') return true; // no message box for help message. Just continue on. if(action == 'load clan') return true; // No log message for this.. if(action == 'load battlecollect') return true; // No log message for this.. if(action == 'battlePop') return true; // No log message for this.. if(action == 'quick heal') return false; if(action == 'autohit') return false; if(action == 'fight' || action=='multifight'){ colorDEBUG(' we have passed all message boxes but have action (multi)fight ', cbl); // If fighting from a user-specified list, cycle it. Otherwise, the problem might repeat indefinitely. if(GM_getValue('staminaSpendHow') == getStaminaMode()) cycleSavedList('pfightlist'); return false; } //else { // colorDEBUG('Unexpected response page: action -'+ action); // DEBUG('Unexpected response page: no message box found - logResponse: HTML=
'+ rootElt.innerHTML.untag()); // return false; //} messagebox = rootElt; } // Since the attempted action received a response, stop skipping fight. skipStaminaSpend = false; var inner = messagebox ? messagebox.innerHTML : ''; var innerNoTags = inner.untag(); var cost, experience, result; switch (action){ case 'autohit': case 'fight': var fight_wrapper = xpathFirst('.//div[@id="fv2_widget_wrapper"]' , innerPageElt); return logFightResponse(innerPageElt, fight_wrapper, context, 0); break; case 'multifight': var fight_wrapper = xpathFirst('.//div[@id="fv2_widget_wrapper"]' , innerPageElt); return logFightResponse(innerPageElt, fight_wrapper, context, 1); break; case 'load battlecollect': DEBUG('We have a load battlecollect message box to handle.. doing nothing..'); break; case 'braziljob': break; // Parse Skill Point Allocation responses case 'autoStatAllocation': DEBUG('autoStatAllocation results'); return false; break; case 'autoStatReward': DEBUG('autoStatReward results'); return false; break; case 'autoRob': if(!isGMChecked('fastRob')) return logRobResponse(rootElt, messagebox, context); else { randomizeStamina(); Autoplay.fx = goRobbingTab; Autoplay.delay = noDelay; Autoplay.start(); return true; } case 'heal': case 'quick heal': if(innerNoTags.match(/doctor healed ([0-9]+) health (.+?)\./i)){ if(autoplay) GM_setValue('healWaitStarted',false); var addHealth = RegExp.$1; var cost = RegExp.$2.match(REGEX_CASH); addToLog('health Icon', ''+' Restored +'+ addHealth+' health for '+ cost+'.'); setGMTime('healTimer','00:00:30'); //getListed(xw_user); } else if(innerNoTags.indexOf('You cannot heal so fast') != -1){ addToLog('warning Icon', ''+'Attempted to heal too quickly.'+''); return true; } return false; break; case 'Missionjob': //doatest var Mission_ResultsElt = xpathFirst('.//div[@class="task_results"]', messagebox); if(Mission_ResultsElt){ DEBUG('found Mission_ResultsElt'); var xpGainTxt=""; var cashGainTxt=""; var cashCostTxt=""; var Mission_Node = Mission_ResultsElt.parentNode; var Mission_Name_Elt = xpathFirst('.//div[@class="doTaskName"]', Mission_Node); if(!Mission_Name_Elt) Mission_Name_Elt = xpathFirst('.//span[@class="doTaskName"]', Mission_Node); if(Mission_Name_Elt) Mission_Name = Mission_Name_Elt.innerHTML.replace(/"/g,''); var doTaskPaysModule = xpathFirst('.//dl[contains(.,"gained")]', Mission_ResultsElt); var xpGainElt = xpathFirst('.//dd[@class="experience doTaskDDHeight"]', doTaskPaysModule); if(xpGainElt){ xpGainTxt = xpGainElt.innerHTML; if(xpGainTxt.match(/([\d,]*\d)\s*?\(you/i)) xpGainTxt = RegExp.$1+ " experience"; } var cashGainElt = xpathFirst('.//dd[@class="italy_cash_icon doTaskDDHeight"]', doTaskPaysModule); bankCity = ITALY; if(!cashGainElt){ cashGainElt = xpathFirst('.//dd[@class="vegas_cash_icon doTaskDDHeight"]', doTaskPaysModule); bankCity = LV; } if(!cashGainElt){ cashGainElt = xpathFirst('.//dd[@class="brazil_cash_icon doTaskDDHeight"]', doTaskPaysModule); bankCity = BRAZIL; } if(!cashGainElt){ cashGainElt = xpathFirst('.//dd[@class="nyc_cash_icon doTaskDDHeight"]', doTaskPaysModule); bankCity = NY; } if(cashGainElt){ cashGainTxt = cashGainElt.innerHTML; if(cashGainTxt.match(/([\d,]*\d)\s*?\(you/i)) cashGainTxt = cities[bankCity][CITY_CASH_SYMBOL]+RegExp.$1; } var doTaskUsesModule = xpathFirst('.//dl[contains(.,"Spent")]', Mission_ResultsElt); var cashCostElt = xpathFirst('.//dd[@class="italy_cash_icon doTaskDDHeight"]', doTaskUsesModule); bankCity = ITALY; if(!cashCostElt){ cashCostElt = xpathFirst('.//dd[@class="vegas_cash_icon doTaskDDHeight"]', doTaskUsesModule); bankCity = LV; } if(!cashCostElt){ cashCostElt = xpathFirst('.//dd[@class="brazil_cash_icon doTaskDDHeight"]', doTaskUsesModule); bankCity = BRAZIL; } if(!cashCostElt){ cashCostElt = xpathFirst('.//dd[@class="nyc_cash_icon doTaskDDHeight"]', doTaskUsesModule); bankCity = NY; } if(!cashCostElt){ cashCostElt = xpathFirst('.//dd[@class="chicago_cash_icon doTaskDDHeight"]', doTaskUsesModule); bankCity = CHICAGO; } if(cashCostElt){ cashCostTxt = cashCostElt.innerHTML.untag(); if(cashCostTxt.match(/([\d,]*\d)\s*?\(you/i)){ cashCostTxt = cities[bankCity][CITY_CASH_SYMBOL]+RegExp.$1; } } if(xpGainElt && (cashGainElt || cashCostElt)){ if(xpGainTxt && cashGainTxt){ var result = 'You performed '+Mission_Name+', gaining '+xpGainTxt+' and '+cashGainTxt+'.'; } else if(xpGainTxt && cashCostTxt){ var result = 'You performed '+Mission_Name+', gaining '+xpGainTxt+' and used '+cashCostTxt+'.'; } else { var result = 'You performed '+Mission_Name+', gaining '+Miss_Pay_Exp+' and '+Miss_Pay_Cash+'.'; } } else { var result = 'You tried to perform '+Mission_Name+', but you don\'t have enough energy or stamina to do the job.'; } addToLog('process Icon', result); masteryGainElt = xpathFirst('.//div[@class="doTaskMastery"]', messagebox); var masteryGainTxt = ""; var pushNextJob = false; // IF we have the mastery gain bar, DEBUG(' checking mastery Mission ID :'+Miss_ID ); if(masteryGainElt){ if( (parseInt(masteryGainElt.innerHTML.substr(0, masteryGainElt.innerHTML.indexOf('%'))) )==100 ){ masteryGainTxt = '. Operations Task '+ masteryGainElt.innerHTML.substr(0, masteryGainElt.innerHTML.indexOf('%'))+'% Mastered'; pushNextJob = true; } else { masteryGainTxt = '. Operations Task '+ masteryGainElt.innerHTML.substr(0, masteryGainElt.innerHTML.indexOf('%'))+'% Mastered'; DEBUG(' NO mastery '+Miss_ID + masteryGainTxt ); } } } else { DEBUG('found NO Mission_ResultsElt'); } //////////// add stuff here //////////// add stuff here var Finish_Mission; if(pushNextJob){ // DEBUG('Job Mastery of 100% detected, Reloading Tabno :'+tabno ); DEBUG('Job Mastery of 100% detected, Reloading nothing:' ); Finish_Mission = xpathFirst('.//a[contains(@id,"sm_action_button_'+Miss_ID+'") and contains(@class,"sexy_button_new medium black") and contains(@onclick,"SocialMissionView.closeTask(\''+Miss_ID+'")]', innerPageElt); if(Finish_Mission){ // DEBUG(' we found the finished marker, close button' ); clickElement(Finish_Mission); // if(!Check_Mission_Job()){ Go_Nxt_Page(); } // load stuff for next mission and try to start it // if there was nothing else on this page, try to go to the next page } else { DEBUG(' mission we did not find the finished close button' ); } Miss_ID = null; Autoplay.fx = GoMissionsTab; } else { if((!chk_stam()) || (!chk_nrg()) ){ DEBUG(' mission setting timer, you dont have enough to perform:'+ Miss_Name_is ); setmissiontimer(); Miss_ID = null; return false; } return; } Autoplay.start(); return true; break; case 'job': var masteryGainElt ; xpGainElt = xpathFirst('.//dd[@class="message_experience"]', messagebox); xpGainElt = xpGainElt ? xpGainElt : xpathFirst('.//dd[@class="experience"]', messagebox); var jobContainer = "job"+missions[GM_getValue('selectMission')][MISSION_NUMBER]; var jobContainerElt = xpathFirst('.//div[@id="'+jobContainer+'"]', rootElt); masteryGainElt = xpathFirst('.//div[@id="'+jobContainer+'"]//div[@class="mastery_bar"]', rootElt); jobName = missions[GM_getValue('selectMission')][MISSION_NAME]; var masteryGainTxt = ""; var pushNextJob = false; // IF we have the mastery gain bar, if(masteryGainElt){ if( (GM_getValue('selectTier','0.0')!= '0.0' )){ if( (parseInt(masteryGainElt.innerHTML.substr(0, masteryGainElt.innerHTML.indexOf('%'))) )==100 ){ masteryGainTxt = '. Job '+ masteryGainElt.innerHTML.substr(0, masteryGainElt.innerHTML.indexOf('%'))+'% Mastered'; pushNextJob = true; } } } if(xpGainElt){ jobOptimizeOn = false; var xpGainTxt = parseInt(xpGainElt.innerHTML); if(xpGainTxt){ var xpBonusElt = xpathFirst('.//div[@class="message_experience"]', messagebox); if(xpBonusElt) xpGainTxt+= '+'+ parseInt(xpBonusElt.innerHTML); xpGainTxt += " Experience"; } // Job completed successfully. result = 'You performed '+''+ jobName+' earning '+ xpGainTxt+''; var cashGainTxt=''; var cashGainElts = $x('.//dd[@class="message_cash"]', messagebox); for(i=0;i'; var cashSpendElt = xpathFirst('.//dt[@class="message_cash bad"]', messagebox); if(!cashSpendElt) cashSpendElt = xpathFirst('.//div[@class="job_uses"]//dd[contains(@class,"cash_icon")]', messagebox); if(cashSpendElt){ var cashSpendTxt = cashSpendElt.innerHTML.untag(); if(cashSpendTxt.match(/(.+?)\s+?Bribes/)) cashSpendTxt = RegExp.$1; result += ', spending '+ cities[city][CITY_CASH_SYMBOL] + cashSpendTxt+''; } if(masteryGainElt) result += masteryGainTxt; result += '.'; if(innerNoTags.indexOf('you spent no energy') != -1 || innerNoTags.indexOf('No energy cost') != -1 ||innerNoTags.indexOf('You Spent: 0') != -1 ) result += ' You spent no energy on this job.'; addToLog('process Icon', result); jobCombo(rootElt); if(masteryGainElt) jobLoot(jobContainerElt); // here else jobLoot(rootElt); // Add message if job tier prize found. if(innerNoTags.match(/.*(An* .+ was added to your inventory[^.]*.)/i)){ addToLog('lootbag Icon', RegExp.$1); } // Ask for help if auto ask is on and enough experience was gained. var xpGain = parseInt(xpGainElt.innerHTML); var parentClass=""; var xpGainMin = parseInt(GM_getValue('autoAskJobHelpMinExp')); if(isGMChecked('autoAskJobHelp') && (!xpGainMin || xpGain >= xpGainMin)){ // ask for help NY - depending on job results var elt = xpathFirst('.//div[@class="message_buttons"]//span[@class="sexy_jobhelp"]', messagebox); if(!elt) elt = xpathFirst('.//div[@class="message_buttons"]//a[@class="sexy_button_new short white sexy_call_new" and contains(.,"Let Friends Get a Bonus")]', messagebox); if(elt){ Autoplay.fx = function(){ clickElement(elt); addToLog('process Icon', 'Asked for help with '+ missions[GM_getValue('selectMission')][MISSION_NAME]+'.'); }; Autoplay.start(); return true; } } } else if(innerNoTags.indexOf('You are not high enough level to do this job') != -1){ addToLog('warning Icon', 'You are not high enough level to do '+ missions[GM_getValue('selectMission', 1)][MISSION_NAME]+'.'); addToLog('warning Icon', 'Job processing will stop'); GM_setValue('autoMission', 0); update_nrg_stam(); // update the icon to show energy spend is off } else if(innerNoTags.indexOf('Success') != -1){ jobOptimizeOn = false; addToLog('process Icon', inner); } else if(innerNoTags.indexOf('Missing') != -1){ if(getJobRowItems(jobName)){ DEBUG(' - - need items jobid='+jobid+' selectMission='+GM_getValue('selectMission', 1)); if(jobid != GM_getValue('selectMission', 1)) Autoplay.fx = autoMission; } } else { DEBUG('Unrecognized job response.'); } if(pushNextJob){ goJobsNav(); } else { return; } Autoplay.start(); return true; break; case 'hitman': // If the target is gone, there is nothing to do. if(innerNoTags.indexOf('someone else took out') != -1){ DEBUG(inner); return false; } var targetKilled = (innerNoTags.indexOf('You knocked out') != -1); if(innerNoTags.indexOf('You WON') != -1){ var cashGain = innerNoTags.match(/gained.*?([A-Z]*?\$|\u00A2)([\d,]*\d)/i); var cashWon = RegExp.$1+RegExp.$2; experience = innerNoTags.match(/\d+\s+experience\s+points?/i); addToLog('yeah Icon', 'Hit '+ linkToString(context.profile, 'user') + ', WON '+ cashWon+' and ' + ''+ experience+'.'); cashWon = parseCash(cashWon); GM_setValue('hitmanWinCountInt',GM_getValue('hitmanWinCountInt',0)+1); GM_setValue('hitmanWinDollarsInt', String(parseInt(GM_getValue('hitmanWinDollarsInt', 0)) + cashWon)); GM_setValue('totalExpInt', GM_getValue('totalExpInt', 0) + parseInt(experience)); GM_setValue('totalWinDollarsInt', String(parseInt(GM_getValue('totalWinDollarsInt', 0)) + cashWon)); GM_setValue('cashWinsNY', String(parseInt(GM_getValue('cashWinsNY', 0)) + cashWon)); if(!targetKilled && canSpendStamina() && ptsToNextLevel > 6){ var eltAtk; if(isGMChecked('staminaPowerattack') && ((isGMChecked('stopPA') && health >= GM_getValue('stopPAHealth')) || !isGMChecked('stopPA'))) eltAtk = xpathFirst('.//a[contains(.,"Power Attack")]', messagebox); if(!eltAtk) eltAtk = xpathFirst('.//a[contains(.,"Attack Again")]', messagebox); if(eltAtk){ // Attack again immediately. Autoplay.fx = function(){ clickAction = action; clickContext = context; clickElement(eltAtk); DEBUG('Clicked to repeat the hit on '+ clickContext.name+' ('+ clickContext.id+').'); }; if(!isGMChecked('noStats')){ updateLogStats(STAMINA_HOW_HITMAN); } Autoplay.delay = noDelay; Autoplay.start(); return true; } } } else if(innerNoTags.indexOf('You LOST') != -1){ var t = innerNoTags.match(/LOST.*?RegExp.$1/i); var cashLoss = RegExp.$1+RegExp.$2; result = 'Hit '+ linkToString(context.profile, 'user') + ' LOST '+ cashLoss+'.'; cashLoss = parseCash(cashLoss); GM_setValue('hitmanLossCountInt',GM_getValue('hitmanLossCountInt',0)+1); GM_setValue('hitmanLossDollarsInt', String(parseInt(GM_getValue('hitmanLossDollarsInt', 0)) + cashLoss)); GM_setValue('totalLossDollarsInt', String(parseInt(GM_getValue('totalLossDollarsInt', 0)) + cashLoss)); GM_setValue('fightLoss$NY', String(parseInt(GM_getValue('fightLoss$NY', 0)) + cashLoss)); if(context.id){ // Add the opponent to the avoid list. setHitmanOpponentAvoid(context.id); result += ' Avoiding.'; } addToLog('omg Icon', result); } else if(innerNoTags.indexOf('This player is currently part of your mafia') != -1){ if(context.id){ setHitmanOpponentAvoid(context.id); } } else { DEBUG(inner); } if(innerNoTags.indexOf('You were snuffed') != -1){ addToLog('updateBad Icon', 'You DIED.'); } if(targetKilled){ if(context.id){ addSavedListItem('hitmanListKilled', context.id, 100); } addToLog('killedMobster Icon', ' You KILLED ' + linkToString(context.profile, 'user') + ' and collected the ' + context.bounty+' bounty set by ' + linkToString(context.payer, 'user')+'.'); GM_setValue('hitmanWinCountInt',GM_getValue('hitmanWinCountInt',0)+1); GM_setValue('hitmanWinDollarsInt', String(parseInt(GM_getValue('hitmanWinDollarsInt', 0)) + parseCash(context.bounty))); GM_setValue('totalWinDollarsInt', String(parseInt(GM_getValue('totalWinDollarsInt', 0)) + parseCash(context.bounty))); GM_setValue('cashWinsNY', String(parseInt(GM_getValue('cashWinsNY', 0)) + parseCash(context.bounty))); } if(!isGMChecked('noStats')){ updateLogStats(STAMINA_HOW_HITMAN); } randomizeStamina(); break; case 'war': // Remove invalid war targets if(innerNoTags.indexOf('Target user is not a friend') != -1 || innerNoTags.indexOf('Target user does not exist') != -1){ removeSavedListItem('autoWarTargetList', context.target_id); addToLog('warning Icon', 'Invalid war target (id='+context.target_id+'). Removing from list.'); } // Friend is already at war with somebody else else if(innerNoTags.indexOf('is already at war with someone else') != -1){ addToLog('info Icon', inner.split('.')[0]+'. Cycling warlist. ' ); cycleSavedList('autoWarTargetList'); } // Go back to war page after betrayal else if(innerNoTags.indexOf('You successfully betrayed') != -1){ addToLog(logIcon, inner.split('

')[0]+''); break; } // Cycle war list after successful war declaration else if(innerNoTags.indexOf('You successfully declared war') != -1){ cycleSavedList('autoWarTargetList'); addToLog('yeah Icon', inner); } // War attack result else if(innerNoTags.indexOf('WON') != -1 || innerNoTags.indexOf('LOST') != -1){ var logIcon = innerNoTags.indexOf('LOST') != -1 ? 'omg Icon' : 'yeah Icon'; if(innerNoTags.indexOf('to winning this war.') != -1){ addToLog(logIcon, inner.split('to winning this war.')[0]+'to winning this war.'); } //else { addToLog(logIcon, inner); } } //else { addToLog('info Icon', inner); } if(helpWar){ // Help attempt was processed. Increment the update count. GM_setValue('logPlayerUpdatesCount', 1 + GM_getValue('logPlayerUpdatesCount', 0)); helpWar = false; } // Visit the War Tab again setGMTime('warTimer', '00:00'); Autoplay.start(); return true; break; case 'stats': if(innerNoTags.match(/You just upgraded your (\w+) by (\d+)/i)){ var statName = RegExp.$1; var statIndex = eval(statName.toUpperCase()+'_STAT'); var statIcon = statName.toLowerCase()+' Icon'; var statInc = isNaN(RegExp.$2) ? 1 : parseInt(RegExp.$2); GM_setValue('nextStat', (statIndex + 1) % 4); switch (statIndex){ case ATTACK_STAT : curAttack += statInc; break; case DEFENSE_STAT: curDefense += statInc; break; case HEALTH_STAT : maxHealth += statInc; break; case ENERGY_STAT : maxEnergy += statInc; break; case STAMINA_STAT: maxStamina += statInc; break; } addToLog(statIcon, ''+statName+' increased by '+statInc+' point(s).'); } else { DEBUG('Failed to increment stat.'); } break; case 'energypack': addToLog('energyPack Icon', 'Used an Energy Pack.'); energyPackElt = undefined; DEBUG('Unrecognized response for "energypack" action : '+inner); break; case 'help': var helpElt = xpathFirst('.//a[contains(.,"Help ")]', messagebox); // If help element is found, click it immediately if(helpElt){ Autoplay.fx = function(){ clickElement(helpElt); clickAction = 'help'; clickContext = context; }; Autoplay.delay = getAutoPlayDelay() Autoplay.start(); return true; } // Help attempt was processed. Increment the update count. GM_setValue('logPlayerUpdatesCount', 1 + GM_getValue('logPlayerUpdatesCount', 0)); var user = linkToString(xpathFirst('.//a[contains(@onclick,"xw_controller=stats&xw_action=view")]', messagebox), 'user'); if(context && !user){ user = context.user; } if(innerNoTags.indexOf('not your friend') != -1 || innerNoTags.indexOf('You need to be friends') != -1 || innerNoTags.indexOf('to help on a job.') != -1){ addToLog('info Icon', 'Failed to help'+ (user? ' '+ user : '')+'with job. Reason: not friends.'); } else if(innerNoTags.indexOf('You are too late') != -1){ addToLog('info Icon', 'You are too late to help '+ (user? ' '+ user : '')+' with this job.'); } else if(innerNoTags.indexOf('already helped') != -1){ addToLog('info Icon', 'Already helped '+ user+' with this job.'); } else if(innerNoTags.indexOf('You received') != -1 || innerNoTags.indexOf('You helped') != -1){ cost = innerNoTags.match(REGEX_CASH); experience = 0; if(innerNoTags.match(/(\d+)\s+experience\s+points?/i)){ experience = parseInt(RegExp.$1); } if(innerNoTags.indexOf('Special Bonus') != -1){ var loot = innerNoTags.split('gained a ')[1]; addToLog('lootbag Icon', 'Found a '+ loot.split('. while helping on a job.'); } result = 'You received '+''+ cost+''+' and '+''+ experience+' experience' + ' for helping '+ user+' complete the job.'; GM_setValue('passivetotalJobExpInt', parseInt(GM_getValue('passivetotalJobExpInt',0)) + experience); addToLog('updateGood Icon', result); if(!isGMChecked('noStats')){ updateLogStats(); } } else if(innerNoTags.indexOf('25 friends') != -1){ addToLog('info Icon', 'Failed to help'+ (user ? ' '+ user : '')+' with job. Reason: already helped 25 friends for the day in that city.'); } else { addToLog('info Icon', 'WARNING: Not sure what happened when trying to help'+ (user? ' '+ user : '')+'.'+ (context? ' '+ context.help : '')+' Perhaps you interfered by clicking on something?'); } Autoplay.start(); return true; break; case 'help burners': var helpElt = xpathFirst('.//a[contains(.,"Accept")]', messagebox); // If help element is found, click it immediately if(helpElt){ Autoplay.fx = function(){ clickElement(helpElt); clickAction = 'help burners'; clickContext = context; }; Autoplay.delay = getAutoPlayDelay() Autoplay.start(); return true; } // Help burners attempt was processed. Increment the update count. GM_setValue('logPlayerUpdatesCount', 1 + GM_getValue('logPlayerUpdatesCount', 0)); addToLog('info Icon', innerNoTags); Autoplay.start(); return true; break; case 'help parts': var helpElt = xpathFirst('.//a[contains(.,"Send Item")]', messagebox); // If help element is found, click it immediately if(helpElt){ Autoplay.fx = function(){ clickElement(helpElt); clickAction = 'help parts'; clickContext = context; }; Autoplay.delay = getAutoPlayDelay() Autoplay.start(); return true; } DEBUG('Parsing parts help.'); // Help parts attempt was processed. Increment the update count. GM_setValue('logPlayerUpdatesCount', 1 + GM_getValue('logPlayerUpdatesCount', 0)); if(innerNoTags.indexOf('You sent ') != -1){ addToLog('info Icon', 'You sent '+ inner.split('You sent ')[1].split('')[0]); } Autoplay.start(); return true; break; case 'deposit': // Log if city has changed after banking if(parseInt(city) != parseInt(context)){ addToLog('warning Icon', 'Warning! You have traveled from '+ cities[context][CITY_NAME]+' to '+ cities[city][CITY_NAME]+' while banking. Check your money.'); } if(innerNoTags.match(/deposited/i)){ addToLog(cities[city][CITY_CASH_CSS], inner); } else { DEBUG(inner); } // Close banking var bankElt = xpathFirst('//div[@id="bank_popup"]'); if(bankElt && bankElt.parentNode) closePopup(bankElt.parentNode, "Bank Popup"); break; case 'withdraw': if(innerNoTags.match(/withdrew/i)){ addToLog(cities[city][CITY_CASH_CSS], inner); } else { DEBUG(inner); } // Close banking var bankElt = xpathFirst('//div[@id="bank_popup"]'); if(bankElt && bankElt.parentNode) closePopup(bankElt.parentNode, "Bank Popup"); break; case 'buy item': addToLog('info Icon', inner.untag()); break; case 'buy brazil item': addToLog('info Icon', 'Brazil Items bought'); break; case 'buy property': addToLog('info Icon', inner); break; case 'crew collection': addToLog('info Icon', inner); break; case 'build item': var propCount = context.propCount; var buildProp = cityProperties[propCount][ctPropName]; var timerName = cityProperties[propCount][ctPropTimer]; if(/You cannot craft/i.test(inner) || /You do not have/i.test(inner) || /You need a higher/i.test(inner) ){ inner = buildProp+": " + inner; setGMTime(timerName, '1 hour'); addToLog('warning Icon', inner); } else { setGMTime(timerName, '18 hours'); if(inner.match(/You got (.+?)\./)){ var log = 'You built '+ RegExp.$1+'.'; if(inner.match(/You gained:(.+?) close/)) log += ' You gained '+ RegExp.$1+'.'; addToLog('lootbag Icon', log); } else { addToLog('lootbag Icon', inner); } } break; default: colorDEBUG('BUG DETECTED: Unrecognized action "'+ action+'".', cre); DEBUG('Unrecognized Action :'+inner); } return false; } function closePopup(eltPopup, coolName){ // This routine needs the handle of the popup! // Not a button in the popup, but the main element // So if we figure out we have a button, then let's try // to find the main element if(!eltPopup){ DEBUG('Can not close '+ coolName+' : popupElt undefined !'); return false; } // Once we see a post pop-up, set the timer to close it var closeElt = xpathFirst('.//a[@class="pop_close"]',eltPopup); if(!closeElt) closeElt = xpathFirst('.//a[@class="close"]',eltPopup); if(!closeElt) closeElt = xpathFirst('.//a[@class="sexy_button_new medium black skip" or contains(.,"Cancel")]',eltPopup); if(!closeElt) closeElt = xpathFirst('.//a[@class="mw_new_ajax pop_close"]',eltPopup); if(closeElt){ clickElement(closeElt); DEBUG('Got rid of '+ coolName+' popup: '+ eltPopup.id+ '.'); } var skipPostElt = document.getElementById('fb_dialog_cancel_button'); if(skipPostElt){ clickElement (skipPostElt); DEBUG('Skipped '+ coolName+' popup: '+ eltPopup.id+ '.'); } if(eltPopup.parentNode) eltPopup.parentNode.removeChild(eltPopup); return true; } // Handle various popups // This function is specifically for handling windows that popup // during gameplay and we want to either grab some info off the // window and log it, process it or we want to just close the window. function handlePopups(){ //Added handling to actually show popups var popupElts = $x('.//div[contains(@id, "pop_b") and not(contains(@style, "none"))]', popupfodderElt); if (popupElts && popupElts.length > 0) { for (var i = 0, iLength=popupElts.length; i < iLength; ++i) { var currentClass = popupElts[i].getAttribute('class'); if(currentClass.indexOf('pop_bg')==-1 && !popupElts[i].getAttribute('opened')){ popupElts[i].setAttribute('style', 'display: block;'); popupElts[i].setAttribute('opened', 'yes'); } else if (popupElts[i].getAttribute('opened')!='yes') { popupElts[i].setAttribute('style', 'display: none;'); } } } var popupElts = $x('.//div[@class="fight_true_popup"]//div[contains(@id, "pop_b")]', innerPageElt); if (popupElts && popupElts.length > 0) { for (var i = 0, iLength=popupElts.length; i < iLength; ++i) { var currentClass = popupElts[i].getAttribute('class'); if(currentClass.indexOf('pop_bg')==-1 && !popupElts[i].getAttribute('opened')){ popupElts[i].setAttribute('style', 'display: block;'); popupElts[i].setAttribute('opened', 'yes'); } else if (popupElts[i].getAttribute('opened')!='yes') { popupElts[i].setAttribute('style', 'display: none;'); } } } /* if(running){ var popupElts = $x('.//div[contains(@id, "pop_b") and contains(@style, "block")]', popupfodderElt); if (popupElts && popupElts.length > 0 && !onProfileNav()) { for (var i = 0, iLength=popupElts.length; i < iLength; ++i) { if (popupElts[i].scrollWidth && popupElts[i].innerHTML.length > 0) { pageChanged = true; justPlay = true; break; } } } var popupElts = $x('.//div[@class="fight_true_popup"]//div[contains(@id, "pop_b") and contains(@style, "block")]', innerPageElt); if (popupElts && popupElts.length > 0 && !onProfileNav()) { for (var i = 0, iLength=popupElts.length; i < iLength; ++i) { if (popupElts[i].scrollWidth && popupElts[i].innerHTML.length > 0) { pageChanged = true; justPlay = true; break; } } } } */ // Refresh the publishing options fetchPubOptions(); try { // Sent Requests Popup var requestPopContainer = xpathFirst('.//div[@id="requests_toaster" and contains(@style,"block")]'); if(requestPopContainer){ var requestPopText = xpathFirst('.//div[@id="requests_toaster_txt"]', requestPopContainer); if(requestPopText) addToLog('process Icon', requestPopText.innerHTML.untag()); var closeElt = xpathFirst('.//div[contains(@onclick,"fadeOut")]', requestPopContainer); clickElement(closeElt); return; } //Buy Prompt Popup var popupContainers = $x('.//div[@class="buy_prompt"]', appLayoutElt); if(running && popupContainers && popupContainers.length > 0){ // Process each popup that is open for (var i = 0, iLength=popupContainers.length; i < iLength; ++i){ if(popupContainers[i] && popupContainers[i].scrollWidth && popupContainers[i].innerHTML.length > 0){ var currentPopup = popupContainers[i]; return(closePopup(currentPopup, "Buy Prompt Popup")); } } } // Battle Pop var battlePopContainer = xpathFirst('.//div[@id="role_select_bg"]',appLayoutElt) if(running && battlePopContainer){ DEBUG('Found Battle Popup'); var popParent = battlePopContainer.parentNode.parentNode; elt = xpathFirst('.//a[@class="rightArrow" and contains(.,"FIGHT")]', battlePopContainer); if(elt){ clickElement(elt); } return(closePopup(popParent, "Battle Popup")); } // Look for Operations popups that are showing var popupContainers = $x('.//div[contains(@id,"socialMissionFail") and @class="socialMissionTryAgain" and contains(@style,"block")]', appLayoutElt); if(running && popupContainers && popupContainers.length > 0){ // Process each popup that is open for (var i = 0, iLength=popupContainers.length; i < iLength; ++i){ if(popupContainers[i] && popupContainers[i].scrollWidth && popupContainers[i].innerHTML.length > 0){ var currentPopup = popupContainers[i]; var processElt; if(isGMChecked('AutoRetryOperations')){ processElt = xpathFirst('.//a[contains(@onclick,"tryAgain") and contains(.,"Start")]',currentPopup); DEBUG('Clicking to retry expired operation'); } else { processElt = xpathFirst('.//a[contains(@onclick,"tryAgain") and contains(.,"Close")]',currentPopup); DEBUG('Clicking to close expired operation'); } if(processElt) clickElement(processElt); return true; } } } // Look for Achievements popups that are showing var popupContainers = $x('.//div[contains(@id,"zy_popup_box") and not(@class="zy_popup_box_bg") and contains(@style,"block")]', appLayoutElt); if(running && popupContainers && popupContainers.length > 0){ // Process each popup that is open for (var i = 0, iLength=popupContainers.length; i < iLength; ++i){ if(popupContainers[i] && popupContainers[i].scrollWidth && popupContainers[i].innerHTML.length > 0){ var currentPopup = popupContainers[i]; var processElt; processElt = xpathFirst('.//div[@class="achievement_message_text"]',currentPopup); if(processElt){ var processTxt = processElt.innerHTML.untag(); if(processTxt.match(/you earned(.+)share/i)){ addToLog('yeah Icon','You earned '+RegExp.$1+'.'); } if(isGMChecked('autoGlobalPublishing')){ processElt = xpathFirst('.//a[contains(@class,"sexy_achievement_new") and contains(.,"Share the wealth")]',currentPopup); if(processElt){ clickElement(processElt); DEBUG('Clicked to share Achievement Bonus'); } } } return(closePopup(currentPopup, "Achievement Popup")); } } } // Look for all other popups that are showing var popupElts = $x('.//div[(contains(@id,"pop_box") and contains(@style, "block")) or contains(@id,"mystery")]', appLayoutElt); if(popupElts && popupElts.length > 0){ // Process each popup that is open for (var i = 0, iLength=popupElts.length; i < iLength; ++i){ if(popupElts[i] && popupElts[i].scrollWidth && popupElts[i].innerHTML.length > 0){ var currentPopup = popupElts[i]; var popupInner = currentPopup.innerHTML; var popupInnerNoTags = popupInner.untag().toLowerCase(); if( popupInner.indexOf('fight_wrapper') != -1 // Don't Close Fight Popup || popupInner.indexOf('bank_popup') != -1 // The Bank || popupInner.indexOf('vault_popup') != -1 // Las Vegas Vault //|| popupInner.indexOf('mw_app=slotmachine') != -1 // Slot Machine ){ continue; } // Skip these popups! if( popupInner.indexOf('id="marketplace"') != -1 // The Marketplace || popupInner.indexOf('id="original_buyframe_popup"') != -1 // The Marketplace || popupInner.indexOf('marketplace_title.png') != -1 // The Marketplace || popupInner.indexOf('giftcard_iframe') != -1 // The Marketplace || popupInner.indexOf('newbuyer_congrats') != -1 // The Marketplace || popupInner.indexOf('xw_controller=hospital') != -1 // The Hospital || popupInner.indexOf('Build Complete') != -1 // Chop Shop/Weapon Depot success popup || popupInner.indexOf('id="ChopShopCarousel"') != -1 // Chop Shop/Weapon Depot craft popup //|| popupInner.indexOf('mw_app=slotmachine') != -1 // Slot Machine || popupInner.indexOf('id="map_boss_fight"') != -1 // Vegas Boss fights || popupInner.indexOf('id="pop_box_map_boss_fight_popup"') != -1 // Boss fights || popupInner.indexOf('class="account_settings_title"') != -1 // Account Settings || popupInner.indexOf('class="exp_discount_main"') != -1 // Item Sales || popupInner.indexOf('TournamentController.nextPage()') != -1 // Tournament Ready to fight popup || popupInner.indexOf('this wave has ended') != -1 // kill zombie fight ended // Various Warning Popups || popupInnerNoTags.indexOf('wishlist is full') != -1 || popupInnerNoTags.indexOf('cooldown') != -1 ){ if(running) return(closePopup(currentPopup, "Annoying Zollipops stuff")); continue; } if(isGMChecked('TestChanges')) DEBUG('Popup Found: '+ popupElts[i].id + ' - '+ popupInnerNoTags); // shows popup_fodder_zmc constantly /* THESE POPUPS get processed only when PS MWAP is running: */ /* START */ if(running){ /* THESE POPUPS get always processed: */ // Close Free Gift Selector if timer goes off if(popupInnerNoTags.indexOf('close_suggestor_iframe') !=-1){ if(!timeLeftGM('requestTimer')) return(closePopup(currentPopup, "Free Gift Suggestor")); return; } // Slot Machine!?! if(popupInner.indexOf('mw_app=slotmachine') != -1){ var flashvars = xpathFirst('//object[@id="slots"]/param[@name="flashvars"]'); if(flashvars && flashvars.value){ slotSpins = flashvars.value.match(/&freeSpins=(\d+)&/)[1]; slotBonus = flashvars.value.match(/&bonusMeter=(\d+)&/)[1]; addToLog('info Icon', 'Slot Spins Remaining: ' + slotSpins+' Bonus Level: '+ slotBonus); } return(closePopup(currentPopup, "Slot Machine Popup")); } // Accept Gifts from MESSAGE CENTER / Total Requests popup if(popupInnerNoTags.indexOf('total requests') != -1){ var acceptgiftButtons = $x('.//a[@class="sexy_button_new medium white" and contains(@onclick,"accept_gift") and not(contains(@onclick,"item_id=3009")) ]',currentPopup); if(acceptgiftButtons && isGMChecked('autoAcceptMsgGifts')){ for(i=0;i0;++i){ acceptgiftButton = acceptgiftButtons[i]; clickElement(acceptgiftButton); } DEBUG('Popup Process: MESSAGE CENTER - '+acceptgiftButtons.length+' Gifts Accepted'); } // Accept Boosts from MESSAGE CENTER / Total Requests popup acceptgiftButtons = $x('.//a[@class="sexy_button_new medium white" and contains(@onclick,"accept_boost")]',currentPopup); if(acceptgiftButtons && isGMChecked('autoAcceptMsgBoosts')){ for(i=0;i0;++i){ acceptgiftButton = acceptgiftButtons[i]; clickElement(acceptgiftButton); } DEBUG('Popup Process: MESSAGE CENTER - '+acceptgiftButtons.length+' Boosts Accepted'); } // Accept War Requests MESSAGE CENTER / Total Requests popup if(isGMChecked('AutoBattle')){ var acceptButtons = $x('.//a[@class="sexy_button_new medium white" and contains(@onclick,"xw_action=createBattle") and contains(@onclick,"opponent_id='+GM_getValue('AutoBattleClanID')+'")]',currentPopup); if(acceptButtons){ for(i=0;i0;++i){ acceptButton = acceptButtons[i]; clickElement(acceptButton); } DEBUG('Popup Process: MESSAGE CENTER - Accepted '+acceptButtons.length+' battles.'); } } // Accept Mafia Invites from MESSAGE CENTER / Total Requests popup var acceptButtons = $x('.//a[@class="sexy_button_new medium white" and contains(.,"Join Mafia")]',currentPopup); if(acceptButtons && isGMChecked('acceptMafiaInvitations')){ for(i=0;i0;++i){ acceptButton = acceptButtons[i]; clickElement(acceptButton); } DEBUG('Popup Process: MESSAGE CENTER - Added '+acceptButtons.length+' members to your mafia.'); } // Accept Crew Invites from MESSAGE CENTER / Total Requests popup var acceptButtons = $x('.//a[@class="sexy_button_new medium white" and contains(.,"Accept Crew")]',currentPopup); if(acceptButtons && isGMChecked('autoAcceptMsgCrew')){ for(i=0;i0;++i){ acceptButton = acceptButtons[i]; clickElement(acceptButton); } DEBUG('Popup Process: MESSAGE CENTER - Accepted '+acceptButtons.length+' Crew Invites to your mafia.'); } // Send Eneryg Packs to your Mafia from MESSAGE CENTER / Total Requests popup var acceptButtons = $x('.//a[@class="sexy_button_new medium white" and (contains(.,"Send Energy") or contains(@onclick,"xw_action=accept_energy_req"))]',currentPopup); if(acceptButtons && isGMChecked('autosendMsgEnergyPack')){ for(i=0;i0;++i){ acceptButton = acceptButtons[i]; clickElement(acceptButton); } DEBUG('Popup Process: MESSAGE CENTER - Sent '+acceptButtons.length+' energy Packs to your mafia.'); } return(closePopup(currentPopup, "MESSAGE CENTER")); } // Process Red Mystery Bag popup if(popupInnerNoTags.indexOf('opened a red mystery bag') != -1){ DEBUG('Popup Process: Red Mystery Bag Processed'); var bagTxt; if(popupInnerNoTags.match(/you got:(.+?)(send|share)/i)) bagTxt = RegExp.$1; addToLog('lootbag Icon', 'Received '+ bagTxt+' from a red mystery bag.'); return(closePopup(currentPopup, "Red Mystery Bag Drop")); } // Process Mystery Bag popup if(popupInnerNoTags.indexOf('share mystery bonus') != -1){ DEBUG('Popup Process: Mystery Bag Processed'); var bagTxt; if(popupInnerNoTags.match(/you got:(.+?)(send|share)/i)) bagTxt = RegExp.$1; addToLog('lootbag Icon', 'Received '+ bagTxt+' from a mystery bag.'); return(closePopup(currentPopup, "Mystery Bag Drop")); } // Process Battle Rewards Collect popup if(popupInner.indexOf('BattleResultsController')!=-1){ DEBUG('Found BattleRewards Popup'); elt = xpathFirst('.//a[contains(@onclick,"BattleResultsController.collectReward") and contains(.,"Collect")]', currentPopup); if(elt){ DEBUG('Found collect link to click, boom!'); clickElement(elt); } else { DEBUG('No collect link found :('); } return(closePopup(currentPopup, "Battle Collect Popup")); } // Process Robbery Loot popup if(popupInnerNoTags.indexOf('you cleared the full board') != -1){ var totalCash=0; var totalXP = 0; var totalNRG = 0; var totalSTAM = 0; // get robbing results var robResults = $x('.//div[@class="rob_res_expanded_details"]'); var robResultTxt=''; if(robResults && robResults.length>0){ for(i=0,iLength=robResults.length;i'; if(totalXP) robResultTxt+=' and '+totalXP+' experience'; if(totalNRG) robResultTxt+=' and '+totalNRG+' energy'; if(totalSTAM) robResultTxt+=' and '+totalSTAM+' stamina'; robResultTxt='You Gained '+robResultTxt+'.'; } // Look for any loot on popup DEBUG('Popup Process: Processing robbing board'); if(popupInnerNoTags.match(/(\d+) bonus experience/i)){ var exp = RegExp.$1.replace(/[^0-9]/g, ''); var boardrecord =""; var boardExp = parseInt(boardLastPtsToNextLevel) - parseInt(ptsToNextLevel); var boardStam = parseInt(boardLastStamina) - parseInt(stamina); var boardRatio = parseFloat(boardExp / boardStam).toFixed(2); if(popupInner.match(/your record on this board was\s+(.+?)\./i)) boardrecord = '
Board Record: '+ RegExp.$1+''; addToLog('yeah Icon', 'Robbing board cleared. '+robResultTxt+' Bonus: '+ exp+' experience.'+ boardrecord+' - Ratio: '+ boardExp+'/'+ boardStam + ' ('+ boardRatio +') '); boardLastStamina = parseInt(stamina); boardLastPtsToNextLevel = parseInt(ptsToNextLevel); //DEBUG('doRob Getting start values: '+boardLastStamina+'-'+boardLastPtsToNextLevel); if(!isGMChecked('fastRob') || !isGMChecked('noStats')){ updateRobStatistics(null,parseInt(exp)); updateLogStats(); } if(popupInner.match(/you\s+(earned|gained|received|collected)\s+(some|an?)\s+bonus\s+(.+?)\.?<\/div>/i)){ addToLog('lootbag Icon', 'Found '+ RegExp.$3+' on robbing board.'); } } return(closePopup(currentPopup, "Robbing Board Popup")); } // Level Up popups // Process Level Up Skill Points var upgradePointsElt = xpathFirst('.//span[@id="level_up_skill"]',currentPopup); if(upgradePointsElt){ if(isGMChecked('autoStat')){ var upgradePoints=0; upgradePoints = parseInt(upgradePointsElt.innerHTML); var autoStatValues = autoStatVars(); if(upgradePoints && autoStatValues[0]!='' && autoStatValues[1]!=0){ var StatUpgrdUrl = 'remote/html_server.php?xw_controller=stats&xw_action=upgrade&upgrade_key='+autoStatValues[0]+'&upgrade_amt='+autoStatValues[1]+'&no_load=1&source=level_up_popup'; var ajaxID = createAjaxPage(true); var elt = makeElement('a', null, {'onclick':'return do_ajax("'+ ajaxID+'","'+StatUpgrdUrl+'", 1, 0, null, update_level_up_skill); return false;' } ); if(elt){ var statName = autoStatValues[0].replace('max_',''); var statIndex = eval(statName.toUpperCase()+'_STAT'); var statIcon = statName.toLowerCase()+' Icon'; var statInc = isNaN(autoStatValues[1]) ? 1 : parseInt(autoStatValues[1]); GM_setValue('nextStat' , (statIndex + 1) % 4); switch (statIndex){ case ATTACK_STAT: curAttack += statInc; break; case DEFENSE_STAT: curDefense += statInc; break; case HEALTH_STAT: maxHealth += statInc; break; case ENERGY_STAT: maxEnergy += statInc; break; case STAMINA_STAT: maxStamina += statInc; break; } addToLog(statIcon, ''+statName+' increased by '+statInc+' point(s).'); clickAction = 'autoStatAllocation'; clickElement(elt); return; } } var StatUpgrdUrl = 'remote/html_server.php?xw_controller=levelUpBonus&xw_action=addBonusItem&xw_city='+city+'&no_load=1'; var ajaxID = createAjaxPage(true); var elt = makeElement('a', null, {'onclick':'return do_ajax("'+ ajaxID+'","'+StatUpgrdUrl+'", 1, 0, null, update_level_up_bonus_item); return false;' } ); if(elt && claimLevelUpBonus){ DEBUG('Claiming Skill Points Allocation Reward'); clickAction = 'autoStatReward'; clickElement(elt); claimLevelUpBonus = false; return; } } else { DEBUG('Skill Poinst Allocation OFF'); } } // Click to share bonus if(popupInnerNoTags.match(/(you are now level|promoted to level) (\d+)/i)){ addToLog('info Icon','You were promoted to level '+ RegExp.$2 +''); if(document.getElementById('bonusItemName')){ var bonusItemName = document.getElementById('bonusItemName'); addToLog('lootbag Icon','Level Up Bonus Item: '+ bonusItemName.innerHTML +''); } if(isGMChecked('autoLevelPublish')){ var eltPubButton = xpathFirst('.//a[contains(@onclick,"postLevelUpFeedAndSend") and contains(.,"Share")]',currentPopup); if(!eltPubButton) eltPubButton = xpathFirst('.//a[contains(@onclick,"xw_action=levelup_boost_brag") and contains(.,"Share")]',currentPopup); if(!eltPubButton) eltPubButton = xpathFirst('.//div[@id="bonusShareButton"]//a[contains(.,"Share")]',currentPopup); if(eltPubButton){ DEBUG('Level Up popup Share button detected'); clickElement(eltPubButton); } } claimLevelUpBonus = true; return(closePopup(currentPopup, "Level Up Bonus")); } // Post to friends var postFriendsElts = $x('.//a[contains(@onclick,"postFeedAndSendSocialList") and contains(.,"Post")]',currentPopup); if(postFriendsElts && postFriendsElts.length>0){ return(closePopup(currentPopup, "Level Up Bonus Sharing")); } // Operations / Missions popups // Get rid of not in Operations popup if(popupInnerNoTags.indexOf('not involved in this mission') != -1){ return(closePopup(currentPopup, "Not in Operation")); } // Start a New Operation if(popupInnerNoTags.indexOf('start operation') != -1){ var missionButton = xpathFirst('.//a[@class="sexy_button_new medium white" and contains(@onclick,"postCelebrateFeed")]',currentPopup); if(!missionButton) missionButton = xpathFirst('.//a[@class="sexy_button_new medium white" and contains(@onclick,"startMission")]',currentPopup); if(missionButton && isGMChecked('AutoMafiaMission')){ clickElement(missionButton); DEBUG('Popup Process: OPERATIONS - Started a new Operation'); } return(closePopup(currentPopup, "Start New Operation")); } // Invite Friends on Operation Start if(popupInnerNoTags.indexOf('invite friends') != -1){ var missionButton = xpathFirst('.//a[@class="sexy_button_new medium white" and contains(@onclick,"postCelebrateFeed")]',currentPopup); if(missionButton){ if(isGMChecked('AutoMafiaMission')){ clickElement(missionButton); DEBUG('Popup Process: OPERATIONS - Started My own Operation'); } } return(closePopup(currentPopup, "Inviting Friends on Operation Start")); } // Claim Operation Rewards Failed if(popupInnerNoTags.indexOf('failed to give reward') != -1){ DEBUG('Popup Process: OPERATIONS - Claim Rewards Failed'); return(closePopup(currentPopup, "Claim Operations Rewards Failed")); } // Log Operation Rewards if(popupInnerNoTags.indexOf('completed the operation') != -1){ DEBUG('Popup Process: OPERATIONS - Claim Rewards : '+currentPopup.id); var rewards = $x('.//td[@class="collectPopLootItem"]', currentPopup); var rewardsTxt =""; var rewardsNoTags =""; for(i=0;i (A: '+RegExp.$2+' / D: '+ RegExp.$3+')'; else if(rewardsNoTags.match(/(.+?)(\d{2})(\d{1})$/)) rewardsNoTags = ''+RegExp.$1+ ' (A: '+RegExp.$2+' / D: '+ RegExp.$3+')'; else if(rewardsNoTags.match(/(.+?)(\d{1})(\d{2})$/)) rewardsNoTags = ''+RegExp.$1+ '(A: '+RegExp.$2+' / D: '+ RegExp.$3+')'; else if(rewardsNoTags.match(/(.+?)(\d{1})(\d{1})$/)) rewardsNoTags = ''+RegExp.$1+ '(A: '+RegExp.$2+' / D: '+ RegExp.$3+')'; if(rewardsTxt) rewardsTxt += ', '+ rewardsNoTags; else rewardsTxt = rewardsNoTags; } addToLog('lootbag Icon', 'Operation Rewards : '+rewardsTxt); if(!isGMChecked('autoShareRewards')) return(closePopup(currentPopup, "Operations Rewards claimed")); } // Share Operation Rewards var shareButton = xpathFirst('.//a[@class="sexy_button_new medium white sexy_call_new" and contains(@onclick,"postCelebrateFeed")]',currentPopup); if(shareButton){ if(isGMChecked('autoShareRewards')){ clickElement(shareButton); DEBUG('Popup Process: OPERATIONS - Share Rewards'); } return(closePopup(currentPopup, "Share Operations Rewards")); } // War Popups // Get rid of War Fight Won - Succesfull War Attack popup if(popupInnerNoTags.indexOf('won the fight') != -1){ return(closePopup(currentPopup, "Succesfull War Attack")); } // Get rid of War Fight Lost - Succesfull War Attack popup if(popupInnerNoTags.indexOf('lost the fight') != -1){ return(closePopup(currentPopup, "Succesfull War Attack")); } // Get rid of War already helped popup if(popupInnerNoTags.indexOf('have already helped') != -1){ return(closePopup(currentPopup, "Already Helped")); } // Get rid of War is already over popup if(popupInnerNoTags.indexOf('war is already over') != -1){ return(closePopup(currentPopup, "War already over")); } // Get rid of War Not in Mafia popup if(popupInnerNoTags.indexOf('a mafia request') != -1){ return(closePopup(currentPopup, "War Not in Mafia")); } // War Declaration var warDeclareButton = xpathFirst('.//a[@class="sexy_button_new short white sexy_call_new" and contains(@onclick,"attemptFeed")]',currentPopup); if(warDeclareButton){ if(isGMChecked('autoWarPublish')){ clickElement(warDeclareButton); DEBUG('Popup Process: WAR - Declare War Publishing'); } return(closePopup(currentPopup, "War Declaration Popup")); } // War Rally for Help if(popupInnerNoTags.indexOf('help to take out all 7') != -1){ eltHelp = xpathFirst('.//a[contains(.,"Ask Friends for Help")]', currentPopup); if(eltHelp && isGMChecked('autoWarResponsePublish')){ clickElement(eltHelp); DEBUG('Popup Process: WAR - Ask Friends for Help Publishing'); } return(closePopup(currentPopup, "War Help Popup")); } // War Reward : Share Victory Coins if(popupInnerNoTags.indexOf('share victory coins') != -1){ var warRewardButtons = $x('.//a[@class="sexy_button_new short white" and contains(@onclick,"postWarWin")]',currentPopup); if(warRewardButtons && isGMChecked('autoWarRewardPublish')){ for(i=0;i0;++i){ warRewardButton = warRewardButtons[i]; clickElement(warRewardButton); DEBUG('Popup Process: WAR - Reward Friends (Share Coins) for Help Publishing'); } } return(closePopup(currentPopup, "War Reward (Share Coins) Popup")); } // Miscelaneous // Themed Events eltHelp = xpathFirst('.//a[contains(@class,"sexy_button_new") and contains(.,"Share")]', currentPopup); if(eltHelp && isGMChecked('autoGlobalPublishing')){ clickElement(eltHelp); DEBUG('Popup Process: Shared Themed Event Items - '+popupInnerNoTags); DEBUG('Popup Process: Button: '+eltHelp.innerHTML); return(closePopup(currentPopup, "Shared Themed Event Items")); } // Loot Events if(popupInnerNoTags.match(/you found (.*) loot event./i) || popupInnerNoTags.match(/you found all (.*) in action./)){ if(popupInnerNoTags.match(/you found (.*) loot event./i)){ logtxt = 'You found '+ RegExp.$1+' loot event.'; } else if(popupInnerNoTags.match(/you found all (.*) in action./)){ logtxt = 'You found '+ RegExp.$1+' in action.'; } if(logtxt) addToLog('yeah Icon',logtxt); return(closePopup(currentPopup, "Loot Event")); } // Brazil City Crew //Send city crew requests if(( isGMChecked('autoAskCityCrew') || isGMChecked('autoAskChicagoCrew') )&& popupInnerNoTags.indexOf('send city crew requests') != -1){ colorDEBUG('City Crew Requests Popup Detected'); var crewMembers = $x('.//div[@class="mfs_selectable"]//li[@class="mfs_add" and not(contains(@style,"none"))]',currentPopup); if(crewMembers && crewMembers.length>0){ var iLength = (crewMembers.length>50) ? 50 : crewMembers.length; for(i=0;i'+popupInnerNoTags); clickElement(eltButton); } else { DEBUG('Could not process the following popup :
'+popupInnerNoTags); } return(closePopup(currentPopup, "autoClosing (autoProcess) Unknown")); } // End of Popups Section } /* END */ } } } } catch (ex){ DEBUG('Error @handlePopups: '+ ex); } return false; } function updateScript(){ try { GM_xmlhttpRequest({ method: 'GET', url: SCRIPT.metadata+'?'+ Math.random(), onload: function(resp){ if(resp.status != 200) return; if(!resp.responseText.match(/@version\s+(\d+).(\d+).(\d+)/)) return; var googleVersion = RegExp.$1+'.'+RegExp.$2+'.'+RegExp.$3; var runningVersion = SCRIPT.version; if(googleVersion != runningVersion){ if(window.confirm('Version '+ googleVersion+' is available!\n\n'+'Do you want to install this version?'+'\n')){ window.location.href = SCRIPT.url; } } else { alert('You already have the latest version: '+ googleVersion); return; } } }); } catch (ex){ DEBUG('BUG DETECTED (updateScript): '+ ex); } } /////////////////////////////////////////////////////////////////////////////// // UTILITY METHODS // /////////////////////////////////////////////////////////////////////////////// /******************************** General ********************************/ function clearSettings(){ if(typeof GM_listValues == 'function' && typeof GM_deleteValue == 'function'){ var values = GM_listValues(); for (var i in values){ if(typeof GM_deleteValue == 'function') GM_deleteValue(values[i]); } } else { alert('In order to do this you need at least GreaseMonkey version: 0.8.20090123.1. Please upgrade and try again.'); } } /******************************** Array ********************************/ function getArrayDiffs(workingArray){ diffArray = []; for (var i = 1; i < workingArray.length; i++){ if(workingArray[i] - workingArray[i-1] < 0){ diffArray.push(0) } else { diffArray.push(workingArray[i] - workingArray[i-1]); } } diffArray.unshift(0); return diffArray; } // Save an array of strings. The strings must not contain "\n". function setSavedList(listName, list){ GM_setValue(listName, list.join('\n')); } // Get an array of strings that was saved with setSavedList(). function getSavedList(listName){ var savedList = GM_getValue(listName, ''); return savedList? savedList.split('\n') : []; } // Add an item to a list saved with setSavedList(). // If the size of the list is greater than the "max" // parameter, the first item in the list is removed. function addSavedListItem(listName, item, max){ var savedList = getSavedList(listName); // Only add if it isn't already there. if(savedList.indexOf(item) != -1){ return; } savedList.push(item); if(max > 0){ while (max < savedList.length){ var itm = savedList.shift(); DEBUG('Removing '+ itm+' from '+ listName+'.'); } } setSavedList(listName, savedList); } // Remove an item from a list saved with setSavedList(). function removeSavedListItem(listName, item){ var savedList = getSavedList(listName); var idx = savedList.indexOf(item); if(idx != -1){ savedList.splice(idx, 1); setSavedList(listName, savedList); return true; } // No matches. return false; } function removeJobForItem(jobList, itemName){ var jobs = getSavedList(jobList, ''); var i=0; if(jobs.length>0){ var job=jobs[jobs.length-1]; requirementJob.forEach( function(j){ if(j[1] == job){ if(requirementJob[i][0]==itemName){ removeSavedListItem(jobList,requirementJob[i][1]); DEBUG('removing job'+requirementJob[i][1]); } } i++; } ); } } function cycleSavedList(listName){ // Move the first item to the end of the list. var opponents = GM_getValue(listName, '').split('\n'); var first = opponents.shift(); if(first){ opponents.push(first); } GM_setValue(listName, opponents.join('\n')); } /******************************** HTML/DOM ********************************/ function stripURI(img){ img = img.split('"')[1]; return img.replace('" />', ''); } function showIfUnchecked(setting){ if(setting != 'checked'){ setting = 'unchecked'; } return setting; } function showIfSelected(setting){ if(setting == 'checked'){ return 'selected'; } else { return 'not selected'; } } function showIfRelative(key){ return GM_getValue(key) == 'checked'? 'relative' : 'absolute'; } // Converts a link element to an HTML string with an optional CSS class. function linkToString(link, className){ if(!link) return link; // Decode ID var decBase64ID = function (strInput){ if(strInput.match(/user=/)){ var id = strInput.split('user=')[1].split('\'')[0].split('&')[0]; strInput = strInput.replace (id, decodeID(id)); } return strInput; }; var str = ''+ link.innerHTML+''; return str; } function decodeHTMLEntities(str){ if(!str) return str; scratchpad.innerHTML = str; return scratchpad.value; } // Hide the element function hideElement(elt, hideFlag){ if(!elt) return; if(hideFlag == null) hideFlag = true; elt.setAttribute("id", hideFlag ? "mwapHide" : "", 0); return elt; } function clickElement(elt){ if(!elt){ colorDEBUG('BUG DETECTED: Null element passed to clickElement().', cre); return; } if(gvar.isGreaseMonkey){ try{ $(elt).click(); } catch (clickError){ //colorDEBUG('JQuery Component unavailable :'+clickError); // Simulate a mouse click on the element. var evt = document.createEvent('MouseEvents'); evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); elt.dispatchEvent(evt); } } else { var evt = document.createEvent('MouseEvents'); evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); elt.dispatchEvent(evt); } } function ignoreElement(element){ var parentElt = element.parentNode; var id; if(parentElt){ id = parentElt.id; if(id && (id.indexOf('countdown') != -1 || id.indexOf('timer') != -1 || id.indexOf('ask_for_job_help_time') != -1 || id.indexOf('tournament_time_left') != -1 || id.indexOf('tournament_try_again_timer') != -1 || id.indexOf('zmc_event_count') != -1 || id.indexOf('googleAds') != -1 || id.indexOf(' ps_mwap_promo_banner') != -1 )) return true; } id = element.id; if(id && (id.indexOf('countdown') != -1 || id.indexOf('timer') != -1 || id.indexOf('ask_for_job_help_time') != -1 || id.indexOf('tournament_time_left') != -1 || id.indexOf('tournament_try_again_timer') != -1 || id.indexOf('zmc_event_count') != -1 || id.indexOf('googleAds') != -1 || id.indexOf(' ps_mwap_promo_banner') != -1 )) return true; return false; } function xpathFirst(p, c){ return document.evaluate(p, c || document, null, XPathResult.ANY_UNORDERED_NODE_TYPE, null).singleNodeValue; } function $x(p, c){ var i, r = [], x = document.evaluate(p, c || document, null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null); while ((i = x.iterateNext())) r.push(i); return r; } function xpath(query, element){ var elt = (element == null) ? document : element; return document.evaluate(query, elt, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); } // Toggle checkbox element and return true if it is checked function toggleCheckElt(eltId){ if(isGMChecked(eltId)){ GM_setValue(eltId, 0); return false; } else { GM_setValue(eltId, 'checked'); return true; } } // Default an array of checkbox elements function defaultCheckBoxElementArray(arrayEltIds, value){ for (var i=0; i= 60){ strTime = parseInt(num/60)+'h '; num -= parseInt(num); num *= 60; } strTime += parseInt(num)+'m '; num -= parseInt(num); num *= 60; strTime += parseInt(num)+'s'; } return strTime.replace('00','0'); } function secondsToHMS(d){ d = Number(d); var h = Math.floor(d / 3600); var m = Math.floor(d % 3600 / 60); var s = Math.floor(d % 3600 % 60); return ((h > 0 ? h + ":" : "") + (m > 0 ? (h > 0 && m < 10 ? "0" : "") + m + ":" : "0:") + (s < 10 ? "0" : "") + s); } // Convert seconds to ?h ?m ?s format function getHoursTime(timer){ var seconds = timeLeftGM(timer); if(seconds == 0) return 0; if(isNaN(seconds)) return undefined; var num = parseInt(seconds); var strTime = ''; if(num){ num /= 60; if(num >= 60){ num /= 60; strTime = parseInt(num)+'h '; num -= parseInt(num); num *= 60; } strTime += parseInt(num)+'m '; num -= parseInt(num); num *= 60; strTime += parseInt(num)+'s'; } return strTime; } /******************************** Base64 Logic ********************************/ function IsJsonString(str){ try { JSON.parse(str);} catch (e){ return false; } return true; } function decodeID (strID){ // Unescape and clean up the ID first (for %3D string, non-base 64 strings etc) strID = unescape (strID); if(isNaN(strID)){ strID = decode64(strID); } return strID; } // Function to decode strings from Base64 function decode64(input){ var output = ""; var chr1, chr2, chr3 = ""; var enc1, enc2, enc3, enc4 = ""; var i = 0; // remove all characters that are not A-Z, a-z, 0-9, +, /, or = var base64test = /[^A-Za-z0-9\+\/\=]/g; if(base64test.exec(input)){ DEBUG('Invalid character(s) found in input ('+ input +'). Expect errors in decoding.'); } input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); do { enc1 = keyStr.indexOf(input.charAt(i++)); enc2 = keyStr.indexOf(input.charAt(i++)); enc3 = keyStr.indexOf(input.charAt(i++)); enc4 = keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if(enc3 != 64){ output = output + String.fromCharCode(chr2); } if(enc4 != 64){ output = output + String.fromCharCode(chr3); } chr1 = chr2 = chr3 = ""; enc1 = enc2 = enc3 = enc4 = ""; } while (i < input.length); return output; } function encode64(input){ var output = ""; var chr1, chr2, chr3 = ""; var enc1, enc2, enc3, enc4 = ""; var i = 0; do { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if(isNaN(chr2)){ enc3 = enc4 = 64; } else if(isNaN(chr3)){ enc4 = 64; } output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4); chr1 = chr2 = chr3 = ""; enc1 = enc2 = enc3 = enc4 = ""; } while (i < input.length); return output; } //////////////////////////////////////////////////////////////////////////////////////////////////////// function Auto_Mafia_Mission(){ Autoplay.delay = getAutoPlayDelay(); //missionsDelays = 5000 ; // 6k = 6 seconds use this to override delay values // Go to the missions tab var Miss_ID = null; var Miss_Slot = null; var MyMafiaJobs = null; var idleCity = GM_getValue('idleLocation', NY); if(city != idleCity){ Autoplay.fx = function(){ goLocation(idleCity); }; Autoplay.start(); return false; return true; } if(!OnMissionsTab()){ Autoplay.fx = GoMissionsTab; Autoplay.start(); return true; } DEBUG('Mymission Timer '+parseInt(timeLeftGM('checkedmymissionTimer'))+' Seconds.') ; if(!timeLeftGM('checkedmymissionTimer')){ if(!My_Missions_Tab()){ Autoplay.fx = Go_My_Missions_Tab; Autoplay.start(); return true; } if(isGMChecked('AutoStartOperations')){ Check_For_Start_A_Mission(); } Check_For_Remove_A_Mission(); if(isGMChecked('AskMissionHelp') ) Chk_mission_help () ; if(isGMChecked('AutoMafiaCollection')) Auto_Mafia_Collection() ; // will collect mymission if(isGMChecked('AutoMafiaRemoved')) Auto_Mafia_Remove() ; // will check for being removed from operations on this page if(Chk_Nxt_MY_Mission()){ Autoplay.fx = Go_Nxt_Page; Autoplay.start(); return true; } DEBUG(' mission. end of myMissions processing, set timer 2 min, checking myMafia operations.'); setGMTime('checkedmymissionTimer', '00:02:00'); } // end of mymissions next is myMafia missions // if(!Mafia_Missions_Tab()){ Autoplay.fx = Go_Mafia_Missions_Tab(); Autoplay.start(); return true; } if(isGMChecked('AskMissionHelp')) Chk_mission_help () ; if(isGMChecked('AutoMafiaCollection')) Auto_Mafia_Collection() ; // will collect mymission if(isGMChecked('AutoMafiaRemoved')) Auto_Mafia_Remove() ; // will check for being removed from missions onthis page if(isGMChecked('AutoMafiaJob')){ if(Check_Mission_Job()){ Autoplay.fx = Do_Mission_Job(); Autoplay.start(); return true; } } if(Chk_Nxt_Page()){ Autoplay.fx = Go_Nxt_Page; Autoplay.start(); return true; } else { // this fixes the hang on leaveing operations Autoplay.fx = goHome; Autoplay.start(); return true; } return; } //// function OnMissionsTab(){ if(xpathFirst('//div[@id="socialMissionNav"]//a',innerPageElt)){ return true; } return false; } //// function GoMissionsTab(){ var elt = xpathFirst('//div[@id="nav_link_events_unlock"]//a',menubarElt); if(elt){ var numMiss = xpathFirst('//span[contains(@id,"user_socialmissions")]',menubarElt); if(numMiss){ missCnt = numMiss.innerHTML.untag(); numMissCnt = parseInt(missCnt.replace( /\D/g , "" )); if(numMissCnt > 0){ DEBUG('Clicking Family Tab to go check on '+numMissCnt +' operations.'); clickElement(elt); return true; } else { mmis_time = '00:15:00'; // set timer to 15 min DEBUG(' operations count '+numMissCnt+' timer set to: '+ mmis_time ); setGMTime('colmissionTimer', mmis_time); return false; } } else { DEBUG('number of operations not found, go check just in case'); clickElement(elt); } } } //// function Chk_mission_help(){ var missionElts = $x('.//div[@class="socialMission" and contains(@id,"socialMission_")]',innerPageElt); if(missionElts && missionElts.length>0){ for(i=0,iLength=missionElts.length;i0){ return true; } return false; } //// function Do_Reward_Collection(){ var ColMissionReward = xpathFirst('.//a[@class="sexy_button_new medium green" and contains(@onclick, "collectReward")]', innerPageElt); if(ColMissionReward){ clickElement(ColMissionReward); return true; } return; } //// function Auto_Mafia_Remove(){ var parentDivs; parentDivs = $x('.//div[@class="missionBoxRight"]', innerPageElt); numDivs = parentDivs.length; if(numDivs>0){ for(i=0;i 0){ DEBUG('We need '+cashDiff+' to do this Operation 5 times. Going to the bank/vault of '+city); suspendBank = true; autoBankWithdraw(cashDiff); Autoplay.fx = GoMissionsTab; Autoplay.start(); return false; } } if((!chk_stam()) || (!chk_nrg()) ){ MyMafiaJobs = null; return false; } if(MyMafiaJobs){ colorDEBUG('autoMission - We can do this Mission'); return true ; } } } // Family Boss Fight Functions function bossLoad(){ // Shows the listing of bosses.. if (!running||!isGMChecked('autoFamilyBosses')){ isBossRunning = false; return; } mwap_do_ajax('Epicclanboss','list_view','','',bossCallback); } function bossLoadBoss(){ // Shows the boss page mwap_do_ajax('Epicclanboss','boss_view','','&boss_id='+current_boss_id,bossCallback); } function bossJoin(){ // Role is one of arsonist,racketeer,bruiser //mwap_do_ajax('Epicclanboss','epic_join','','&role='+GM_getValue('bossRole','racketeer')+'&boss_id='+current_boss_id,bossCallback); mwap_do_ajax('Epicclanboss','epic_join','','&role='+bossRoles[GM_getValue('bossRole',0)]+'&boss_id='+current_boss_id,bossCallback); } function bossSendBoost(cell_id, role_id, boss_id, target_ppid){ mwap_do_ajax('Epicclanboss','epic_send_role','','&role_id='+role_id+'&boss_id='+boss_id+'&cell_id='+cell_id+'&target_ppid='+target_ppid,bossCallback); } function bossAskBoost(role_id, boss_id){ // Role: 1 = Bruiser, 2 = Arsonist, 3 = Racketeer mwap_do_ajax('Epicclanboss','epic_ask_role','','&role_id='+role_id+'&boss_id='+boss_id,bossCallback); } function bossCollect(boss_id){ mwap_do_ajax('Epicclanboss','epic_collect','','&boss_id='+boss_id,bossCallback); } function bossAttack(){ mwap_do_ajax('Epicclanboss','epic_attack','','&consumable_id=0&boss_id='+current_boss_id,bossCallback); } function bossCallback(controller, action, other, city, status, request){ if (status){ // If we were successful var Bosses = []; // empty array var BossNames = []; var respData; if (action == 'epic_ask_role' || action == 'epic_send_role'){ if(IsJsonString(request.responseText)){ var jsonresult = JSON.parse(request.responseText); if (jsonresult.data && jsonresult.data.impulseBuy){ addToLog('info Icon', jsonresult.data.impulseBuy.message.untag()); } } window.setTimeout(bossLoad,getAutoPlayDelay()); return; } else if (action=='epic_attack'){ if(IsJsonString(request.responseText)){ var jsonresult = JSON.parse(request.responseText); if(jsonresult.data) if(IsJsonString(jsonresult.data)) respData = JSON.parse(jsonresult.data); if (respData && respData.damage.toBoss){ addToLog('info Icon', 'Did ' + respData.damage.toBoss + ' damage to ' + current_boss_name); } } window.setTimeout(bossLoad,getAutoPlayDelay()); return; } else if (action=='epic_collect' || action=='epic_join'){ window.setTimeout(bossLoad,getAutoPlayDelay()); return; } else if (action=='boss_view'){ if (request.responseText.indexOf('xw_controller=Epicclanboss&xw_action=epic_join')!=-1){ addToLog('info Icon', 'Joining Boss' + current_boss_id); bossJoin(); return; } else { doc = document.createElement('div') doc.innerHTML = request.responseText var page = request.responseText; var boosts = 0, boss_rage = 0, boss_stamina = 0; var userData, bossData; // Object to store the boss userdata var i1 = request.responseText.indexOf('"currentCharges":'); if (i1!=-1){ boosts = parseInt(request.responseText.slice(i1+17,request.responseText.indexOf(',',i1))); } //addToLog('info Icon', 'We have ' + boosts + ' boosts to send for boss ' + current_boss_id); // Check for sending boosts.. var sendElts = $x('.//div[contains(@class,"helpButton") and contains(@style, "block")]/a[contains(@href,"xw_action=epic_send_role&")]', doc); if (sendElts && sendElts.length && boosts > 0 && isGMChecked('sendBossFightBoosts')){ var bossSendElt = sendElts[Math.floor(Math.random() * sendElts.length)]; // Random Person var role_id = bossSendElt.href.match(/role_id=(\d+)/)[1]; var cell_id = bossSendElt.href.match(/cell_id=(\d+)/)[1]; var target_ppid = bossSendElt.href.match(/target_ppid=(.*)/)[1]; addToLog('info Icon', 'Sending a boost to a family member, playerid: ' + target_ppid); bossSendBoost(cell_id, role_id, current_boss_id, target_ppid); return; } // Check for asking boosts.. var boostElts = $x('.//div[contains(@class,"needBoost") and not(contains(@style, "none"))]/div[contains(@class,"boostAskHelp") and not(contains(@style, "none"))]/a[contains(@href,"xw_action=epic_ask_role")]', doc); // Ask for a boost if we can.. if (boostElts && boostElts.length && isGMChecked('askBossFightBoosts')){ //addToLog('info Icon', 'We can ask for ' + boostElts.length + ' boosts'); var role_id = boostElts[0].href.match(/role_id=(\d+)/)[1]; bossAskBoost(role_id,current_boss_id); return; } // Stamina isearch='user_fields[\'user_stamina\'] = parseInt("'; i1 = page.indexOf(isearch); if(i1!=-1){ boss_stamina = parseInt(page.slice(i1+isearch.length,page.indexOf('"',i1+isearch.length))); } isearch = 'bossData = {'; i1 = page.indexOf(isearch); if(i1!=-1){ bossData = JSON.parse(page.slice(i1+isearch.length-1,page.indexOf('};',i1+isearch.length)+1)); } isearch = 'userData = {'; i1 = page.indexOf(isearch); if(i1!=-1){ userData = JSON.parse(page.slice(i1+isearch.length-1,page.indexOf('};',i1+isearch.length)+1)); } DEBUG('Rage: ' + bossData.current_rage + ' Stamina: ' + boss_stamina); if ( isGMChecked('autoFamilyBossFighting') && (bossData.current_rage < GM_getValue('bossRageLimit',250) || userData.pendingRoleEffects["2"]["count"] > 0) && //(userData.stamina_required <= GM_getValue('bossStaminaLimit',5) || userData.pendingRoleEffects["3"]["count"] > 0) && (userData.stamina_required <= bossStaminaLimits[GM_getValue('bossStaminaLimit',0)] || userData.pendingRoleEffects["3"]["count"] > 0) && (bossData.currHealth > 0 && boss_stamina >= userData.stamina_required) ){ bossAttack(); return; } DEBUG('Rage: ' + bossData.current_rage + ' / Limit ' + GM_getValue('bossRageLimit',250) + ' boosts: ' + userData.pendingRoleEffects["2"]["count"]); DEBUG('Stamina: ' + userData.stamina_required + ' / Limit ' + bossStaminaLimits[GM_getValue('bossStaminaLimit',0)] + ' boosts: ' + userData.pendingRoleEffects["3"]["count"]); DEBUG('Boss Health: ' + bossData.currHealth + ' Current Stamina: ' + boss_stamina); // We made it here.. we can't do anything else to this boss. setGMTime('familyBoss_'+current_boss_id, '02:00'); // Check this boss again in 2 minutes. window.setTimeout(bossLoad,getAutoPlayDelay()); return; } } else { // List View.. doc = document.createElement('div') doc.innerHTML = request.responseText // Check if we can collect.. i1 = request.responseText.match(/xw_controller=Epicclanboss&xw_action=epic_collect.*?&boss_id=(\d+)/); if (i1 && i1[1]){ addToLog('info Icon', 'Found boss collect for: ' + i1[1]); bossCollect(i1[1]); return; } var bossElts = $x('.//div[@class="boss_operation"]',doc); for (i = 0; i < bossElts.length; i++) { var bossNameElt = xpathFirst('.//div[contains(@class,"boss_name")]', bossElts[i]); var bossName = bossNameElt.innerHTML.untag().trim(); // Can we go to the boss fight? if (xpathFirst('.//a[contains(@onclick,"BossOperationController.goToFight")]', bossElts[i])){ if (!timeLeftGM('familyBoss_'+bossElts[i].id.split('_')[1])){ Bosses.push(bossElts[i].id.split('_')[1]); BossNames.push(bossName); DEBUG('Found active boss fight for: ' + bossName + ' ' + bossElts[i].id.split('_')[1] ); } } } if (Bosses.length){ // Reset it to the 1st if we are at the end.. if (current_boss_index > Bosses.length-1){current_boss_index = 0;} current_boss_id = Bosses[current_boss_index]; // Set the bossid current_boss_name = BossNames[current_boss_index]; current_boss_index++; // Increment the index DEBUG('Loading Boss Page: ' + current_boss_name); window.setTimeout(bossLoadBoss,getAutoPlayDelay()); // Load the boss page return; } // If we are here.. we don't have a boss to go to.. addToLog('info Icon', 'Family Boss Fight is idling'); window.setTimeout(bossLoad,120000); // Check again in 2 minutes. return; } } else { // Failed Request.. window.setTimeout(bossLoad,20000); } } // Battle Safehouse Functions function battleLoad(){ mwap_do_ajax('EpicBattle','view','','',battleCallback); } function battleAttackSafeHouse(){ mwap_do_ajax('epicBattle','attackFortress','','',battleCallback); } function battleJoin(){ mwap_do_ajax('epicBattle','optIn','','',battleCallback); } function battleCallback(controller, action, other, city, status, request){ if(status){ // If we were successful try{ if(!running){ inSafehouse = false; return; } var page = request.responseText; var myHealth = 0; var myStamina = 0; var i1,isearch; // Did we do damage? var message = page.match(/(.*?)<\/td>/); if(message){ var tmp = message[0].untag().trim(); if (tmp.length){ addToLog('info Icon', tmp); } } isearch='user_fields[\'user_health\'] = parseInt("'; i1 = page.indexOf(isearch); if(i1!=-1){ myHealth = parseInt(page.slice(i1+isearch.length,page.indexOf('"',i1+isearch.length))); } isearch='user_fields[\'user_stamina\'] = parseInt("'; i1 = page.indexOf(isearch); if(i1!=-1){ myStamina = parseInt(page.slice(i1+isearch.length,page.indexOf('"',i1+isearch.length))); } if(page.indexOf('xw_controller=epicBattle&xw_action=optIn')!=-1){ addToLog('info Icon', 'Joining Battle'); window.setTimeout(battleJoin,getAutoPlayDelay());// Join Battle } else if(myHealth > 20 && myStamina >= 10 && page.indexOf('xw_controller=epicBattle&xw_action=attackFortress')!=-1){ // Probably want to limit based on the stamina settings we have, but this'll do for now.. window.setTimeout(battleAttackSafeHouse,getAutoPlayDelay());// Attack Again } else { // Is the battle over? if(request.responseText.indexOf('"inBattle":true')!=-1){ // No attack safehouse, but still in the battle.. check again in 15 seconds. window.setTimeout(battleLoad,15000); } else { // Not in a battle, set the variable to off.. and stop processing.. inSafehouse = false; } } } catch (err){ inSafehouse = false; } // We failed.. Turn this off temporarily.. } else { inSafehouse = false; } } //// function setmissiontimer(){ var mmis_time = '00:15:00'; // set timer to 15 min DEBUG(' mission timer set to: '+ mmis_time ); setGMTime('colmissionTimer', mmis_time); } ///////////////////////////////////////////////////////// end of miss collect Function.prototype.bind = function( thisObject ){ var method = this; var oldargs = [].slice.call( arguments, 1 ); return function (){ var newargs = [].slice.call( arguments ); return method.apply( thisObject, oldargs.concat( newargs )); }; } function doFBParse(_myResponse){ // Reused with some slight changes from our code in Wall Scrubber var i1, i2, i1b, i1c, i1d, myUrl, myParms; var strTemp; var PhaseSearch = [ '',i1); eval('strTemp = '+_myResponse.slice(i1,i2)); break; } } // strTemp should be an object here.. if(typeof strTemp=="object" && strTemp.content.pagelet_iframe_canvas_content){ if(strTemp.content.pagelet_iframe_canvas_content.container_id){ i1 = _myResponse.indexOf(''); if(i1>0){ i2 = _myResponse.indexOf('', i1); strTemp = _myResponse.slice(i1,i2); } } else { strTemp = strTemp.content.pagelet_iframe_canvas_content; } } else if(typeof strTemp=="object" && strTemp.content.pagelet_fbml_canvas_content){ if(strTemp.content.pagelet_fbml_canvas_content.container_id){ i1 = _myResponse.indexOf(''); if(i1>0){ i2 = _myResponse.indexOf('', i1); strTemp = _myResponse.slice(i1,i2); } } else { strTemp = strTemp.content.pagelet_fbml_canvas_content; } } else { strTemp = _myResponse; } i1 = strTemp.indexOf('

'+ '
Close Popup'+ ''; MWAP_RX6_PopupOpen(popupTitle, content, height); MWAP_RX6_PopupActivate(); } } }