// ==UserScript==
// @name            AutoPost2del.icio.us
// @namespace       http://proto.jp
// @description     AutoPost2del.icio.us
// @include         http://*
// @exclude         http://mail.google.com/*
// @version			0.75
// ==/UserScript==

(function(){
	
	var d2 = unsafeWindow;
	var PO ={};

	PO.url = d2.document.URL;
	PO.time = 0;
	PO.timeTmp = 0;
	PO.cFlg = false;
	PO.loadFlg = false;
	PO.rankArr = [30,90,150,210,300,600,900,1200,1800,2700,3600];
	PO.LogObj = {};
	PO.FrameObj = {};
	PO.Config = {};

	if(!GM_getValue("LogObj"))
	{
		GM_setValue("LogObj",'{"URLs":{"'+PO.url+'" : '+0+'}}')
	}

	PO.LogObj = eval("("+ GM_getValue("LogObj")+")");
	
	
	if(!GM_getValue("Config"))
	{
		GM_setValue("Config" , 30);
		PO.Config.minPostTime = 30;
	}
	
	PO.Config.minPostTime = GM_getValue("Config");

	PO.setConfig =  function(){
		var setC = prompt("input post min time!(sec)",GM_getValue("Config"));
		
		if( setC.match( /[^0-9]+/ ) )
		{
			alert("Number only")
			PO.setConfig();
		}
		else
		{
			setC = Number(setC);
			GM_setValue("Config" , setC);
			PO.Config.minPostTime = setC;
		}
	};
	
	GM_registerMenuCommand("AutoPost2del.icio.us",PO.setConfig);
	

	PO.TimeCheck = function()
	{
			var d = new Date();
			var t = Math.floor(d.getTime()/1000);
			
			if(t>GM_getValue("LastTime")+21600)
			{			
				GM_setValue("LogObj",'{"URLs":{"'+PO.url+'" : '+0+'}}')
				PO.LogObj = eval("("+ GM_getValue("LogObj")+")");
				
				GM_setValue("FrameObj","");
			}
			GM_setValue("LastTime" , t);
	}
	PO.TimeCheck();

	PO.hA2J = function(ha)
	{	
		var j="";
		
		for( i in ha)
		{
			typeof eval(ha[i])=="object"	?	j += '"'+ i +'":'+ ha[i]+','
											:	j += '"'+ i +'":"'+ ha[i]+'",';
		}
		j = j.slice(0,-1);
		
		return "{"+ j +"}";
	}

	PO.A2J = function(a)
	{	
		var j="";
		
		for(i=0;i<a.length;i++)
		{
			j += '"'+a[i]+'",';
		}
		j = j.slice(0,-1);
		
		return "["+ j +"]";
	}

	PO.cStart = function()
	{		
			var d = new Date();
			PO.timeTmp = Math.floor(d.getTime()/1000);
			PO.cFlg = true;
	}

	PO.cEnd = function()
	{
			var d = new Date();
			PO.time += Math.floor(d.getTime()/1000)-PO.timeTmp;

			PO.LogObj.URLs[PO.url] = PO.time;
			
			var s = '{"URLs":' + PO.hA2J(PO.LogObj.URLs) + '}' ;
			GM_setValue("LogObj",s);
			
			PO.cFlg = false;
	}

	PO.onFlg = true;
	
	d2.addEventListener("focus",function()
	{
		if(PO.onFlg == true)
		{
			PO.onFlg = false;
			PO.cStart();
		}
	},false);

	d2.addEventListener("blur",function()
	{
		if(!PO.onFlg)
		{
			PO.onFlg = true;
			PO.cEnd();
		}
	},false);

	PO.iSearch = function ()
	{
		if(PO.LogObj.URLs[PO.url])
		{
			return true;
		}

		return false;
	}

PO.mSearch = function()
	{
		var f = PO.iSearch();
		
		if(!f && PO.url == GM_getValue("TmpURL"))
		{
			PO.LogObj.URLs[PO.url]=0;
			
			//LogObj‚É’Ç‰Á
			var s = '{"URLs":' + PO.hA2J(PO.LogObj.URLs) + '}' ;
			GM_setValue("LogObj",s);

			return true;
		}
		else if(f)
		{
			PO.time = Number(PO.LogObj.URLs[PO.url]);

			return true;
		}
		else if(!d2.document.referrer)
		{
			PO.LogObj.URLs[PO.url]=0;

			var s = '{"URLs":' + PO.hA2J(PO.LogObj.URLs) + '}' ;
			GM_setValue("LogObj",s);

			return true;
		}
		
		return false;
	}

d2.addEventListener("click",function(e)
	{		
		GM_setValue("TmpURL", e.target.toString() );
		
	}, true);

  var complementDate = function(s){
    return (s < 10) ? '0' + s : s;
  };
  Date.prototype.getW3CDTF = function(){
    var Y = this.getFullYear();
    var m = complementDate(this.getUTCMonth() + 1);
    var d = complementDate(this.getUTCDate());
    var H = complementDate(this.getUTCHours());
    var i = complementDate(this.getUTCMinutes());
    var s = complementDate(this.getUTCSeconds());
	
    return Y + "-" + m + "-" + d + "T" + H + ":" + i + ":" + s + "Z";
  };
	
	PO.s2m = function(s)
	{
		var a0;
		var a1 = Math.floor(s/60);
		if(a1>59)
		{
			a0 = Math.floor(s/3600);
			a1 =a0 + "h" +Math.floor((s%3600)/60);
			s=s%3600;
		}
		
		var a2 = s%60;

		return a1 + "m" +a2 + "s";
	}

	PO.s2r = function(s)
	{
		var i =0;
		
		while(s>PO.rankArr[i])
		{
			i++;
			if(i>PO.rankArr.length){break;};
		}
		
		return "ReadRank_"+ i;
	}

	var REST = function() {};
	    REST.prototype = {
	      makeURI : function(baseURI, queries) {
	        var query = [];
	        for(q in queries){
	          if(queries.hasOwnProperty(q)){
	            query.push(q + "=" + encodeURIComponent(queries[q]));
	          }
	        }
	        var uri = baseURI + "?" + query.join("&");
	        return uri;
	      },
		  
	      post : function(method, baseURI, queries) {
	        GM_xmlhttpRequest({
	            method : method,
	            url    : this.makeURI(baseURI, queries),
	            onload : function(response) {
	              var status = "del.icio.us: " + 
	              [response.status, response.statusText].join(' - ');

	            }
	          });
	      }
		  
	    };
		
	var rest = new REST();
			
	PO.addPost_delicious = function(){
				
				
				var title = document.title;
		        if(!title){title = PO.url;}
				var tags = PO.s2r(PO.time);
				var comment="Read:"+ PO.s2m(PO.time);
				
	            var queries = {
	              url         : PO.url,
	              description : title,
	              tags        : tags,
	              extended    : comment.replace(/^\s+|\s+$/, ""),
	              dt          : (function() {
	                  var date = new Date();
	                  return date.getW3CDTF();
	                })()
	            };
				
				//rest.post("get", ["https://",config.data["delicious username"],":",config.data["delicious password"],"@api.del.icio.us/v1/posts/add"].join(""),queries);
	           	rest.post("get", "http://del.icio.us/api/posts/add",queries);
			  };


(function(){
	
	var a =[];
	var f ={};
	
	if(d2.document.getElementsByTagName("frame"))
	{
		f = d2.document.getElementsByTagName("frame");
		for(var i=0;i<f.length;i++)
		{
			a.push(f[i].src);
		}
	}
	
	if(d2.document.getElementsByTagName("iframe"))
	{
		f = d2.document.getElementsByTagName("iframe");
		for(var i=0;i<f.length;i++)
		{
			a.push(f[i].src);
		}
	}

	
	if(a.length)
	{
		if(GM_getValue("FrameObj"))
		{
			PO.FrameObj = eval("("+ GM_getValue("FrameObj")+")");
		}
		
		PO.FrameObj[PO.url] = a;

		for( i in PO.FrameObj)
		{
			PO.FrameObj[i] = PO.A2J(PO.FrameObj[i]);
		}

		var s = PO.hA2J(PO.FrameObj);
		GM_setValue("FrameObj",s);
		
		
	}
})();

	d2.addEventListener("unload",function()
	{
		
		PO.LogObj = eval("("+ GM_getValue("LogObj")+")");
		if(!PO.iSearch()){return;}
		
		if(PO.cFlg)
		{
			
			PO.cEnd();
		}
		
		if(PO.time>PO.Config.minPostTime)
		{
			PO.addPost_delicious();
		}
		
		
		delete PO.LogObj.URLs[PO.url];

		var s = '{"URLs":' + PO.hA2J(PO.LogObj.URLs) + '}' ;
		GM_setValue("LogObj",s);

		if(GM_getValue("FrameObj"))
		{
			PO.FrameObj = eval("("+ GM_getValue("FrameObj")+")");
			
			if(PO.FrameObj[PO.url])
			{
				
				delete PO.FrameObj[PO.url];

				for( i in PO.FrameObj)
				{
					PO.FrameObj[i] = PO.A2J(PO.FrameObj[i]);
				}

				var s = PO.hA2J(PO.FrameObj);
				GM_setValue("FrameObj",s);
				
				
			}
		}
		
	},false);

if(PO.mSearch())
{
	this.blur();
	this.focus();
	
}
else
{
	d2.addEventListener("mouseover",function()
	{
			if(!GM_getValue("FrameObj"))
			{
				d2.removeEventListener("mouseover",arguments.callee,false);
				return;
			}
			
			PO.FrameObj = eval("("+ GM_getValue("FrameObj")+")");
			
			var f = true;
			if(PO.FrameObj[d2.document.referrer])
			{
				var r = PO.FrameObj[d2.document.referrer];
				for(i=0;i<r.length;i++)
				{
					if(r[i]==PO.url)
					{
						f = false;
						break;
					}
				}
			}
			
			if(f)
			{
				this.blur();
				this.focus();
			}
			this.removeEventListener("mouseover",arguments.callee,false);
	},false);
}


})();
