// ==UserScript==
// @name            AutoPost2del.icio.us
// @namespace       http://proto.jp
// @description     AutoPost2del.icio.us
// @include         http://*
// @exclude         http://mail.google.com/*
// @version			0.61
// ==/UserScript==

(function(){
	
	var d2 = unsafeWindow;
	var PO ={};
	
	PO.url = d2.document.URL;
	PO.time = 0;
	PO.timeTmp = 0;
	PO.click = false;
	PO.cFlg = false;
	PO.rankArr = [30,90,150,210,300,600,900,1200,1800,2700,3600];
	PO.LogObj = {};
	PO.Config = {};

	/*
	d2.document.ondblclick = function()
	{
		GM_setValue("LogObj",'{"URLs":{"'+PO.url+'" : '+0+'}}')
		alert("**AutoPost2delicious**\n\nLogFormat!")
	}
	*/
	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.iSearch = function ()
	{
		for(i in PO.LogObj.URLs)
		{
			if(PO.url == i)
			{
				
				return true;
			}
		}
		
		return false;
	}
	
	PO.TimeCheck = function()
	{
			var d = new Date();
			var t = Math.floor(d.getTime()/1000);
			
			if(t>GM_getValue("LastTime")+28800)
			{
				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;
	}


	d2.addEventListener("load",function()
	{
		this.blur();
		this.focus();
		var aTag = d2.document.getElementsByTagName("a");
		var aTagLength=0;
		var aTagFnc = function()
		{
			aTagLength = aTag.length;

			 for (var i=0,l=aTag.length; i<l; i++)
			 {
				aTag[i].addEventListener("mouseover",function()
				{
					GM_setValue("TmpURL",this.toString());
					
				}
				,false);
				
				aTag[i].addEventListener("click",function()
				{
					PO.click = true;
				}
				,false);
			}
		}
		aTagFnc();
		
		
		var intID = setInterval(function()
			{

				if(aTagLength != d2.document.getElementsByTagName("a").length)
				{
					aTag = d2.document.getElementsByTagName("a")
					aTagFnc();
				}
				else{ clearInterval(intID);}
				
			},2000)
			
	},false);



	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);
	}
	else if(f == false)
	{
		return;	
	}
	else
	{
		PO.time = Number(PO.LogObj.URLs[PO.url]);
	}


	PO.onFlg = true;
	
	d2.addEventListener("focus",function()
	{	
		if(PO.onFlg == true)
		{	
			PO.onFlg = false;
			PO.click = false;
			
			PO.cStart();
		}
	},false);
	
	
	d2.addEventListener("blur",function()
	{
		if(PO.onFlg == false)
		{
			PO.onFlg = true;
			PO.cEnd();
		}
	},false);
	


  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>9){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);
			  }


//ウィンドウを閉じたときの動作(再読み込み、次へ行った時も)
	d2.addEventListener("unload",function()
	{
		PO.LogObj = eval("("+ GM_getValue("LogObj")+")");
		if(PO.iSearch()==false){return;}
		
		if(PO.cFlg)
		{
			PO.cEnd();
		}
		
		if(PO.click)
		{
			return;
		}
		else 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);

})();
