/*************************************************************
*       VLAAH Embed - http://vlaah-embed.appspot.com/        *
**************************************************************
Copyright (c) 2010 Heungsub Lee <sublee@lunant.com>

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
(function(w) {
    if (typeof w.vlaahEmbed == 'undefined') {
        /* Helpers */
        var base64 = /**
*
*  base64 encode / decode
*  http://www.webtoolkit.info/
*
**/
 
{
 
    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
 
    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;
 
        input = base64._utf8_encode(input);
 
        while (i < input.length) {
 
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
 
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
 
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }
 
            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
 
        }
 
        return output;
    },
 
    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
 
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
        while (i < input.length) {
 
            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));
 
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
 
            output = output + String.fromCharCode(chr1);
 
            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
 
        }
 
        output = base64._utf8_decode(output);
 
        return output;
 
    },
 
    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";
 
        for (var n = 0; n < string.length; n++) {
 
            var c = string.charCodeAt(n);
 
            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
 
        }
 
        return utftext;
    },
 
    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
 
        while ( i < utftext.length ) {
 
            c = utftext.charCodeAt(i);
 
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
 
        }
 
        return string;
    }
 
};
        var ie6 = false /*@cc_on || @_jscript_version < 5.7 @*/;
        var urlencode = function(str) {
            return encodeURIComponent(str).replace(/%2F/gi, '%0A');
        };
        var applyAll = function(seq, func, args) {
            var returns = {};
            for (var x in seq) {
                returns[x] = func.apply(seq[x], args);
            }
            return returns;
        }

        /* Candybar class */
        var Candybar = (function () {
    var Candybar = function(context, options) {
        /* Set properties */
        this.context = context;
        this.id = 'vlaah-embed-' + (new Date()).getTime();
        this.data = {degree: {total: 0}, percent: {total: 50}};
        this.element = null;

        /* Set options */
        options = options || {};
        for (var key in this.defaultOptions) {
            if (typeof options[key] == 'undefined') {
                options[key] = this.defaultOptions[key];
            }
        }
        this.options = options;
        this.$ = options.vlaahEmbed;

        /* Register this candybar */
        this.register();
    }

    Candybar.prototype = {
        defaultOptions: {
            showContext: false,
            vlaahEmbed: null,
            plusTheme: 'clover',
            minusTheme: 'tomato'
        },

        markup: function(template) {
            var self = this;

            var context = this.context;
            var id = this.id;
            var plusTheme = this.options.plusTheme;
            var minusTheme = this.options.minusTheme;

            template = template || this.$.html;
            template = template.replace(/\[\[([^\]]+)\]\]/g, function(_, expr) {
                return eval(expr);
            });
            if (ie6) {
                template = template.replace(/chipset\.png/g, 'chipset.gif');
            }
            return template;
        },

        append: function(container, after_ready, template) {
            var self = this;

            var markup = this.markup(template);
            var on_appended = function() {
                self.element = w.document.getElementById(self.id);
                if (self.element) {
                    var text_el = self.getTextElement();
                    var context_el = self.getContextElement();
                    var degree_el = self.getDegreeElement();

                    if (self.options.showContext) {
                        text_el.onmouseover = function() {
                            context_el.style.display = 'none';
                            degree_el.style.display = 'inline';
                        }
                        text_el.onmouseout = function() {
                            context_el.style.display = 'inline';
                            degree_el.style.display = 'none';
                        }
                        text_el.onmouseout();
                    } else {
                        context_el.style.display = 'none';
                        degree_el.style.display = 'inline';
                        self.element.title = self.context;
                    }
                    self.sync();
                }
            }
            if (container) {
                var appending = function() {
                    container.innerHTML = markup;
                    on_appended();
                }
                if (after_ready) {
                    if (w.addEventListener !== undefined) {
                        w.addEventListener('load', appending, true);
                    } else if (w.attachEvent !== undefined) {
                        w.attachEvent('onload', appending);
                    }
                } else {
                    appending();
                }
            } else {
                w.document.write(markup);
                on_appended();
            }
        },

        register: function() {
            var key = base64.encode(this.context);
            if (this.$.candybars[key] === undefined) {
                this.$.candybars[key] = {};
            }
            return this.$.candybars[key][this.id] = this;
        },

        sync: function() {
            this.$.load(this.context);
        },

        update: function(data) {
            var vlaah_score = data['plusesCount'] - data['minusesCount'];
            if (vlaah_score) {
                var denominator = data['plusesCount'] + data['minusesCount'],
                    percent = data['plusesCount'] / denominator * 100;
            } else {
                var percent = 50;
            }
            this.animatePercent(percent);
            this.getDegreeElement().innerHTML = vlaah_score;
            if (data.expressed) {
                var form = this.pushButton(data.expressed);
                form.action = this.$.topic_base + '/' + urlencode(data.comment);
                this.pullButton(data.expressed == 'plus' ? 'minus' : 'plus');
            } else {
                this.pullButton('plus');
                this.pullButton('minus');
            }
            this.data = data;
            this.percent = percent;
        },

        animatePercent: function(percent) {
            var self = this;
            var bar = this.getBarElement();

            var from = parseFloat(this.percent || 50);
            var to = percent;
            from = Math.round(from * 10) / 10;
            to = Math.round(to * 10) / 10;
            if (from == to) return;

            var steps = this.$.duration / this.$.fps;
            var amount = 1 / steps;

            var i = 0, x;
            if (this.__t) clearInterval(this.__t);
            this.__t = setInterval(function() {
                i = Math.min(1, i + amount);
                x = self.$.transition(i);
                bar.style.width = (x * (to - from) + from) + '%';
                if (i >= 1) {
                    clearInterval(self.__t);
                    return;
                }
            }, this.$.fps);
        },

        showLoading: function() {
            this.getTextElement().style.display = 'none';
            this.getLoadingElement().style.display = 'block';
        },

        hideLoading: function() {
            this.getTextElement().style.display = 'block';
            this.getLoadingElement().style.display = 'none';
        },

        pushButton: function(prefer) {
            var forms = this.getFormElements(prefer);
            forms[0].style.display = 'none';
            forms[1].style.display = 'block';
            return forms[1];
        },

        pullButton: function(prefer) {
            var forms = this.getFormElements(prefer);
            forms[0].style.display = 'block';
            forms[1].style.display = 'none';
            return forms[0];
        },

        getFormElements: function(prefer) {
            var i = Number(prefer != 'plus');
            var express = this.element.getElementsByTagName('blockquote')[i];
            return express.getElementsByTagName('form');
        },
        getBarElement: function() {
            return this.element.getElementsByTagName('u')[1];
        },
        getTextElement: function() {
            return this.element.getElementsByTagName('a')[0]
                               .getElementsByTagName('span')[0];
        },
        getContextElement: function() {
            return this.element.getElementsByTagName('s')[0];
        },
        getDegreeElement: function() {
            return this.element.getElementsByTagName('u')[0];
        },
        getLoadingElement: function() {
            return this.element.getElementsByTagName('i')[0];
        }
    };

    return Candybar;
})();

        /* VLAAH Embed library */
        var $;
        w.vlaahEmbed = $ = {
            initialized: true,

            Candybar: Candybar,
            candybars: {},
            initOptions: {},

            topic_base: "http:\/\/vlaah.com",
            html: "\n\n\n\n\n\n<div id=\"[[id]]\" class=\"vlaah-candybar\"\n     style=\"position: relative; width: 100%; margin: 0; padding: 0; border: none; outline: none;\n  font-size: 100%; font-style: normal; font-weight: normal;\n  text-decoration: none; vertical-align: baseline;\">\n  <blockquote class=\"vlaah-candybar-plus\" style=\"\n       margin: 0; padding: 0; border: none; outline: none;\n  font-size: 100%; font-style: normal; font-weight: normal;\n  text-decoration: none; vertical-align: baseline;\n       position: absolute;\n       height: 20px;\n       overflow: hidden;\n       left: 0;\n     \">\n    <form action=\"http:\/\/vlaah.com\/[[urlencode(context)]]\" method=\"post\"\n          onsubmit=\"vlaahEmbed.load('[[context]]', this); return false;\"\n          style=\"margin: 0; padding: 0; border: none; outline: none;\n  font-size: 100%; font-style: normal; font-weight: normal;\n  text-decoration: none; vertical-align: baseline; font-size: 0;\">\n      <input type=\"hidden\" name=\"type\" value=\"plus\" \/>\n      <input src=\"http:\/\/vlaah-embed.appspot.com\/static\/transparent.gif\"\n             type=\"image\" alt=\"plus\"\n             class=\"vlaah-plus-express\" style=\"\n               margin: 0; padding: 0; border: none; outline: none;\n  font-size: 100%; font-style: normal; font-weight: normal;\n  text-decoration: none; vertical-align: baseline;\n               background: url('http:\/\/vlaah-embed.appspot.com\/static\/chipsets\/[[plusTheme]].legacy_chipset.png');\n  background-repeat: repeat-x;\n               background-position: -155px -45px;\n               width: 20px; height: 20px;\n               text-indent: -9999px;\n             \"\n             onmousedown=\"this.style.backgroundPosition = '-180px -45px';\"\n             onmouseout=\"this.style.backgroundPosition = '-155px -45px';\"\n      \/>\n    <\/form>\n    <form style=\"display: none; margin: 0; padding: 0; border: none; outline: none;\n  font-size: 100%; font-style: normal; font-weight: normal;\n  text-decoration: none; vertical-align: baseline;\"\n          onsubmit=\"vlaahEmbed.load('[[context]]', this); return false;\">\n      <input type=\"hidden\" name=\"__method__\" value=\"delete\" \/>\n      <input src=\"http:\/\/vlaah-embed.appspot.com\/static\/transparent.gif\"\n             type=\"image\" alt=\"plus\"\n             class=\"vlaah-plus-cancel\" style=\"\n               margin: 0; padding: 0; border: none; outline: none;\n  font-size: 100%; font-style: normal; font-weight: normal;\n  text-decoration: none; vertical-align: baseline;\n               background: url('http:\/\/vlaah-embed.appspot.com\/static\/chipsets\/[[plusTheme]].legacy_chipset.png');\n  background-repeat: repeat-x;\n               background-position: -180px -45px;\n               width: 20px; height: 20px;\n               text-indent: -9999px;\n             \" \/>\n    <\/form>\n  <\/blockquote>\n  <blockquote class=\"vlaah-candybar-minus\" style=\"\n       margin: 0; padding: 0; border: none; outline: none;\n  font-size: 100%; font-style: normal; font-weight: normal;\n  text-decoration: none; vertical-align: baseline;\n       position: absolute;\n       height: 20px;\n       overflow: hidden;\n       right: 0;\n     \">\n    <form action=\"http:\/\/vlaah.com\/[[urlencode(context)]]\" method=\"post\"\n          onsubmit=\"vlaahEmbed.load('[[context]]', this); return false;\"\n          style=\"margin: 0; padding: 0; border: none; outline: none;\n  font-size: 100%; font-style: normal; font-weight: normal;\n  text-decoration: none; vertical-align: baseline; font-size: 0;\">\n      <input type=\"hidden\" name=\"type\" value=\"minus\" \/>\n      <input src=\"http:\/\/vlaah-embed.appspot.com\/static\/transparent.gif\"\n             type=\"image\" alt=\"minus\"\n             class=\"vlaah-minus-express\" style=\"\n               margin: 0; padding: 0; border: none; outline: none;\n  font-size: 100%; font-style: normal; font-weight: normal;\n  text-decoration: none; vertical-align: baseline;\n               background: url('http:\/\/vlaah-embed.appspot.com\/static\/chipsets\/[[minusTheme]].legacy_chipset.png');\n  background-repeat: repeat-x;\n               background-position: -205px -45px;\n               width: 20px; height: 20px;\n               text-indent: -9999px;\n             \"\n             onmousedown=\"this.style.backgroundPosition = '-230px -45px';\"\n             onmouseout=\"this.style.backgroundPosition = '-205px -45px';\"\n      \/>\n    <\/form>\n    <form style=\"display: none; margin: 0; padding: 0; border: none; outline: none;\n  font-size: 100%; font-style: normal; font-weight: normal;\n  text-decoration: none; vertical-align: baseline;\"\n          onsubmit=\"vlaahEmbed.load('[[context]]', this); return false;\">\n      <input type=\"hidden\" name=\"__method__\" value=\"delete\" \/>\n      <input src=\"http:\/\/vlaah-embed.appspot.com\/static\/transparent.gif\"\n             type=\"image\" alt=\"minus\"\n             class=\"vlaah-plus-cancel\" style=\"\n               margin: 0; padding: 0; border: none; outline: none;\n  font-size: 100%; font-style: normal; font-weight: normal;\n  text-decoration: none; vertical-align: baseline;\n               background: url('http:\/\/vlaah-embed.appspot.com\/static\/chipsets\/[[minusTheme]].legacy_chipset.png');\n  background-repeat: repeat-x;\n               background-position: -230px -45px;\n               width: 20px; height: 20px;\n               text-indent: -9999px;\n             \" \/>\n    <\/form>\n  <\/blockquote>\n  <div class=\"vlaah-bar-minus\" style=\"\n         margin: 0; padding: 0; border: none; outline: none;\n  font-size: 100%; font-style: normal; font-weight: normal;\n  text-decoration: none; vertical-align: baseline;\n         background: url('http:\/\/vlaah-embed.appspot.com\/static\/chipsets\/[[minusTheme]].legacy_chipset.png');\n  background-repeat: repeat-x;\n         position: relative;\n         background-position: 0 -160px;\n         height: 20px;\n         margin: 0 20px;\n       \">\n      <a href=\"http:\/\/vlaah.com\/[[urlencode(context)]]\"\n         style=\"margin: 0; padding: 0; border: none; outline: none;\n  font-size: 100%; font-style: normal; font-weight: normal;\n  text-decoration: none; vertical-align: baseline; text-decoration: none; cursor: pointer;\">\n          <span class=\"vlaah-text\" style=\"\n               margin: 0; padding: 0; border: none; outline: none;\n  font-size: 100%; font-style: normal; font-weight: normal;\n  text-decoration: none; vertical-align: baseline;\n               position: absolute;\n               width: 100%;\n               height: 20px;\n               line-height: 20px;\n               overflow: hidden;\n               text-align: center;\n               color: #fff;\n               font: bolder 11px\/20px 'Trebuchet MS', sans-serif;\n             \">\n            <s class=\"vlaah-context\"\n               style=\"\n                 margin: 0; padding: 0; border: none; outline: none;\n  font-size: 100%; font-style: normal; font-weight: normal;\n  text-decoration: none; vertical-align: baseline;\n                 font-weight: bolder;\n                 text-decoration: none;\">[[context]]<\/s>\n            <u class=\"vlaah-degree\"\n               style=\"\n                 margin: 0; padding: 0; border: none; outline: none;\n  font-size: 100%; font-style: normal; font-weight: normal;\n  text-decoration: none; vertical-align: baseline;\n                 display: none;\n                 font-weight: bolder;\n                 text-decoration: none;\">\n            <\/u>\n          <\/span>\n          <i class=\"vlaah-loading\" style=\"\n               margin: 0; padding: 0; border: none; outline: none;\n  font-size: 100%; font-style: normal; font-weight: normal;\n  text-decoration: none; vertical-align: baseline;\n               display: none;\n               position: absolute;\n               top: 0;\n               width: 100%;\n               height: 20px;\n               background: url('http:\/\/vlaah-embed.appspot.com\/static\/load.gif') no-repeat center;\n               text-indent: -9999px;\n             \">Loading<\/i>\n      <\/a>\n      <u class=\"vlaah-bar-plus\" style=\"\n           margin: 0; padding: 0; border: none; outline: none;\n  font-size: 100%; font-style: normal; font-weight: normal;\n  text-decoration: none; vertical-align: baseline;\n           display: block;\n           background: url('http:\/\/vlaah-embed.appspot.com\/static\/chipsets\/[[plusTheme]].legacy_chipset.png');\n  background-repeat: repeat-x;\n           background-position: 0 -160px;\n           height: 20px;\n           width: 50%;\n           text-decoration: none;\n         \"><\/u>\n  <\/div>\n  <div class=\"vlaah-meta\" style=\"display: none;\">\n    <q title=\"topic_base\">http:\/\/vlaah.com<\/q>\n    <q title=\"context\"><\/q>\n  <\/div>\n  <div class=\"vlaah-loaded\" id=\"[[id]]-scripts\"\n       style=\"visibility: hidden; position: absolute;\"><\/div>\n<\/div>",

            append: function(context, container_id, after_ready,
                             plus_theme, minus_theme, show_context) {
                var candybar = new $.Candybar(context, {
                    plusTheme: plus_theme,
                    minusTheme: minus_theme,
                    showContext: show_context,
                    vlaahEmbed: w.vlaahEmbed
                });
                candybar.append(document.getElementById(container_id),
                                after_ready);
            },

            load: function(context, form) {
                var key = base64.encode(context);
                var callback = 'vlaahEmbed.update("' + key + '")';
                var url, params = '__callback__=' + callback;

                if (form) {
                    url = form.action;
                    // temporarily deprecate the real-time voting
                    open(url, '_blank'); return;
                    var set_method = false;
                    var inputs = form.elements;
                    for (var i = 0; i < inputs.length; ++ i) {
                        var input = inputs[i];
                        params += '&' + input.name
                                + '=' + urlencode(input.value);
                        if (input.name == '_method') set_method = true;
                    }
                    if (!set_method) {
                        params += '&__method__=' + form.method;
                    }
                } else {
                    url = $.topic_base + '/' + urlencode(context);
                }
                url += '?' + params;

                var id, candybars = $.getCandybars(base64.encode(context));
                for (id in candybars) {
                    candybars[id].element && candybars[id].showLoading();
                }

                var scripts_id = id + '-scripts';
                var scripts = document.getElementById(scripts_id);

                var script = document.createElement('script');
                script.type = 'text/javascript';
                script.src = url;
                scripts.appendChild(script);
            },

            update: function(key) {
                return function(data) {
                    var candybars = $.getCandybars(key);
                    for (var id in candybars) {
                        if (!candybars[id].element) continue;
                        candybars[id].update(data);
                        candybars[id].hideLoading();
                    }
                }
            },

            getCandybars: function(key) {
                return $.candybars[key] || {};
            },

            /* Animation */
            duration: 100,
            fps: 20,
            transition: function(x) {
                return Math.sin(x * Math.PI / 2);
            }
        };
    }
})(window);

(function(w) {
    var opt = w.vlaahEmbed.initOptions;

    var context = "http:\/\/blog.dahlia.kr\/post\/379524623" || opt.context || w.location.href;
    var container_id = null || opt.container_id;
    var after_ready = null || opt.after_ready || false;
    var plus_theme = null || opt.plus_theme || 'clover';
    var minus_theme = null || opt.minus_theme || 'tomato';
    var show_context = null || opt.show_context || false;

    w.vlaahEmbed.append(context, container_id, after_ready,
                        plus_theme, minus_theme, show_context);
    w.vlaahEmbed.initOptions = {};
})(window);

