//  pkFusemail 0.8
//  2009-05-11
//  (c) 2006-2009, Pooya Karimian
//  http://pooyak.com/p/pkfusemail/
// This script is licensed under GPL.
//
// ==UserScript==
// @name		pkFusemail
// @namespace	http://www.pooyak.com/p/pkfusemail/
// @description	pkFusemail
// @include		https://webmail.fusemail.com/*webmail.php
// @include		https://webmail.mailanyone.net/*webmail.php
// @include		https://webmail.fusemail.com/*webmail.php?Menu=Mail
// @include		https://webmail.mailanyone.net/*webmail.php?Menu=Mail
// ==/UserScript==

// pkUpdate 0.1 
// pkUpdate - start
var pkfu_version='0.8';
pkupdate_check('pkFusemail',pkfu_version); // Comment this line with a // if you want to disable the auto-update feature
function pkupdate_check(pk_scriptname, pk_ver) {
	var current_time=(new Date().getTime()) / 1000;
	var last_time=GM_getValue('pkUpdate_lastupdate');
	if (!last_time) 
		last_time=0 
	if (current_time-last_time<2*3600) 
		return;
	GM_setValue('pkUpdate_lastupdate',current_time.toString());

	GM_xmlhttpRequest({
		method: 'GET',
		url: 'http://www.pooyak.com/p/pkupdate/?n='+escape(pk_scriptname)+'&v='+escape(pk_ver),
		headers: {
			'User-agent': 'Mozilla/4.0 (compatible) pkUpdate',
		},
		onload: function(responseDetails) {
			if(responseDetails.status==200) {
				var t=responseDetails.responseText;
				var data_array=t.split(/\n/);
				if (data_array[0]!='PKUPDATEAVAILABLE') 
					return;
				
 				var r=confirm('A new update is available for '+pk_scriptname+
							' Greasemonkey script\n'+
							'Proceed to the update it at '+data_array[1]+'?\n'+data_array[2]);
				if (r==true) {
					//window.location=data_array[1];
					GM_openInTab(data_array[1]);
				}
		    }
		}
	});
}
// pkUpdate - end

if (!unsafeWindow.DoThis) {
	return;
}

pk_injectscript('var pk_junk_url="asldkjfklaadsfsdjflkadsjf";');
	
//unsafeWindow.pk_filter=function (xmldata) {
var pk_filter=function (xmldata) {
	var content=xmldata.responseText;
	
//	content='<div>http://www.pooyak.com<style>http://www.yahoo.com/</style></div>';
//	alert(content);
//	content='test';
	content=content.replace(/(https*:\/\/)/ig,pk_junk_url+'$1');

	var range = document.createRange();
	range.selectNode(document.documentElement);
	var frag = range.createContextualFragment('<div edAttr>' + content + '</div>');
	var newDiv = document.createElement('div');
	newDiv.style.display = 'none';
	newDiv.appendChild(frag);
	document.body.appendChild(newDiv);

//	var ellist=document.evaluate('//*[ancestor::div[@edAttr]][text()[contains(.,"'+pk_junk_url+'")]]', document, null, XPathResult.ANY_TYPE, null);
	var ellist=document.evaluate('//*[ancestor::div[@edAttr] and not(self::style)]/text()', document, null, XPathResult.ANY_TYPE, null);
	var el;
	var elArray=new Array();
	while (el=ellist.iterateNext()) {
		elArray[elArray.length]=el;
	}
	
	for (i=0;i<elArray.length;i++) {
		blockedContent=true;
		elArray[i].data=elArray[i].data.replace(new RegExp(pk_junk_url,"g"),'');
//		elArray[i].innerHTML=elArray[i].innerHTML.replace(new RegExp(pk_junk_url,"g"),'');
	}

	var ellist=document.evaluate('//a[ancestor::div[@edAttr]][@href[contains(.,"'+pk_junk_url+'")] | @title[contains(.,"'+pk_junk_url+'")]]', document, null, XPathResult.ANY_TYPE, null);
	var el;
	var elArray=new Array();
	while (el=ellist.iterateNext()) {
		elArray[elArray.length]=el;
	}
	for (i=0;i<elArray.length;i++) {
		if (elArray[i].href) {
			elArray[i].href=elArray[i].href.replace(new RegExp(pk_junk_url,"g"),'');
		}
		if (elArray[i].title) {
			elArray[i].title=elArray[i].title.replace(new RegExp(pk_junk_url,"g"),'');
		}
	}

	var ellist=document.evaluate('//img[ancestor::div[@edAttr]][@src[contains(.,"'+pk_junk_url+'")]]', document, null, XPathResult.ANY_TYPE, null);
	var el;
	var elArray=new Array();
	while (el=ellist.iterateNext()) {
		elArray[elArray.length]=el;
	}

	content=newDiv.getElementsByTagName('div')[0].innerHTML;

//	if (elArray.length>0) {
	if (content.match(new RegExp(pk_junk_url,"g"))) {
		content='<div><div style="background: #FFFF80; padding: 0.5em; text-size: 1.1em;">WARNING: Remote images are blocked! &nbsp;&nbsp;&nbsp; <input type="button" class="formelement" onclick="pk_unfilter(event)" value="Show Images"> <input type="button" class="formelement" onclick="pk_hide(event)" value="Hide"></div>'+content+'</div>';
	}

	document.body.removeChild(newDiv);
	return content;
//	return '<xmp>'+content+'</xmp>';

};
pk_injectfunc('pk_filter', String(pk_filter));


var pk_unfilter=function (e) {
	var topel=e.target.parentNode;
	var msgel=e.target.parentNode.nextSibling;
	msgel.innerHTML=msgel.innerHTML.replace(new RegExp(pk_junk_url,"g"),'');

/*
	var ellist=document.evaluate('//img[@src[contains(.,"'+pk_junk_url+'")]]', msgel, null, XPathResult.ANY_TYPE, null);
	var el;
	var elArray=new Array();
	while (el=ellist.iterateNext()) {
		elArray[elArray.length]=el;
	}
	for (i=0;i<elArray.length;i++) {
		elArray[i].src=elArray[i].src.replace(new RegExp(pk_junk_url,"g"),'');
	}
*/
//	unsafeWindow.pk_hide(e);
	pk_hide(e);
};
pk_injectfunc('pk_unfilter', String(pk_unfilter));

var pk_hide=function (e) {
	var topel=e.target.parentNode;
	topel.style.display='none';
};
pk_injectfunc('pk_hide', String(pk_hide));

var DT=unsafeWindow.DoThis;
var DT2=DT.toString();
DT2=DT2.replace('function DoThis(','function (');
DT2=DT2.replace(/(if \(DoCache == 0\) \{)/g,'$1 data=pk_filter(xmldata); ');
DT2=DT2.replace(/(xmldata\.responseText)/g,'data');
pk_injectfunc('DoThis', DT2);

var CM=unsafeWindow.ChangeMsg;
var CM2=CM.toString();
CM2=CM2.replace('function ChangeMsg(','function (');
CM2=CM2.replace(/(if \(DoCache == 0\) \{)/g,'$1 data=pk_filter(xmldata); ');
CM2=CM2.replace(/(xmldata\.responseText)/g,'data');
//document.getElementById("PreviewPane").innerHTML=CM2;
//unsafeWindow.ChangeMsg=unsafeWindow.eval(CM2);
pk_injectfunc('ChangeMsg', CM2);

var AV=unsafeWindow.AttachView;
var AV2=AV.toString();
AV2=AV2.replace('function AttachView(','function (');
AV2=AV2.replace(/(function \(xmldata\) \{)/g,'$1 data=pk_filter(xmldata); ');
AV2=AV2.replace(/(xmldata\.responseText)/g,'data');
//unsafeWindow.AttachView=unsafeWindow.eval(AV2);
pk_injectfunc('AttachView', AV2);

var MVD=unsafeWindow.MoveDetection;
var MVD2=MVD.toString();
MVD2=MVD2.replace('function MoveDetection(','function (');
MVD2=MVD2.replace('if (MoveThisID != "") {','if(MoveThisID != "") {  if (y<0) y=0; ');
//unsafeWindow.MoveDetection=unsafeWindow.eval(MVD2);
pk_injectfunc('MoveDetection', MVD2);


//document.addEventListener('mousemove',unsafeWindow.MoveDetection,false);
pk_injectscript('document.onmousemove = window.MoveDetection; ');

if (/^Mac/.test(navigator.platform)) {
	var KCD=unsafeWindow.KeyClickDetect;
	var KCD2=KCD.toString();
	KCD2=KCD2.replace('function KeyClickDetect(','function (');
	KCD2=KCD2.replace('} else if (mye.ctrlKey) {','} else if (mye.altKey) { ');
	pk_injectfunc('KeyClickDetect', KCD2);
	document.addEventListener('keydown',unsafeWindow.KeyClickDetect,false);
	document.addEventListener('keyup',unsafeWindow.KeyClickDetect,false);
}

var pk_timeout;
function pk_search_e(e) {
  var obj=e.target;
  if (pk_timeout) {
	clearTimeout(pk_timeout);
  }
  pk_timeout=setTimeout(function() {pk_do_search(obj.value);} ,1000);
}

function pk_do_search(sterm) {
	var mb=unsafeWindow.CurrentMailbox;
	
	unsafeWindow.Loading(1,"Searching "+mb);
	
	var ellist=document.evaluate('//tr[contains(@id,"row_msg")]', document.getElementById('TableMsgList'), null, XPathResult.ANY_TYPE, null);
	var elArray=new Array();
	while (el=ellist.iterateNext()) {
		elArray[elArray.length]=el;
	}
	for (i=0;i<elArray.length;i++) {
		var found=false;
		if (elArray[i].textContent.toLowerCase().indexOf(sterm)>=0) {
			found=true;
		} else {
			if(elArray[i].getElementsByTagName('td')[3].getElementsByTagName('a')[0].title.toLowerCase().indexOf(sterm)>=0) {
				found=true;
			}
		}
		
		if(found) {
			elArray[i].style.display='';
		} else {
			elArray[i].style.display='none';
		}
	}
	unsafeWindow.Loading(0,"Searching "+mb);
}

var ellist=document.evaluate('//td[@width="28%"]', document, null, XPathResult.ANY_TYPE, null);
var el=ellist.iterateNext();
el.innerHTML='Search: <input id="pk_search" size="8" class="formelement" type="text">&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:MessageAction(\'\',CurrentMailbox,\'delete\')"><img src="images/mail/deletechecked.gif" border="0" height="21" width="94" align="top"></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
var pk_search=document.getElementById('pk_search');
pk_search.addEventListener('keypress', pk_search_e,false);

function pk_keypress(e) {
	var obj=e.target;
	if (obj.tagName=='INPUT' || obj.tagName=='TEXTAREA') 
		return;
	if (e.ctrlKey || e.altKey || e.metaKey)
		return;
		
	// "v" toggle preview panel
	if(e.charCode==118) {
		if (unsafeWindow.OpenNewWindow=='Yes') {
			unsafeWindow.OpenNewWindow='No';
		} else {
			unsafeWindow.OpenNewWindow='Yes';
		}
		if (unsafeWindow.PreviewPane=='Yes') {
			unsafeWindow.PreviewPane='No';
		} else {
			unsafeWindow.PreviewPane='Yes';
		}
		unsafeWindow.DoSizeAdjust();
	}
	// "n" new mail 
	if(e.charCode==110) {
		if (unsafeWindow.openComposeInline==1) {
			unsafeWindow.CreateMail("EntireMsgList",undefined,1,unsafeWindow.ComposeFormat);
		} else {
			unsafeWindow.CreateMail(undefined,undefined,undefined,unsafeWindow.ComposeFormat);
//			unsafeWindow.CreateMail(undefined,undefined,undefined,'Text');
		}
	}
	// "f" find using quick search
	if (e.charCode==102) {
		document.getElementById('pk_search').value='';
		document.getElementById('pk_search').focus();
	}
	// "F" find using advanced search
	if (e.charCode==70) {
		unsafeWindow.ToggleSearch( 0,'');
		document.getElementById('searchquery1').focus();
	}
	// "C" clear preview panel
	if (e.charCode==67){
		var previewPane=document.getElementById('PreviewPane');
		if (previewPane) {
			previewPane.innerHTML='<br><center>There is no message selected.</center>';
		}
	}
}

document.addEventListener('keypress', pk_keypress,false);

function pk_injectscript(scripttxt) {
    var script = document.createElement( 'script' );
    script.setAttribute( 'type', 'text/javascript' );
    script.innerHTML = scripttxt;
    document.body.appendChild( script );
}

function pk_injectfunc(fname, script) {
	pk_injectscript('window.'+fname+' = ' + script + "; \n");
}

