// ==UserScript==
// @name           auto-mission
// @namespace      hk.orz
// @description    by neo@orz.hk, please visit http://orz.hk
// @include        http://apps.facebook.com/street-wars/job.php
// Version 1.0
// ==/UserScript==

// config
// interval to check action point (in seconds)
var check_interval = 600;

var last_check = new Date();

// setup a count down box
var htmlElement = document.createElement('div');
htmlElement.id = 'timer';
htmlElement.style.color = 'black';
htmlElement.style.position = 'fixed';
htmlElement.style.width = '150px';
htmlElement.style.height = '80px';
htmlElement.style.paddingTop = '4px';
htmlElement.style.paddingLeft = '2px';
htmlElement.style.background = '#CCCCCC';
htmlElement.style.zIndex = 100;
window.parent.document.body.appendChild(htmlElement);

// start up check
window.setTimeout(function() { tick() }, 1);


check_and_run();

function check_and_run() {
  // execute the order if health is above 10
  health_tag = document.getElementById('app17326627347_main');
  if ( health_tag == null) return;
  str = (new RegExp('體力:[^<]+')).exec(health_tag.innerHTML);
  if (str == null) return null;
  health = parseInt(str.toString().split(':')[1].split('/')[0]);
  if (health < 10) return health;
  action = document.getElementById('app17326627347_mod_action-5');
  if (action == null) return health;
  action_link = action.getElementsByTagName('a')[0];
  if (action_link == null) return health;

  // simulate click
  GM_setValue('reload', 1);
  var evt = document.createEvent("MouseEvents");
  evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
  action_link.dispatchEvent(evt);
  return health
}


function tick() {
  current = new Date();
  seconds = (current - last_check) / 1000;

  health = check_and_run();

  // display 
  htmlElement.innerHTML = '古惑自動做嘢機 v1.0<br />by neo@orz.hk<br /><a href=http://orz.hk target=_blank>http://orz.hk</a>' 
	+ '<br />上次reload:' + last_check.getHours() + ':' 
	+ last_check.getMinutes() + ':' 
	+ last_check.getSeconds() +
	'<br />尚餘時間: ' + (check_interval - Math.round(seconds)) + '秒';
  if (health != null)
    htmlElement.innerHTML += '<br />體力: ' + health;


 
  // reload the page if nesscary
  if (seconds > check_interval) {
    // check if is in error page
    if (document.getElementById('error_message') != null) {
      location.href='http://apps.facebook.com/street-wars/job.php';
      return;
    }


    // execute the order if health is above 10

    if (GM_getValue('reload') == 1) {
      location.href='http://apps.facebook.com/street-wars/job.php';
      GM_setValue('reload', 0);
    } else {
      location.reload();
    }  
  }

  // come back again every second, looks cool
  window.setTimeout(function() { tick()}, 1000);
}
