// ==UserScript==
// @name          LDR Ipatsu SBM
// @namespace     http://www.ohmiyapatriots.com/blog/
// @description   post the entry to del.icio.us,hatena bookmark with pushing one key (including setting window)
// @include       http://reader.livedoor.com/reader/*
// @version   1.0.0.1
// @license   http://creativecommons.org/licenses/by-sa/2.1/jp/
//            original: http://d.hatena.ne.jp/antipop/20060427/1146067330
//                      by: kentaro
//                      license: cc by-sa
// ==/UserScript==

(function() {
 	//property
	var shortcutKey,id,pwd,tags,need_delicious,need_hatebu;
	
	var close_data ='data:image/png;base64,'+
	    'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAACXBI'+
	    'WXMAAA3XAAAN1wFCKJt4AAAAB3RJTUUH1QwDARgOPQO6ugAAAZNJREFUOMudk71SGzEUhT/J9hri'+
	    'PEDGBTCTN2B4Axc0FHQ01KFPCbUzjtN7Jn3SU/IuTIoQ90S7lvfPq5Nis2vIuonV6M5I57v3niuZ'+
	    '2Xz6AfjKHsta+5HZfKp912w+Vb+hLZfL/8o+Ho8BaAEqinovSyhLqCoUAkgYa6HXg34f0+/DYNCC'+
	    'tgDva3FRQFliJIwECIwFa1BvUIuH0Q7AagVZBkXB8fk5AE/39wAcXV4C8OvhAUURGr0hhPAPYL0G'+
	    'v8LmRUtvhO2dOIYowlqznUQTmDSF3zFyjp+LRce0p8UC4xzEMawzqqp6XQFpipK4biPPOwA9P6Mo'+
	    'whweYkZv2xbaCvAekgQ5x8ntbQdwfHeHnCM4h9ae/G+SrQdZSogTzNq3oh/X14B4/+07AME5zGYD'+
	    'abpjCmmG/AolCY9XVyhN63ECjxcXmIMDzGgEIaAs2wHI8/otrGpI8L72QsI0vUtYa18BWg+Gp6eo'+
	    'gUkgIYk6VHMAEsOzs24F7yYTmEw65jVuA2w2mzZ+aeLN5y+f9vrOwM0fpocVsnebVZ4AAAAASUVO'+
	    'RK5CYII=';

	var config_id='idr_ipatsu_config';
	var menu_title="LDR Ipatsu SBM - Settings ";

	var libraries = [
		"http://reader.livedoor.com/js/wsse.js"
	];

	var w       = unsafeWindow;
	var _onload = w.onload;

	function show_config() {
		var configPane = build_config();
		var body = document.getElementsByTagName("body");
		body[0].appendChild(configPane);
		configPane.style.display = 'block';
		return;
	}

	function close_config(w){
		w.style.display = 'none';
	}

    function build_config() {
		log(decode_data(GM_getValue("password")));
		
        var parameters = [ // The parameters to be presented in the form
            { name: "id", label: "id", type: "string",
              value: decode_data(GM_getValue("id")),
              help: "please input your id"},
            { name: "pwd", label: "password", type: "password",
		   value: decode_data(GM_getValue("pwd")),
              help: "Change password (or enter it initially)" },
           { name: "shortcut", label: "shortcut key", type: "shortcut",
		   value: decode_data(GM_getValue("shortcut")),
              help: "please input shortcut key to use"},
            { name: "tags", label: "\u3042\u3089\u304b\u3058\u3081\u5165\u529b\u3059\u308b\u30bf\u30b0",
              type: "string", value: decode_data(GM_getValue("tags")),
              help: "please input tags",
		   description:"\u203b\u30b9\u30da\u30fc\u30b9\u3067\u533a\u5207\u3063\u3066\u8907\u6570\u5165\u529b\u3067\u304d\u307e\u3059"},
            { name: "need_delicious", label: "del.icio.us? ",
              type: "boolean", value: GM_getValue("need_delicious", false),
              help: "if you wanna post to delicious,please check it" },
            { name: "need_hatebu", label: "hatena bookmark? ",
             type: "boolean", value: GM_getValue("need_hatebu", false),
             help: "if you wanna post to hatena bookmark,please check it" },
        ];

		var configPane = document.createElement("div"); 
		configPane.setAttribute("style",
		                 "margin: 0 40%; width: 40%; position: fixed; " +
		                 "top: 0; left: 0; border: thin solid black; " +
		                 "color: black; background: #f5f5f5; opacity: 0.9; " +
		                 "-moz-border-radius: 10px; font-size: 12pt; " +
		                 "z-index: 99999; padding: 6px; display: none; " +
		                 "font-family: Arial, sans-serif;");
		configPane.setAttribute("id", config_id);
		var close = document.createElement("img");
		close.setAttribute("src", close_data);
		close.setAttribute("style", "float: right; vertical-align: top; " +
		                   "margin: 2px; width: 16px; height: 16px; " +
		                   "background-color: #ffb; border: none;");
		close.setAttribute("title", "Click To Remove");
		close.setAttribute("id",config_id + "_close");
		close.addEventListener('click',
		                       function(e) { close_config(configPane); },
		                       false);
		var caption = document.createElement("caption");
		caption.setAttribute("style", "width: 100%; text-align: left");
		strong = document.createElement("strong");

		strong.appendChild(close);
		strong.appendChild(document.createTextNode(menu_title));
		caption.appendChild(strong);
		configPane.appendChild(caption);

		var form = document.createElement("form");
		form.setAttribute("method", "get");
		form.setAttribute("action", "");
		form.setAttribute("id",config_id);
		form.setAttribute("style", "padding: 0; margin: 0;");

		var dl = document.createElement("dl");
		dl.setAttribute("id", "ldr_config_pane");
		form.appendChild(dl);

        for (var idx = 0; idx < parameters.length; idx++)
        {
			set_config_content(dl,parameters[idx]);
        }
        configPane.appendChild(form);
        return configPane;
    }
	
	function set_config_content(pane,param) {
		var name = param['name'];
		var value = param['value'];
		var dt = document.createElement("dt");
		var dd = document.createElement("dd");

		dt.setAttribute("style","text-align: left;font-weight:bold;");
		dd.setAttribute("style","margin-bottom:5px;padding-left:10px;");

		dt.appendChild(document.createTextNode(param['label']));
		pane.appendChild(dt);
		
		
        var control;
        var helptext = param['help'] || '';
        switch (param['type']) {
            case 'string':
                control = document.createElement("input");
                control.setAttribute("id", "ipatsu_config_elem_" + name);
                control.setAttribute("type", "text");
                control.setAttribute("size", 35);
                control.setAttribute("title", helptext);
                control.setAttribute("name", name);
                control.setAttribute("value", value);
                control.addEventListener("blur", function (ev) {
                    change_value(name, this.value);
                }, false);
                break;
           case 'password':
                control = document.createElement("input");
                control.setAttribute("id", "ipatsu_config_elem_" + name);
                control.setAttribute("type", "password");
                control.setAttribute("size", 35);
                control.setAttribute("title", helptext);
                control.setAttribute("name", name);
                control.setAttribute("value", value);
                control.addEventListener("blur", function (ev) {
               		change_value(name, this.value);
			 }, false);
                break;
            case 'integer':
                control = document.createElement("input");
                control.setAttribute("id", "ipatsu_config_elem_" + name);
                control.setAttribute("type", "text");
                control.setAttribute("size", 8);
                control.setAttribute("title", helptext);
                control.setAttribute("name", name);
                control.setAttribute("value", value);
                control.addEventListener("blur", function (ev) {
                    change_value(name, this.value);
                }, false);
                break;
            case 'boolean':
                // Start with a <span> to contain the two radiobuttons and text
                control = document.createElement("span");
                control.setAttribute("id", "ipatsu_config_elem_" + name);
                // First radiobox, for "yes"
                var radiobox = document.createElement("input");
                radiobox.setAttribute("type", "radio");
                radiobox.setAttribute("name", "ipatsu_config_elem_bool_" + name);
                radiobox.setAttribute("id", "ipatsu_config_elem_bool_" + name +
                                      "_yes");
                radiobox.setAttribute("value", "yes");
                if (value)
                    radiobox.setAttribute("checked", value);
                radiobox.addEventListener("click", function(ev) {
                    change_value_bool(name, this.value, this.checked);
                }, false);
                control.appendChild(radiobox);
                // The word "yes" and some padding space
                control.appendChild(document.createTextNode("\u306f\u3044"));
                // Second radiobox, for "no"
                radiobox = document.createElement("input");
                radiobox.setAttribute("type", "radio");
                radiobox.setAttribute("name", "ipatsu_config_elem_bool_" + name);
                radiobox.setAttribute("id", "ipatsu_config_elem_bool_" + name +
                                      "_no");
                radiobox.setAttribute("value", "no");
                if (! value)
                    radiobox.setAttribute("checked", ! value);
                radiobox.addEventListener("click", function(ev) {
                    change_value_bool(name, this.value, this.checked);
                }, false);
                control.appendChild(radiobox);
                // The word "no" and padding
                control.appendChild(document.createTextNode("\u3044\u3044\u3048"));
                break;
            case 'shortcut':
                control = document.createElement("input");
                control.setAttribute("id", "ipatsu_config_elem_" + name);
                control.setAttribute("type", "text");
                control.setAttribute("size", 35);
                control.setAttribute("title", helptext);
                control.setAttribute("name", name);
                control.setAttribute("value", value);
                control.addEventListener("blur", function (ev) {
                    change_value_shortcut(name, this.value);
                }, false);
                break;
            default:
                control = null;
                break;
        }

     if (control != null)
     		dd.appendChild(control);

	if(param['description'] != null){
		var p = document.createElement('p');
		p.appendChild(document.createTextNode(param['description']));
		dd.appendChild(p);
	}
 
     pane.appendChild(dd);

   }

	function change_value(name, value) {
		GM_setValue(name, encodeURI(value || ''));
		GM_setValue('first_config_done', true);
		
		set_propertys();
	}

	function change_value_bool(name, value, onoff) {
		truestate = (value == 'yes') ? onoff : ! onoff;
		GM_setValue(name, truestate);
		GM_setValue('first_config_done', true);
		set_propertys();
		return;
	}

 	function change_value_shortcut(name, value) {
		GM_setValue(name, encodeURI(value || ''));
		GM_setValue('first_config_done', true);

		if(value)
			set_keybind(value);
	}

	function set_propertys(){
		shortcutKey = GM_getValue('shortcut');
		id       =  decode_data(GM_getValue('id'));
		pwd    =  decode_data(GM_getValue('pwd'));
		tags    = decode_data(GM_getValue('tags'));
		need_delicious = GM_getValue('need_delicious');
		need_hatebu = GM_getValue('need_hatebu');
	}
	function init(){
		if (!GM_getValue('first_config_done', false)) {
			show_config();
		}
		set_propertys();
		return;
	}

      function log(message) {
          if (unsafeWindow && unsafeWindow.console) {
              unsafeWindow.console.log(message);
          }
      }

	function decode_data(v){
		return  v!=null ? decodeURI(v):'';
	}
	GM_registerMenuCommand(menu_title,show_config);
	init();

	function REST() {}
	REST.prototype = {

		makeURI : function(baseURI, queries) {
			var query = "";
			for (var q in queries)
				query += "&" + q + "=" + encodeURIComponent(queries[q]);

			return baseURI + query.substr(1);
		},
		
		post : function(method, baseURI, queries,oncallback) {
			var self=this;
			window.setTimeout(function() {
			GM_xmlhttpRequest({
					method : method,
					url    : self.makeURI(baseURI, queries),
					onload : oncallback
				});
			},0);
		}
	};
	

	var onload = function() {
		if(!shortcutKey)
			return;

		for (var i = 0; i < libraries.length; i++)
		{
			var script = document.createElement('script');
			document.getElementsByTagName('head')[0].appendChild(script);
			script.type = 'text/javascript';
			script.src  = libraries[i];
		}
		set_keybind(shortcutKey);
	};

	function set_keybind(skey){
		w.Keybind.add(skey, function(){
			var item = w.get_active_item(true);
	
			if (!item) return;
			
			if(need_delicious)
				post_delicious(item);

			if(need_hatebu)
				post_hatena(item);
		});
	}

	function post_hatena(item){
		w.message("post "+ "\u306f\u3066\u306a\u30d6\u30c3\u30af\u30de\u30fc\u30af" + ": " + item.title);
		var atom = new ATOM(id, pwd);
		var comment = "[" + tags.replace(/　/g," ").replace(/ /g,"][") + "]";

		atom.post("http://b.hatena.ne.jp/atom/post", item.link,comment ,
			function(response){
				var msg = "\u306f\u3066\u306a\u30d6\u30c3\u30af\u30de\u30fc\u30af \u3078\u306E\u767B\u9332\u306B\u5931\u6557\u3057\u307E\u3057\u305F";
				if(response.status == '201'){
					msg = "\u306f\u3066\u306a\u30d6\u30c3\u30af\u30de\u30fc\u30af \u306B\u767B\u9332\u3057\u307E\u3057\u305F";
				}else{
					w.document.getElementById("clip_icon_"+item.item_id).src = "/img/icon/clip.gif";
				}
				w.message(msg);
			}
		);
	}

	function ATOM(username, password)
	{
		this.username = username;
		this.password = password;
	}
	ATOM.prototype = {
		post : function(postURI, permalink, comment,oncallback) {
			permalink = permalink.replace(/#/, '%23');
			var requestBody =
				<entry xmlns="http://purl.org/atom/ns#">
					<title>dummy</title>
					<link rel="related" type="text/html" href={permalink} />
					<summary type="text/plain">{comment}</summary>
				</entry>;
			var self=this;
			window.setTimeout(function() {
				GM_xmlhttpRequest({
					method  : "POST",
					url     : postURI,
					headers : {
						'Accept' : 'application/x.atom+xml, application/xml, text/xml, */*',
						'X-WSSE' : w.wsseHeader(self.username, self.password),
					},
					data    : requestBody.toString(),
					onload  :oncallback
				});
			},0);
		}
	};


	function post_delicious(item){
			var rest = new REST();
			w.message("post del.icio.us: " + item.title);

			// del.icio.us
			if (id)
			{
				//var tags = [], notes = "";

				var queries = {
					url         : item.link,
					description : item.title,
					//tags        : '\u3042\u3068\u3067\u8AAD\u3080',
					tags	: tags.replace(/　/g," "),
					dt          : (function() {
						var date = new Date();
						return date.getW3CDTF();
					})()
				};
				
				var itemid = item.item_id;
				w.document.getElementById("clip_icon_"+itemid).src = "/img/icon/clipped.gif";
				rest.post("get", "https://" + id + ":" + pwd + "@" + "api.del.icio.us/v1/posts/add?",queries,
					function(response){
						var msg = 'del.icio.us \u3078\u306E\u767B\u9332\u306B\u5931\u6557\u3057\u307E\u3057\u305F';							
						if(response.status == '200'){
							msg = 'del.icio.us \u306B\u767B\u9332\u3057\u307E\u3057\u305F';
						}else{
							w.document.getElementById("clip_icon_"+itemid).src = "/img/icon/clip.gif";
						}
						w.message(msg);
					}
				);

			}
	}

	w.onload = function() {
		_onload();
		onload();
	};

	function complementDate(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";
	}
})();