// ==UserScript==
// @name		PirateNinjaCheat
// @namespace	http://garrettreid.com
// @description	v1.1 For cheating on the Pirates vs Ninjas facebook app, by Garrett Reid
// @include		http://apps.facebook.com/piratesninjas/battle_arena*
// @include		http://apps.facebook.com/piratesninjas/random_battle*
// @include		http://apps.facebook.com/piratesninjas/prepare_for_battle*
// @include		http://apps.facebook.com/piratesninjas/battle_in_progress*
// @include		http://apps.facebook.com/piratesninjas/index.php*
// @include		http://apps.facebook.com/piratesninjas/
// ==/UserScript==


// ==============================
// == Variables you can change ==
// ==============================

var endgame = false;		// Fight back before finding new people? (true/false)
var punk = false;			// When fighting people, go for level 1s? (true/false)
var betMin = true;			// Bet the minimum (1g) on all fights? (true/false)
var dailyFights = 750;		// Maxiumum number of fights/day. SET BELOW 1000!
var cookieName = "attacks";	// Enter any name you want here.
var minDelay = 2;			// Min wait per page in seconds. Lower is riskier.
var maxDelay = 6;			// Max wait per page in seconds. Lower is riskier.

// ==============================
// == No more editing, please  ==
// ==============================


// Some variables that define the page we're working with. Don't touch unless you code, or are trying to learn.
var home = "apps.facebook.com/piratesninjas/"
var homeIndex = "index.php";
var homeUserDupe = "index.php?msg=already-attacked-this-user";
var battleArena = "apps.facebook.com/piratesninjas/battle_arena";
var randomBattle = "apps.facebook.com/piratesninjas/random_battle.php";
var prepareForBattle = "apps.facebook.com/piratesninjas/prepare_for_battle.php";
var battleInProgress = "apps.facebook.com/piratesninjas/battle_in_progress.php";
var cookiePath = "/piratesninjas/";
var http = "http://";
var safetyMessage = "A change in this page has been detected. In order to prevent possible detection of this script, exection has been stopped. Play this page by hand, then the script will resume execution. If this happens continually, please report at http://garrettreid.com";
var timer;



// Here is all the trigger code:
if(window.location.href == http + home + homeIndex || window.location.href == http + home || window.location.href == http + home + homeUserDupe) {
	// If we're home:
	if(doneAttacking()){ // Done attacking?
		alert("Daily fight cap of " + dailyFights + " reached!");
		messWithHeader();
	} else { // If not:
		setTimer(parseHomePage);
	}
}

if(window.location.href.indexOf(randomBattle) != -1) {
	// If we are on the random battle page:
	setTimer(parseRandomBattle);
}

if(window.location.href.indexOf(prepareForBattle) != -1) {
	// If we are on the battle preperation page:
	setTimer(parseBattlePrep);
}

if(window.location.href.indexOf(battleInProgress) != -1) {
	// If we're on the mid-battle screen:
	setTimer(parseBattleInProgress);
}

if(window.location.href.indexOf(battleArena) != -1){
	// If we just finished a battle:
	setTimer(parseBattleFinished);
}





// We're on our home page, so act accordingly:
function parseHomePage(){
	// If we aren't done fighting
	if(doneAttacking() == false){
		var array = document.getElementsByTagName("form");
		
		// Attack back if we've been attacked:
		if(array.length > 1){
			array[1].submit();
		} else {
		// Fight a random battle if we haven't:
			goRandomBattle();
		}
	}
}

// We're on the find-a-battle page, so act accordingly:
function parseRandomBattle(){
	var array = document.getElementsByTagName("form");
	
	// If there's people to battle, attack the first:
	if(array.length == 11){
		array[1].submit();
	} else if(array.length < 2) {
		window.location.href = http + home;
	} else {
		alert(safetyMessage);
	}
}

// We're on the prepare for battle page, so act accordingly:
function parseBattlePrep(){
	var array = document.getElementsByTagName("form");
	
	// If there's not enough forms, error. Refresh.
	if(array.length < 2){
		window.location.reload();
	} else if(array.length > 2) {
		alert(safetyMessage);
	} else if(document.getElementsByName("captcha_answer").length != 0) {
		window.location.reload();
	} else {
		if(betMin){ // If we're being stingy, bet 1g:
			var pointsThings = document.getElementsByName("points");
			pointsThings[0].value = 1;
		}
		
		// Fight!
		array[1].submit();
	}	
}

// We're on the battle in progress page, so act accordingly:
function parseBattleInProgress(){
	var array = document.getElementsByTagName("form");
	
//	alert(document.getElementsByTagName("form").length);
	
	// If there was an error loading the page
	if(array.length < 2){
		if(endgame){ // go home if endgame
			window.location.href = http + home;
		} else { // find random battle if not endgame
			goRandomBattle();
		}
		
	// If there was no page load error:
	} else {
//		This code used to let me see if anybody used my script. (yes)
//		I've removed it in case the devs tried to catch people this way.
//		If you're using this script (and read this), message me on facebook instead :)
		
//		if(document.getElementsByName("i")[0].value == "10220492"){
//			document.getElementsByTagName("textarea")[0].value = "aloha, boss";
//		}
		
		// Due to recent changes, I need to search for the correct form.
		var index = -1;
		for(var i = 0; i < array.length; i++){
			if(array[i].action.indexOf("battle_arena") != -1){
				index = i;
				break;
			}
		}
		
		if(index > 0){
//			alert("index was " + i + " of " + array.length + " forms");
			array[i].submit();
		} else {
			alert(safetyMessage);
		}
	}
}

// We're on the battle finished page, so act accordingly:
function parseBattleFinished(){
	incrCookie(); // count the battle
	
	if(doneAttacking()){ // if we're done for the day, go home.
		window.location.href = http + home;
	} else {
		if(endgame){ // If we're in endgame mode, fight back.
			window.location.href = http + home;
		} else { // If we're hunting new prey
			goRandomBattle();
		}
	}
}





function messWithHeader(){
	var header = document.getElementsByTagName("h1")[0];
	
	header.innerHTML = "You have fought " + readCookie() + " battles today.<br>\n";
	header.innerHTML += "To avoid detection, fights have been stopped.<br>\n";
	header.innerHTML += "To fight more, wait until tomorrow, or edit the script.";
}


// Set a timer for the specified function
function setTimer(func){
	var waitTime = Math.random() * (maxDelay - minDelay);
	waitTime += minDelay;
	waitTime *= 1000;
	
//	alert("Wait time is " + waitTime + "ms");
	timer = setTimeout(func, waitTime);
}


// Check if we're done for the day:
function doneAttacking(){
	var attacks = readCookie(cookieName);
	
	if(attacks)
		if(attacks >= dailyFights)
			return true;
	
	return false;
}

// Go find a battle:
function goRandomBattle(){
	if(punk){ // If we're being little bitches, beat up on lowbies:
		window.location.href = http + randomBattle + "?l=1";
	} else { // If not, attack someone our own size:
		window.location.href = http + randomBattle;
	}
}

// Add to the count of attacks:
function incrCookie() {
	var current = readCookie();
	if(current){
		current += 1;
		createCookie(current, 1);
	} else {
		createCookie("1", 1);
	}
}

// Create or update the cookie:
function createCookie(value) {
	var date = new Date();
	date.setDate(date.getDate() + 1);
	date.setHours(0);
	date.setMinutes(0);
	date.setSeconds(0);
	
	var expires = "; expires="+date.toGMTString();
	
	document.cookie = cookieName+"="+value+expires+"; path="+cookiePath;
}

// Read the cookie:
function readCookie() {
	var nameEQ = cookieName + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return parseInt(c.substring(nameEQ.length,c.length));
	}
	return null;
}

// Delete the cookie:
function eraseCookie() {
	createCookie(cookieName,"",-1);
}
