// ==UserScript==
// @name           AutoProxy
// @namespace      www.daddy.sk
// @description    Automaticaly redirects to proxied pages when detects one forbidden by the proxy
// @include        *
// ==/UserScript==

debugMode		= false;

// Log the message to the console if debugging is turned on (debugMode variable)
function log(msg) {
	if (debugMode) {
		GM_log(msg);
	}	
}

function xPath(query, doc) {
    var xResult, arrResult = [];
	if (!doc) {
		doc = document;
	}
	xResult = document.evaluate(query, doc, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);	
	for (i = 0; item = xResult.snapshotItem(i); i++) {
		arrResult.push(item);
	}
	return arrResult;
}

if (-1 != (window.location.hostname.indexOf('www.cantbustme.com'))) {
	testResult = xPath("//body/div[@id='error']/p[contains(text(),'proxy from a remote Website')]");
	if (testResult.length = 1) {
		document.getElementById('search').value = GM_getValue('redirectUrl', 'http://gm.daddy.sk');
		document.getElementById('form').submit();
	}
}

testResult = xPath("//body/ul[2]/li/p[contains(text(),'Access control')]|//*[text()='Server encountered an internal error.']");
log(testResult.length);

if (testResult.length != 1) {
	exit;
}

log(testResult[0].innerHTML);

formDiv = document.createElement('div');
formDiv.innerHTML = "<form method=\"post\" id = \"redirectForm\"action=\"http://www.cantbustme.com/surf.php\"> " +
"<input name=\"q\" value=\"\" id=\"sinput\" type=\"text\"> " +
"<input name=\"hl[include_form]\" value=\"1\" type=\"hidden\"> " +
"<input name=\"hl[remove_scripts]\" value=\"1\" type=\"hidden\"> " +
"<input name=\"hl[accept_cookies]\" value=\"1\" type=\"hidden\"> " +
"<input name=\"hl[show_images]\" value=\"1\" type=\"hidden\"> " +
"<input name=\"hl[show_referer]\" value=\"1\" type=\"hidden\"> " +
"<input name=\"hl[strip_meta]\" value=\"1\" type=\"hidden\"> " +
"<input name=\"hl[session_cookies]\" value=\"1\" type=\"hidden\"> " +
"</form> ";

testResult[0].appendChild(formDiv);

document.getElementById('sinput').value = window.location.toString();
GM_setValue('redirectUrl', window.location.toString());
document.getElementById('redirectForm').submit();
