// ==UserScript==
// @name           Gmail Check Mail Now 
// @author         Daniel Slaughter
// @namespace      http://www.danielslaughter.com/
// @description    Automatically pulls in 3rd party POP3 accounts a set time interval.
// @include        http*://mail.google.com/*
// ==/UserScript==

// Last updated 1/15/2010.

function init(gmail) {
	// Change this number to how often (in minutes) you'd like it to check. 
	// Set it to 0 if you don't want it to automatically check. The link will still be in the top left.
	var checkEvery = 10; 
	
	// Don't play with anything under this unless you know what you're doing:
	var milliseconds = new Date();
	var label = '';
	milliseconds = Date.UTC(milliseconds.getYear(),milliseconds.getMonth(),milliseconds.getDate(),milliseconds.getHours(),milliseconds.getMinutes(),milliseconds.getSeconds());
	function fetchPopMail() {
		label.setAttribute('class','');
		label.innerHTML = 'Checking...';
		var d = new Date();
		var tempHash = top.location.hash;
		milliseconds = Date.UTC(d.getYear(),d.getMonth(),d.getDate(),d.getHours(),d.getMinutes(),d.getSeconds());
		top.location.hash = '#settings/accounts';
		do {
		} while (top.location.hash != '#settings/accounts')
		window.setTimeout(function() {
			var el2 = gmail.getActiveViewElement().getElementsByTagName('span');
			for(var j=0;j<el2.length;j++) {
				if (el2[j].innerHTML == 'Check mail now') {
					var evt2 = document.createEvent("HTMLEvents");
					evt2.initEvent('click', true, true); // event type, bubbling, cancelable
			        el2[j].dispatchEvent(evt2);
				}
			}
			top.location.hash = tempHash;
			label.innerHTML = 'Check POP3 now';
			label.setAttribute('class','e');
		},1000);
		return false;
	};
	function timerPopMail() {
		var d = new Date();
		if (checkEvery > 0 && milliseconds < (Date.UTC(d.getYear(),d.getMonth(),d.getDate(),d.getHours(),d.getMinutes(),d.getSeconds()))-(checkEvery*60000)) {
			fetchPopMail();
		}
		window.setTimeout(function() {
			timerPopMail();
		},15000);
	};
	timerPopMail();
	var header = gmail.getMastheadElement().getElementsByTagName('nobr');
	label = document.createElement('a');
	label.setAttribute('class', 'e');
	label.setAttribute('id', 'pop3fetch');
	label.innerHTML = 'Check POP3 now';
	label.addEventListener('click', function() {
		fetchPopMail();
	},true);
	header[1].innerHTML += ' | ';
	header[1].appendChild(label);
	label = gmail.getMastheadElement().getElementById('pop3fetch');
	alert(label);
	gmail.getMastheadElement().getElementById('pop3fetch').onclick = function() {
		alert('hi');
	};
}
window.addEventListener('load', function() {
	if (unsafeWindow.gmonkey) {
		unsafeWindow.gmonkey.load('1.0', init)
	}
}, true);