// ==UserScript==
// @name           Facebook Warstorm Autoplayer
// @namespace      game-designer.org
// @description    Autoplayer for Facebook Warstorm by Challenge Games
// @include        http://apps.facebook.com/warstorm/*
// @include        http://fb.warstorm.com/?*
// @include        http://fb.warstorm.com/play?*
// ==/UserScript==

// Run main
if (!checkLoadIframe()) {  
  var fbwsCSS = 
    'html { overflow: auto !important } '
  + '#wrapper, #cgbar_container, #top_box_container, #script_container { width: 760px; margin: 0 !important; padding: 0 !important; } '
  + 'body { background: black; } '
  + 'strong { color: #F93 }'
  + 'a:link, a:visited { color: #0CF; }'
  + 'a:hover { color: #0FC; }';

  // Adjust footer
  document.getElementById("footer").getElementsByTagName("p")[0].innerHTML = document.getElementById("footer").getElementsByTagName("p")[0].innerHTML.replace("|","<br/>");
  fbwsCSS += '#footer { background: black; position: fixed; bottom: 0; left: 0; width: 424px; height: 75px; color: white; z-index: 100; overflow: auto; margin: 0 0 0 800px !important; } '
          +  '#footer p { padding: 10px 0 0 0 !important; } ';

  if(!GM_getValue('fbwsAutoSilver'))
    GM_setValue('fbwsAutoSilver',0);
  if(!GM_getValue('fbwsAutoExp'))
    GM_setValue('fbwsAutoExp',0);

  fbwsRefreshTimer = null;
  fbwsAutoRunning = null;

  makeBox();
  
  document.getElementById("fbwsRefreshProfile").setAttribute('value','Refreshing...');
  document.getElementById("fbwsRefreshProfile").setAttribute('style','color: red');
  window.setTimeout(getProfile, 5000);

  // CSS
  makeElement('style', document.getElementsByTagName('head')[0], {'id':'fbwsCSS','type':'text/css'}).appendChild(document.createTextNode(fbwsCSS));
}

// Load the iframe
function checkLoadIframe() {
  var iFrameCanvas = document.getElementById("app29507308663_iframe_canvas");
  if (iFrameCanvas) {
    window.location.replace(iFrameCanvas.src);
    return true;
  }
  return false;
}

// Make box
function makeBox() {
  fbwsCSS += '.alt1, .alt2 { color: #eee; padding: 10px; padding: 10px; line-height: 1.5em; }'
          +  '.alt1 { background: #333; } .alt2 { background: #444 }';
          +  '.alt1 p, .alt2 p { padding-bottom: 10px; }';

  fbwsContainer = makeElement('div', document.body, {'id':'fbwsContainer'});   
  fbwsCSS += '#fbwsContainer { position: absolute; top: 32px; left: 800px; width: 424px; z-index: 98; border: 1px solid; border-color: #777; } ';

  fbwsProfile = makeElement('div', fbwsContainer, {'id':'fbwsProfile'});
  fbwsCSS += '#fbwsProfile { background: black; height: 32px; color: #FC0; line-height: 32px; font-weight: bold; padding-left: 10px; font-size: 1.4em; } ';
  
  fbwsInfo = makeElement('div', fbwsContainer, {'id':'fbwsInfo','class':'alt1'});
    
  fbwsAutoMatch = makeElement('div', fbwsContainer, {'id':'fbwsAutoMatch','class':'alt2'});
  fbwsCSS += '#fbwsAutoMatch select { width: 25%; } '
          +  '#fbwsAutoAmount { width: 2em; padding: 0 5px; text-align: center; } ';

  fbwsRefresh = makeElement('div', fbwsContainer, {'id':'fbwsRefresh','class':'alt1'});
  fbwsCSS += '#fbwsRefresh input[type=submit] { display: block; width: 60%; margin: 5px auto; padding: 0 50px; line-height: 1.2em; border: 1px solid; border-color: #777; background: #000; color: #FC0; cursor: pointer; }';
  fbwsRefresh.innerHTML = '<input type="submit" value="Refresh Warstorm" id="fbwsRefreshButton"/>'
                        + '<input type="submit" value="Refresh Profile" id="fbwsRefreshProfile"/>'
                        + '<div id="fbwsAutoRefresh"><input type="checkbox" value="" id="fbwsRefreshBoolean"/> '
                        + '<strong>Auto refresh</strong> '
                        + 'every <input type="text" value="0.08" id="fbwsRefreshAmount"/> minutes</div>';
  fbwsCSS += '#fbwsAutoRefresh input[type=text] { width: 2em; padding: 0 5px; text-align: center; } '
          +  '#fbwsRefreshBoolean { position: relative; top: 2px; } '
          +  '#fbwsAutoRefresh { text-align: center; }';
  document.getElementById("fbwsRefreshButton").addEventListener("click", refresh, false);
  document.getElementById("fbwsRefreshProfile").addEventListener("click", getProfile, false);
  document.getElementById("fbwsRefreshBoolean").addEventListener("change", startRefreshTimer, false);
  document.getElementById("fbwsRefreshAmount").addEventListener("change", changeTimeout, false);
  
  if(GM_getValue('fbwsRefreshBoolean'))
    document.getElementById("fbwsRefreshBoolean").checked = GM_getValue('fbwsRefreshBoolean');
  if(GM_getValue('fbwsRefreshAmount'))
    document.getElementById("fbwsRefreshAmount").value = GM_getValue('fbwsRefreshAmount');
  
  startRefreshTimer();
}

// Refresh Timer Stuff
function startRefreshTimer() {
  var timeout = parseInt(document.getElementById("fbwsRefreshAmount").value);
  GM_setValue('fbwsRefreshBoolean', document.getElementById("fbwsRefreshBoolean").checked);
  if (document.getElementById("fbwsRefreshBoolean").checked)
  {
    if (typeof(timeout) == 'number') {
      timeout *= 60000;
      fbwsRefreshTimer = window.setTimeout(refresh, timeout);
    }
  }
  else {
    if(fbwsRefreshTimer) {
      clearTimeout(fbwsRefreshTimer);
    }
    fbwsRefreshTimer = null;
  }
}

function changeTimeout() {
  GM_setValue('fbwsRefreshAmount', document.getElementById("fbwsRefreshAmount").value);
}

function refresh() { 
  window.location.reload(true); 
  document.getElementById("fbwsRefreshButton").setAttribute('value','Refreshing...');
  document.getElementById("fbwsRefreshButton").setAttribute('style','color: red');
}

// Get Profile
function getProfile() {
  document.getElementById("fbwsRefreshProfile").setAttribute('value','Refreshing...');
  document.getElementById("fbwsRefreshProfile").setAttribute('style','color: red');
  GM_xmlhttpRequest({
    method: "GET",
    url: "http://fb.warstorm.com/avatars/get_state/all",
    onload: function(response) {
      if (!response.responseXML) {
        response.responseXML = new DOMParser()
      	.parseFromString(response.responseText, "text/xml");
      }
      
      fbwsXML = response.responseXML;
      fbwsProfile.textContent = QF('//warstorm_player/avatar/name').textContent
      + " - Rating: " + QF('//warstorm_player/avatar/rating').textContent;
      
      fbwsInfo.innerHTML = 
        "<strong>User ID: </strong>" + QF('//warstorm_player/avatar/user_id').textContent + "<br/>"
      + "<strong>Exp: </strong> " + QF('//warstorm_player/avatar/experience').textContent + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
      + "<strong>Silver: </strong> " + QF('//warstorm_player/avatar//currency[2]/value').textContent + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
      + "<strong>Cash: </strong> " + QF('//warstorm_player/avatar//currency[1]/value').textContent;
      
      var squads = Q('//warstorm_player/squads/squad');
      var squadArray = '<option value="0">NONE</option>';
      for(var i=0;i < squads.snapshotLength;++i)
        squadArray += '<option value="' + squads.snapshotItem(i).getElementsByTagName('squad_id')[0].textContent + '">'
                   +  squads.snapshotItem(i).getElementsByTagName('name')[0].textContent + '</option>';
                            
      fbwsAutoMatch.innerHTML = 
	"<strong>Fight Automatches with: </strong> <br/><br/>"
      + '<select id="fbwsSquad1Select">'
      + squadArray + '</select>'
      + '<select id="fbwsSquad2Select">'
      + squadArray + '</select>'
      + '<select id="fbwsSquad3Select">'
      + squadArray + '</select>'
      + '<select id="fbwsSquad4Select">'
      + squadArray + '</select><br/><br/>'
      
      + 'Battle <input type="text" id="fbwsAutoAmount" value="40"/> times/hour. <a href="#" id="fbwsAutoStart">Start!</a>'
      + '<span id="fbwsAutoStats"> </span>';
      
      if(GM_getValue('fbwsAutoSilver') > 0 || GM_getValue('fbwsAutoExp') > 0) {
        document.getElementById("fbwsAutoStats").innerHTML = '<br/></br>' + GM_getValue('fbwsAutoSilver') + ' silver and '
                                                           + GM_getValue('fbwsAutoExp') + ' experience earned so far...'
                                                           + ' <a href="#" id="fbwsAutoClear">Clear</a>';
        document.getElementById("fbwsAutoClear").addEventListener("click", function() { GM_setValue('fbwsAutoSilver',0); GM_setValue('fbwsAutoExp',0); document.getElementById("fbwsAutoStats").innerHTML = ''; }, false);
      }
                                                           
      document.getElementById("fbwsAutoStart").addEventListener("click", startBattleInterval, false);
      
      document.getElementById("fbwsSquad1Select").addEventListener("change", function() { GM_setValue("fbwsSquad1Select",document.getElementById("fbwsSquad1Select").selectedIndex); }, false);
      if (GM_getValue("fbwsSquad1Select")) document.getElementById("fbwsSquad1Select").selectedIndex = GM_getValue("fbwsSquad1Select");
      document.getElementById("fbwsSquad2Select").addEventListener("change", function() { GM_setValue("fbwsSquad2Select",document.getElementById("fbwsSquad2Select").selectedIndex); }, false);
      if (GM_getValue("fbwsSquad2Select")) document.getElementById("fbwsSquad2Select").selectedIndex = GM_getValue("fbwsSquad2Select");
      document.getElementById("fbwsSquad3Select").addEventListener("change", function() { GM_setValue("fbwsSquad3Select",document.getElementById("fbwsSquad3Select").selectedIndex); }, false);
      if (GM_getValue("fbwsSquad3Select")) document.getElementById("fbwsSquad3Select").selectedIndex = GM_getValue("fbwsSquad3Select");
      document.getElementById("fbwsSquad4Select").addEventListener("change", function() { GM_setValue("fbwsSquad4Select",document.getElementById("fbwsSquad4Select").selectedIndex); }, false);
      if (GM_getValue("fbwsSquad4Select")) document.getElementById("fbwsSquad4Select").selectedIndex = GM_getValue("fbwsSquad4Select");
      
      if (fbwsAutoRunning) document.getElementById("fbwsAutoStart").textContent = 'Stop';

      document.getElementById("fbwsRefreshProfile").setAttribute('value','Refresh Profile');
      document.getElementById("fbwsRefreshProfile").setAttribute('style','');
      
      if(GM_getValue('fbwsAutoRunning') && !fbwsAutoRunning) {
        startBattleInterval();
      }
    }
  });
}

// Autobattle
function startBattleInterval() {
  if (fbwsAutoRunning) {
    if (fbwsAutoRunning) document.getElementById("fbwsAutoStart").textContent = 'Start';
    window.clearInterval(fbwsAutoRunning);
    GM_deleteValue('fbwsAutoRunning');
    fbwsAutoRunning = null;
  } else {
    if(document.getElementById("fbwsAutoAmount").value) {
      startBattle();
      fbwsAutoRunning = setInterval(startBattle, 3600000 / document.getElementById("fbwsAutoAmount").value);
      GM_setValue('fbwsAutoRunning',fbwsAutoRunning);
      if (fbwsAutoRunning) document.getElementById("fbwsAutoStart").textContent = 'Stop';
    }
  }
}

function startBattle() {
  var url = "http://fb.warstorm.com/battle/automatch";
  var squads = '?';
  
  for (var i=1;i<=4;++i) {
    var el = document.getElementById('fbwsSquad'+i+'Select');
    if(el.options[el.selectedIndex].value != 0) {
      squads += 'squad' + i + '=' + el.options[el.selectedIndex].value;
      squads += '&';
    }
  }
  
  if(squads == '?')
    return;
    
  url += squads;
  
  document.getElementById("fbwsAutoStart").textContent = 'Stop';
  
  GM_xmlhttpRequest({
    method: "GET",
    url: url,
    onload: function(response) {
      if (!response.responseXML) {
        response.responseXML = new DOMParser()
      	.parseFromString(response.responseText, "text/xml");
      }
      
      fbwsXML = response.responseXML;
      
      var failure = QF('//challengegames/response').textContent;
      if(failure == 'failure') {
        getProfile();
        return;
      }
      
      var silver = QF('//message/winnings//value');
      if (silver) {
        silver = parseInt(silver.textContent) + GM_getValue('fbwsAutoSilver');
        GM_setValue('fbwsAutoSilver', silver);
      }
      
      var exp = QF('//message/winnings/experience');
      if (exp) {
        exp = parseInt(exp.textContent) + GM_getValue('fbwsAutoExp');
        GM_setValue('fbwsAutoExp', exp);
      }
      
      getProfile();
    }
 });
}

// DOM Library
function makeElement(type, appendto, attributes) {
  var element = document.createElement(type);
  if (attributes != null) {
    for (var i in attributes) {
      element.setAttribute(i, attributes[i]);
    }
  }
  if (appendto) {
    appendto.appendChild(element);
  }
  return element;
}

function destroyByID( id){
  var elt = document.getElementById(id);
  if (elt) elt.parentNode.removeChild(elt);
}

function remakeElement(type, appendto, attributes) {
  if (attributes.id) destroyByID(attributes.id);
  return makeElement(type, appendto, attributes);
}

// XPATH library

function Q(query) {
  if(fbwsXML)
    return xpath(query, fbwsXML);
}

function QF(query) {
  if(fbwsXML)
    return xpathFirst(query, fbwsXML);
}

function xpathFirst(query, xml) {
  return xml.evaluate(query, xml, null, XPathResult.ANY_UNORDERED_NODE_TYPE, null).singleNodeValue;
}

function xpath(query, xml) {
  return xml.evaluate(query, xml, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
}

// Cookie Library
function readCookie(name) {
	var nameEQ = name + "=";
	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 c.substring(nameEQ.length,c.length);
	}
	return null;
}

