//  msDictionary 1.3.1
//  2006-04-27
//  (c) 2006, Mohammad Ali Safari
//  http://www.cs.ubc.ca/~safari
// This script is licensed under GPL.
//
// ==UserScript==
// @name          msDictionary
// @namespace     http://sharifiha.com/dictionary
// @description	  English2Persian Dictionary
// @exclude http://*.js
// ==/UserScript==




//To add new users first create them at http://sharifiha.com/greasemonkey/dictionary/createuser.php
//It should look like new Array("x", "y", "z", ...) where x, y, x, .. are your created IDs.
var msDictionary_ids=new Array("testuser");























////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////

GM_setValue('msDictionary_version', '1.3.1');
if (GM_getValue('msDictionary_id',-1)==-1)
	GM_setValue('msDictionary_id',1);



////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////

var firstTime = GM_getValue('msdictionary_v'+GM_getValue('msDictionary_version'));

if (!firstTime){ //First Time Visiting This Page
	var r=confirm('Check new features in the new version of msDictionary?');
	GM_setValue('msdictionary_v'+GM_getValue('msDictionary_version'), 'no')
	if (r==true) 
		location.href='http://moham.blogfa.com/post-13.aspx';


};


////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////

// msUpdate - start
//msupdate is based on pkUpdate (c)2006 pooya karimian (http://pooyak.com/p/pkorkut/)
msupdate_check('msDictionary',GM_getValue('msDictionary_version')); // Comment this line with a // if you want to disable the auto-update feature
function msupdate_check(ms_scriptname, ms_ver) {
	var current_time=(new Date().getTime()) / 1000;
	var last_time=GM_getValue('msUpdate_lastupdate');
	if (!last_time) 
		last_time=0 
	if (current_time-last_time<2*3600) 
		return;
	GM_setValue('msUpdate_lastupdate',current_time.toString());

	GM_xmlhttpRequest({
		method: 'GET',
		url: 'http://sharifiha.com/greasemonkey/check.php?n='+escape(ms_scriptname)+'&v='+escape(ms_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]!='MSUPDATEAVAILABLE') 
					return;
				
 				var r=confirm('A new update is available for '+ms_scriptname+
							' Greasemonkey script\n'+
							'Proceed to the update it at '+data_array[1]+'?\n'+data_array[2]);
				if (r==true) {

					var cnt = 1;
					var txt='';
					for (x in msDictionary_ids){
						if (cnt > 1)
							txt = txt + '__'+ msDictionary_ids[x];
						else
							txt = txt + msDictionary_ids[x];
						cnt++;
					};

					window.location='http://sharifiha.com/greasemonkey/genScript.php?n=msDictionary&IDS='+txt;
				}
		    }
		}
	});
}
// msUpdate - end








////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////












function Trim(sString){
	while (sString.substring(0,1) == ' '){
	sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == ' '){
		sString = sString.substring(0,sString.length-1);
	}
	return sString;

};

function remove()
{
	var adSidebar = document.getElementById('ddd1');
	
	if (adSidebar) 
		adSidebar.innerHTML = '';
}




////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////



function onKeyDown(e)
{   




    var code =  e.keyCode?e.keyCode:e.charCode;
    var id=GM_getValue('msDictionary_id');
    if (id > 0)
	id = msDictionary_ids[id-1];
    else
	id = '';

	//%%%%%%%%%%%%%%%%%%%%%
    if (e.ctrlKey && (code==88)){  //Ctrl-X for changing user name


		if (id  == '')
			id = 'no one';
		var txt = 'Current ID:'+id + '\n Choose ID. 0:no one ';;
		
		
		var cnt = 1;
			for (x in msDictionary_ids){
			txt = txt + cnt +':'+ msDictionary_ids[x]+' ';
			cnt++;
		};

		id = prompt(txt);
		if (id) GM_setValue('msDictionary_id',id);

	

	};

	//%%%%%%%%%%%%%%%%%%%%%


    if (e.ctrlKey && (code==90)){  //Ctrl-Z for viewing the dictionary

		if (id!='')
			location.href='http://sharifiha.com/greasemonkey/dictionary/showwords.php?id='+id;
	else
		alert('You do not have an active user-id. Please activate your user-id by pressing Ctrl-X   or, in case you do not have a user-id, go to  http://sharifiha.com/greasemonkey/dictionary/createuser.php to create a user-id first');
	

	};

	//%%%%%%%%%%%%%%%%%%%%%
    if (e.ctrlKey && (code==89)){  //Ctrl-Y for removing a word

		var val = Trim(window.getSelection().toString());
		if (id != '')
	            GM_xmlhttpRequest({
        	        method: 'POST',
                	url: 'http://sharifiha.com/greasemonkey/dictionary/addword.php',
	                headers: {
        	        'Content-type':'application/x-www-form-urlencoded',
                	    'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey',
	                    'Accept': 'application/atom+xml,application/xml,text/xml',
        	        },
	            data:'op=remove&id='+id+'&word='+val
	        });

		var txt = val + ' Removed!';
		if (document.getElementById('ddd1'))
			document.getElementById('ddd1').innerHTML = txt
		else{
			var logo = document.createElement('div');
	
			logo.innerHTML ='<div id="ddd1" STYLE="  border-width: 1px;  border-color: #0000ff;  border-style: solid;  background-color:#e5ecf9;  font-family: Tahoma;   color:black; font-size: 11pt;  position:absolute; top:300; left:0; z-index:10">' +  
					txt + '</div>';
			document.body.insertBefore(logo, document.body.firstChild);
		};
		var px = window.pageYOffset.toString()+'px';
		document.getElementById('ddd1').style.top = px;
		setTimeout(remove, 4000);

	};


	//%%%%%%%%%%%%%%%%%%%%%




    if (e.ctrlKey && (code==81)){  //Ctrl-Q for adding a word

	var val = Trim(window.getSelection().toString());

	GM_xmlhttpRequest({
	    method: 'POST',
	    url: 'http://www.math.columbia.edu/~safari/masood/cgi-bin/dict.cgi',
	    headers: {
		'Content-type':'application/x-www-form-urlencoded',
	        'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey',
        	'Accept': 'application/atom+xml,application/xml,text/xml',
	    },
	    data:'font=4&face=40&faced=40&DFn=0&PSearch=Persian&words='+val,
						
	    onload: function(responseDetails) {
		var txt = responseDetails.responseText.split("size=+2>")[1]
		if (!txt)
			txt = 'Word Not Found!';
		else
			txt = txt.split("</tr>")[0];
		if (!txt)
			txt = 'Word Not Found!';

		var txt2 = '<font color=red size=\'1pt\'>(' +id+ ')</font>'+val + ':' + txt;




		if (document.getElementById('ddd1'))
			document.getElementById('ddd1').innerHTML = txt2
		else{
			var logo = document.createElement('div');
	
			logo.innerHTML ='<div id="ddd1" STYLE="  border-width: 1px;  border-color: #0000ff;  border-style: solid;  background-color:#e5ecf9;   color:black; font-family: Tahoma;   font-size: 11pt;  position:absolute; top:300; left:0; z-index:10">' +  
					txt2 + '</div>';
			document.body.insertBefore(logo, document.body.firstChild);
		};
		var px = window.pageYOffset.toString()+'px';
		document.getElementById('ddd1').style.top = px;
		setTimeout(remove, 4000);


		txt = escape(encodeURI(txt));
        	if (id != '')
	            GM_xmlhttpRequest({
        	        method: 'POST',
                	url: 'http://sharifiha.com/greasemonkey/dictionary/addword.php',
	                headers: {
        	        'Content-type':'application/x-www-form-urlencoded',
                	    'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey',
	                    'Accept': 'application/atom+xml,application/xml,text/xml',
        	        },
	            data:'id='+id+'&meaning='+txt+'&word='+val
	        });

				   

	    }
	});

   };

	//%%%%%%%%%%%%%%%%%%%%%


}






window.addEventListener('keydown',onKeyDown,false);
