// ==UserScript==
// @name            AutoPost2del.icio.us
// @namespace       http://proto.jp
// @description     AutoPost2del.icio.us
// @include         http://*
// @exclude         http://mail.google.com/*
// @version			0.7
// ==/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.Config = {};


////////////////////////////////////////////////	
	if(GM_getValue("LogObj")== undefined)
	{
		GM_setValue("LogObj",'{"URLs":{"'+PO.url+'" : '+0+'}}')
	}
	else
	{
		PO.LogObj = eval("("+ GM_getValue("LogObj")+")");
	}
	
	if(GM_getValue("Config")== undefined)
	{
		GM_setValue("Config" , 30);
		PO.Config.minPostTime = 30;
	}
	else
	{
		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("setConfig",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("LastTime" , t);
			
			
	}
	PO.TimeCheck();

////////////////////////////////////////////////
	PO.hA2J = function(ha)
	{	
		var j="";
		
		for( i in ha)
		{
			j += '"'+ i +'":"'+ ha[i]+'",';
		}
		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);
	
	//PO.onFlg = false;
	d2.addEventListener("blur",function()
	{
		if(PO.onFlg == false)
		{
			
			
			PO.onFlg = true;
			PO.cEnd();
		}
	},false);

////////////////////////////////////////////////
	PO.iSearch = function ()
	{
		if(PO.LogObj.URLs[PO.url])
		{
			
			return true;//中urlにあったら
		}
		
		
		return false;//
	}
////////////////////////////////////////////////
PO.mSearch = function()
	{
		var f = PO.iSearch();
		
		if(f == false && PO.url == GM_getValue("TmpURL"))
		{
		
			PO.LogObj.URLs[PO.url]=0;

			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 == false)
		{
			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);

////////////////////////////////////////////////
if(PO.mSearch())
{
	this.blur();
	this.focus();
	
}

//////////////////////////////////////////////
  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;
	}
	
//del.icio.us post/////////////////////////////////////////////
	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);
			  }

//////////////////////////////
	d2.addEventListener("unload",function()
	{
		PO.LogObj = eval("("+ GM_getValue("LogObj")+")");
		if(PO.iSearch()==false){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);
		
	},false);


})();
