/*
 livedoor clip utils
 http://clip.livedoor.com/js/utils.js
 version: 0.1 / 2007-05-21

 Copyright (C) 2007 livedoor Co.,Ltd.
 Code licensed under the BSD License
*/
if(typeof Livedoor == "undefined"){Livedoor = {}}
if(typeof LDClip == "undefined"){LDClip = {}}

new function(){
    function escapeHTML(str){
        return (""+str).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
    }
    function Tag(tagname){
        return function(param, innerHTML){
            var attrs = [];
            for(var key in param){
                if(param.hasOwnProperty(key))
                    attrs.push(key + "=" + '"' + escapeHTML(param[key]) + '"');
            }
            if(arguments.length > 1){
                return "<" + tagname  + " " + attrs.join(" ") + ">" + innerHTML + "</" + tagname + ">"
            } else {
                return "<" + tagname  + " " + attrs.join(" ") + " />"
            }
        }
    }
    var SPAN = Tag("span");
    var IMG = Tag("img");
    var DIV = Tag("div");
    var LI = Tag("li");
    var Count = {};

    function generate_id(namespace){
        return [namespace, counter(namespace)].join("_")
    }
    function counter(namespace){
        return (Count[namespace]) ? ++Count[namespace] : (Count[namespace] = 1)
    }

    Livedoor.Clip = {
        __PACKAGE__: 'Livedoor.Clip',
        ApiBase:    'http://api.clip.livedoor.com/',
        ImageBase:  'http://image.clip.livedoor.com/counter/',
        ButtonBase: 'http://parts.blog.livedoor.jp/img/cmn/',
        Buttons: [
            "clip_16_12_w.gif",
            "clip_16_12_b.gif",
            "clip_16_16_w.gif",
            "clip_16_16_b.gif"
        ],
        _user: function(id){
            return this.A({
                href: 'http://clip.livedoor.com/clips/' + id,
                text: id
            });
        },
        _page: function(url){return 'http://clip.livedoor.com/page/' + this.escape(url)},
        el: function(id){return document.getElementById(id)},
        A: function(param){
            var attrs = [];
            var text = param.text;
            if (this.linktarget) param.target = "_blank";
            delete param.text;
            for(var key in param){
                if(param.hasOwnProperty(key))
                    attrs.push(key + "=" + '"' + param[key] + '"');
            }
            return "<a " + attrs.join(" ") + ">" + text + "</a>"
        },
        escape: function(str){
            return str.replace("#", "%23");
        },
        callbacks: {},
        loader: function(script_url){
            var head = document.getElementsByTagName("head")[0];
            var s = document.createElement("script");
            s.type = "text/javascript";
            s.charset = "utf-8";
            s.src = script_url;
            head.appendChild(s)
        },
        load: function(module, param){
            var api = this.ApiBase + module;
            var buf = [];
            for(var key in param){
                buf.push(key + "=" + encodeURIComponent(param[key]));
            }
            this.loader(api + "?" + buf.join("&"));
        },
        _write: function(str){
            document.write(str);
        },
        request: function(api, callback){
            var self = this;
            var url = this.ApiBase + api;
            var cb = api.replace("/","_") + "_" + counter(api);
            this.callbacks[cb] = function(){
                callback.apply(self, arguments);
                delete self.callbacks[cb];
            };
            return {
                send: function(param){
                    param.callback = [self.__PACKAGE__, 'callbacks', cb].join(".");
                    self.load(api, param)
                }
            };
        },
        image_counter: function(size, id){
            var url = this.ImageBase + (size ? size : "small");
            var target = this.location || location.href;
            var img_url = url + "/" + this.escape(target);
            var str = this.A({
                href: this._page(target),
                text: IMG({src:img_url, border:0})
            });
            $(id).find("script.livedoor").after(str);
        },
        text_counter: function(alt, detail){
            var target = this.location || location.href;
            var uniq_id = generate_id("ldc_text_count");
            var alt_text = (typeof alt == "undefined") ? "" : "" + alt;
            this._write(SPAN({id:uniq_id}, alt));
            this._load_count(uniq_id, target);
        },
        _load_count: function(id, url){
            var el = this.el(id);
            var self = this;
            var req = this.request("json/count", function(num){
                var text = (typeof num == "number") ? num : 0;
                if(text != 0){
                    el.innerHTML = self.A({
                        href: self._page(url),
                        text: text
                    });
                } else {
                    el.innerHTML = "0";
                }
            });
            req.send({link: url});
        },
        counter: function(){
            var target = this.location || location.href;
            var uniq_id = generate_id("")
            this._write(SPAN({id:"ldc_count"}, "-"));
            this._load_count("ldc_count", target);
        },
        simple_comment: function(){
            var target = this.location || location.href;
            this._write(DIV({id:"ldc_comment"},"-"));
            this._load_comment("ldc_comment", target);
        },
        formatter: function(c){
            return LI(
                {"class": "ldc_comments"},
                this._user(c.livedoor_id) + ":" + c.notes
            )
        },
        _load_comment: function(id, url){
            var el = this.el(id);
            var formatter = this.formatter;
            var req = this.request("json/comments", function(clips){
                var buf = [];
                var l = clips.Comments.length;
                var c;
                buf.push("<ul>");
                for(var i=0;i<l;i++) buf.push(formatter(clips.Comments[i]));
                buf.push("</ul>");
                el.innerHTML = buf.join("");
            });
            req.send({link: url});
        },
        simple_button: function(type_num){
            var target = this.location || location.href;
            var img_src = this.ButtonBase + this.Buttons[type_num || 0];
            this._write(
                SPAN({"class":"ldc_button"},
                    this.A({
                        href: 'http://clip.livedoor.com/page/' + this.escape(target),
                        text: IMG({src: img_src, border:0})
                    })
                )
            );
        },
        clip_button: function(type_num){
            var target = this.location || location.href;
            var img_src = this.ButtonBase + this.Buttons[type_num || 0];
            var params = {
                link: encodeURIComponent(target),
                title: encodeURIComponent(document.title)
            };
            var query = [];
            for(var key in params){
                if(params.hasOwnProperty(key))
                    query.push(key+"="+params[key]);
            }
            this._write(
                SPAN({"class":"ldc_button"},
                    this.A({
                        href: 'http://clip.livedoor.com/redirect?' + query.join("&"),
                        text: IMG({src: img_src, border:0})
                    })
                )
            );
        },
        _write_button: function(id){
            var el = this.el(id);
            el.innerHTML;
        },
        
        bind_method: function(target_object){
            var self = this;
            for(var key in this){
                if(typeof this[key] == "function"){
                    (function(method){
                        var f = self[method];
                        target_object[method] = function(){
                            return f.apply(self, arguments)
                        }
                    })(key);
                }
            }
        }
    };
    Livedoor.Clip.bind_method(Livedoor.Clip);
};

Livedoor.Clip.linktarget = 0;

