// ==UserScript==
// @name            ReadMark
// @version			0.5
// @namespace       http://proto.jp
// @description     ReadMark
// @include         http://*
// @exclude         http://mail.google.com/*
// ==/UserScript==
// Version: 2006-06-06

(function(){
	
	var d2 = unsafeWindow;
	var PO ={};
	//初期化
	PO.maxN = 30;//全ログ数
	PO.nowN = 0;
	PO.url = d2.document.URL;
	PO.time = 0;
	PO.timeTmp = 0;
	PO.click = false;
	PO.cFlg = false;
	PO.rankArr = [30,60,120,180,300,600,900,1200,1800,2700,3600];
	PO.LogObj = {};
	PO.Config = {};

	d2.addEventListener("dblclick",function()
	{//ダブクリでログ初期化	
		GM_setValue("LogObj",'{"URLs":["'+PO.url+'"],"rTimes":[0]}')
	},false);
	
//Value処理//////////////////////////////////////////////	
	if(GM_getValue("LogObj")== undefined)
	{
		GM_setValue("LogObj",'{"URLs":["'+PO.url+'"],"rTimes":[0]}')
	}
	else
	{
		PO.LogObj = eval("("+ GM_getValue("LogObj")+")");
	}
	
	//config設定
	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 (var i=0, l=PO.LogObj.URLs.length; i<l; i++)
		{
			if(PO.url == PO.LogObj.URLs[i])
			{
				PO.nowN = i;
				return true;
			}
		}
		return false;//
	}

	PO.LO_a2j = function(arr)
	{
		var j = '"' + this.LogObj[arr][0] + '"';
		
		for(var i =1 ;i<this.LogObj[arr].length; i++)
		{
			j+= ","+ '"' + this.LogObj[arr][i] + '"';
		}
		return arr +":["+ 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 = eval("("+ GM_getValue("LogObj")+")");
			PO.iSearch();
			PO.LogObj.rTimes[PO.nowN] = PO.time;
			var s = "{"+ PO.LO_a2j("URLs") + "," + PO.LO_a2j("rTimes")+"}";
			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"))
	{
	
		if(PO.LogObj.URLs.length > PO.maxN-1)
		{
			PO.LogObj.URLs.shift();
			PO.LogObj.URLs.push(PO.url);
			PO.LogObj.rTimes.shift();
			PO.LogObj.rTimes.push(0);
		}
		else
		{
			PO.LogObj.URLs.push(PO.url);
			PO.LogObj.rTimes.push(0);
		}

		var s = "{"+ PO.LO_a2j("URLs") + "," + PO.LO_a2j("rTimes")+"}";
		GM_setValue("LogObj",s);
	}
	else if(f == false)
	{
		return;
	}
	else
	{
		PO.time = Number(PO.LogObj.rTimes[PO.nowN]);
	}

	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>(PO.rankArr.length-1)){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(' - ');
	              //Dialog.message(status);
				  //debug(response.responseText);
	            }
	          });
	      }
		  
	    };
		
	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);
			  }

	PO.aPullUp = function(a , n)
	{
		var a1 = a.slice(0,n+1);
		var a2 = a.slice(n);
		a1.pop();
		a2.shift();

		return a1.concat(a2);
	}

	d2.addEventListener("unload",function()
	{	
		if(PO.cFlg)
		{
			PO.cEnd();
		}
		else
		{
			PO.LogObj = eval("("+ GM_getValue("LogObj")+")");
			PO.iSearch();
		}
		
		if(PO.time>PO.Config.minPostTime)
		{
			PO.addPost_delicious();//del.icio.usへポスト
			
			PO.LogObj.URLs = PO.aPullUp( PO.LogObj.URLs , PO.nowN );
			PO.LogObj.rTimes = PO.aPullUp( PO.LogObj.rTimes ,PO.nowN );

			var s = "{"+ PO.LO_a2j("URLs") + "," + PO.LO_a2j("rTimes")+"}";
			GM_setValue("LogObj",s);
			
		}
		else if(PO.click)
		{
			return;
		}
		else
		{
			PO.LogObj.URLs = PO.aPullUp( PO.LogObj.URLs , PO.nowN );
			PO.LogObj.rTimes = PO.aPullUp( PO.LogObj.rTimes ,PO.nowN );

			var s = "{"+ PO.LO_a2j("URLs") + "," + PO.LO_a2j("rTimes")+"}";
			GM_setValue("LogObj",s);
		}
	},false);

})();
