// AdSense Click Protection
// Version 0.2
// Copyright (C) 2009 Otto de Voogd
// Released under the GNU General Public License, version 3
// http://www.gnu.org/licenses/gpl.html

// ==UserScript==
// @name          AdSense Click Protection
// @namespace     http://www.7is7.com/software/firefox/
// @description   Protects your adsense account from accidental clicks
// @include       http://googleads.g.doubleclick.net/*
// ==/UserScript==

var l = document.location.href;
var asked = false;

// Messages
var confirm_id_msg = "Do you want to protect the AdSense ID on this page from clicks by you?";
var already_set_msg = "This AdSense ID is already protected!";
var nothing_to_clear_msg = "You are currently not protecting any AdSense ID!";
var clear_id_msg = "Are you sure you want to remove protection for the current AdSense ID?";
var aid_label = "\n\nAdSense ID = ";

function setAdsenseId() {
	asked=true;
	var new_aid = l.match(/client=ca-[^&]+/)[0].replace(/client=ca-/,"");
	if ( new_aid && new_aid.length>3 ) {
		var cur_aid=GM_getValue('adsense_id','n/a');
		if ( cur_aid == new_aid ) {
			alert(already_set_msg+aid_label+cur_aid);
		} else if ( confirm(confirm_id_msg+aid_label+new_aid) ) {
			GM_setValue('adsense_id',new_aid);
			protect_ads();
		}
	}
}

function clearAdsenseId() {
	var adsense_id = GM_getValue('adsense_id','');
	if ( adsense_id.length <= 3 ) {
		alert(nothing_to_clear_msg);
	} else if ( confirm(clear_id_msg+aid_label+adsense_id) ) {
		GM_setValue('adsense_id','');
	}
}

function mouseEvent(e) {
	e.stopPropagation();
	e.preventDefault();
	var a=e.target.parentNode;
	if (e.type=='mouseup' && a.href && e.button==0 && /dashed/.test(a.style.borderStyle)) {
		top.location.href=e.target.parentNode.href.replace(/&nm=[0-9]+$/,'');
	}
}

function protect_ads() {
	var adsense_id = GM_getValue('adsense_id','');
	if ( adsense_id.length > 3 && l.indexOf(adsense_id) > 3 ) {
		links = document.getElementsByTagName('a');
		for (var i = 0; i < links.length; i++) {
			a=links[i];
			if ( /googleads.g.doubleclick.net/.test(a.href) ) {
				a.href=decodeURIComponent(a.href.replace(/^.*&adurl=/,'').replace(/&.*$/,''));
				if ( !( /googleads.g.doubleclick.net/.test(a.href) ) ) {
					a.style.backgroundColor='#9ACD32';
					a.style.borderWidth='thin';
					a.style.borderStyle='dashed';
					a.style.borderColor='#006400';
					a.style.textDecoration='none';
				}
			}
		}
		document.addEventListener('click',function(event){mouseEvent(event);},true);
		document.addEventListener('mousedown',function(event){mouseEvent(event);},true);
		document.addEventListener('mouseup',function(event){mouseEvent(event);},true);
	} else if ( adsense_id.length <= 3 && !asked ) {
		setAdsenseId();
	}
}

protect_ads();

GM_registerMenuCommand('Set AdSense ID',setAdsenseId);
GM_registerMenuCommand('Clear AdSense ID',clearAdsenseId);


// TIAF!
