var Comments = function() {
    this.init.apply(this, arguments);
}
$j.extend(Comments.prototype, {
    init: function(select, context, options) {
        select = select || '.comment > ul > li';
        context = context || document;
        options = options || {};
        this.lis = $j(select, context).not('.c-overflow, .c-reply-main, .c-foot');
        try {
            diggComments;
        } catch(noComments) {
            diggComments = {};
        }
        doWork = $j('#c-menu-all').hasClass('do-work-son');
        plusMinus = $j('.comment').hasClass('c-plus-minus');
        if (this.lis.length > 0) {
            this.parent = $j(this.lis[0]).parent();
            this.pid = this.parent.attr('id');
            $j('#c-loading-total').text(this.lis.length);
            this.pos = 0;
            this.process(options);
        } else {
            $j('.comment').children('ul').prepend('<li class="c-empty" style="padding: 15px;"><h3>No Comments!</h3> It\'s quiet in here... can you hear the echo?</li>').show();
        }
        $j('.c-message a').unbind().click(function(e) {
            var all = $j('#c-menu-all');
            all.removeClass('do-work-son').text(all.text().replace('collapse', 'expand'));;
            var commentsSort = $j('#c-sort option:selected').attr('value');
            CommentsData.get('all', commentsSort);
            e.preventDefault();
        });
        $j('.show-more').unbind().click(function(e) {
            var offset = $j('#c-offset').text();
            var page = Math.ceil(offset / CommentsSettings.pageSize);
            CommentsData.get(false, false, page);
            $j(this).parent().find('div').show();
            $j(this).parent().find('a').hide();
        });
        $j('#comment-reply textarea').autogrow({
            maxHeight: 30,
            minHeight: 8,
            lineHeight: 1,
            unit: 'em'
        });
        $j('#comment-reply form').unbind().submit(function(e) {
            var _thisEl = $j(this);
            _thisEl.children(':submit').attr('disabled', 'disabled');
            if (!CommentsSettings || !CommentsSettings.isLoggedIn) {
                $j('.warning').remove();
                $j('.c-reply-main').before('<li class="warning">You have to be logged in to do that. <a href="/login">Login</a> or <a href="/register">join now</a>.</li>');
                $j('.warning', '.comment').show();
                e.preventDefault();
                return false;
            }
            var data = {
                'itemid': $j('.news-body').attr('id'),
                'parent': 0,
                'cntType': 'story',
                'comments': $j('textarea', this).val(),
                'token': tokens.comments.post
            }
            var captcha = _thisEl.children('.c-captcha');
            if (captcha.length > 0) {
                data['captcha'] = captcha.find(':text').val();
                data['md5'] = captcha.find(':hidden').val();
            }
            $j.ajax({
                'url': '/ajax/comments/post.html',
                'async': true,
                'type': 'POST',
                'dataType': 'html',
                'data': data,
                'success': function(html) {
                    CommentsSettings.captcha = false;
                    var content = $j(html);
                    var newId = content.attr('id');
                    $j('.c-empty, .c-warning').remove();
                    content.insertBefore('.c-reply-main');
                    new Comments(content, false, {
                        animate: 'show',
                        animateCallback: function() {
                            var newReply = $j('#' + newId);
                            newReply.css('background-color', '#DCECF4');
                            newReply.animate({
                                backgroundColor: '#fefad4'
                            },
                            2000);
                        }
                    });
                    _thisEl.children(':submit').removeAttr('disabled');
                    _thisEl.children('textarea').val('');
                    var mine = $j('#c-menu-mine');
                    mine.removeClass('c-disabled');
                    var mineCheck = /(\d+)/.exec(mine.text());
                    var inc = mineCheck != null ? parseInt(/(\d+)/.exec(mine.text())[1]) + 1: 1;
                    if (mineCheck != null{
                        mine.text(mine.text().replace(/(\d+)/, inc));
                    } else {
                        mine.text(mine.text() + ' (1)');
                    }
                    analyticsEvent('event11', 'comment');
                },
                'error': function(xml) {
                    var json = eval('(' + xml.responseText + ')');
                    if (captcha.length > 0) {
                        $j('.c-reply-main .c-captcha').remove();
                        $j('.c-reply-main textarea').after('<div class="c-captcha"><img src="/img/c-spinner.gif" alt=""/> Loading captcha...</div>');
                        $j('.c-reply-main :submit').attr('disabled', 'disabled');
                        $j.ajax({
                            'url': '/get_captcha',
                            'async': true,
                            'type': 'GET',
                            'dataType': 'json',
                            'data': {
                                'tpl': 'json',
                                'keyname': 'uuddlrlrba'
                            },
                            'success': function(json) {
                                $j('.c-reply-main .c-captcha').html('<img src="' + json.src + '" height="' + json.height + '" width="' + json.width + '" alt="captcha!" /><input type="hidden" id="c-md5-main" value="' + json.md5 + '" /><label for="c-captcha-main">Enter the text you see in the image.</label><input id="c-captcha-main" type="text" />');
                                $j('.c-reply-main :submit').removeAttr('disabled');
                            },
                            'error': function(xml) {
                                var json = eval('(' + xml.responseText + ')');
                                _this.error(json.error);
                            }
                        });
                    }
                    $j('.warning').remove();
                    $j('.c-reply-main').before('<li class="warning">' + json.error + '</li>');
                    $j('.warning').show();
                }
            });
            e.preventDefault();
        });
        $j('#comment-reply .c-spellcheck').click(function(e) {
            new spellChecker($j(this).siblings('textarea').get(0)).openChecker();
            e.preventDefault();
        });
    },
    process: function(options) {
        var len = this.lis.length;
        if (this.pos >= len) return false;
        this.parent.show();
        var li = this.lis[this.pos];
        diggComments[li.id] = new Comment(li, true, options);
        if (this.pos < len - 1) {
            this.pos++;
            setTimeout(function() {
                this.process(options);
            }.bind(this), 50);
        } else {
            if (CommentsSettings.sort != 5) {
                $j('#c-menu-all').removeClass('c-disabled');
            }
            if (doWork) {
                try {
                    q;
                } catch(noQueue) {
                    q = new Queue();
                }
                $j('li:not(.c-disabled) a.c-replies', this.parent).each(function() {
                    var _this = $j(this);
                    q.add({
                        f: function() {
                            _this.click();
                        },
                        obj: _this.siblings('ul').attr('id'),
                        splice: true
                    });
                });
                if (!q.isOn()) q.start();
            }
            try {
                threadCallbacks[this.pid]();
            } catch(noCallback) {}
            try {
                options.threadCallback();
            } catch(noCallback) {}
        }
    }
});
var Comment = function() {
    this.init.apply(this, arguments);
}
$j.extend(Comment.prototype, {
    init: function() {
        this.el = $j(arguments[0]);
        if (this.el.length == 0) return false;
        if (diggComments[this.el.id]return false;
        var _this = this;
        this.orig = this.preProcess();
        this.auto = arguments[1] || true;
        this.tplRan = false;
        this.stateVal = 0;
        this.ticks = 0;
        this.cid = this.el.attr('id');
        this.iid = iid;
        var options = arguments[2] || {};
        this.callback = options.callback ||
        function() {};
        this.animate = options.animate || false;
        this.animateCallback = options.animateCallback ||
        function() {};
        if (this.animate) {
            this.el.hide();
        }
        if (this.auto) this.transform();
    },
    preProcess: function(str) {
        str = str || this.el.html();
        return str.replace(/\r|\n/gi, '');
    },
    transform: function(forceTpl) {
        var tpl = forceTpl ? (forceTpl == true ? this.tplRan: forceTpl) : 'default';
        if (this.tplRan == tpl && !forceTpl) return false;
        var c = this.el.attr('class');
        c = c ? c.split(' ') : [];
        var cq = {
            remove: [],
            add: []
        }
        var cc = function(i) {
            return c.indexOf(i) != -1;
        }
        var isOff = function() {
            return ['below', 'buried', 'blocked', 'deleted'].indexOf(tpl) == -1 ? false: true;
        }
        var reg = /([^,]+),\s(.+?),\s([-+\/\d]+)<span>(.*?)<\/span>(Dugg[^<]+)?(<ul.+<\/ul>)?/i;
        var res = reg.exec(this.orig);
        if (!res) return false;
        var user = res[1];
        var stamp = res[2];
        var comment = res[4];
        var diggs = [];
        $j.each(res[3].split('/'),
        function(i, num) {
            diggs.push(Math.abs(num));
        });
        diggs.push(diggs[1] - diggs[0]);
        if (diggs[2] > 0) diggs[2] = '+' + diggs[2];
        if (cc('c-disabled')) cq['remove'].push('c-disabled');
        if (!forceTpl) {
            if (diggs[2] < CommentsSettings.threshold && !cc('u')) {
                tpl = 'below';
            }
            if (cc('g')) {
                tpl = 'default';
                this.state(1);
                cq['remove'].push('g');
            } else if (cc('b') || this.state() == -1) {
                tpl = 'buried'this.state( - 1);
                cq['remove'].push('b');
            }
            if (cc('k')) {
                tpl = 'blocked';
            }
            if (cc('x')) {
                tpl = 'deleted';
            }
        }
        var reportLink = 'Is \':user:\' being offensive? <a class="c-report">Report it</a>';
        if (cc('r')) reportLink = 'Report received. Thanks!';
        var replyLink = '<a class="c-reply-link">Reply</a></div>';
        var l = /l(\d+)/.exec(c.join(' '));
        if (l && l.length > 1 && l[1] >= CommentsSettings.replytolevel) {
            replyLink = '';
        }
        var threadLink = '<a href=' + $j(stamp).attr('href') + ' class="c-thread-link">Thread</a> / ';
        if (CommentsSettings && CommentsSettings.sort != 5) {
            threadLink = '';
        }
        var mine = false;
        if (cc('u') || cc('c-mine')) {
            cq['remove'].push('u');
            cq['add'].push('c-mine');
            mine = true;
        } else if (cc('f')) {
            cq['remove'].push('f');
            cq['add'].push('c-friend');
        }
        var friends = (res[5] != undefined && res[5].length > 0) ? res[5].replace(/([:|,]\s)(\w+)/gi, "$1<a href=\"/users/$2\">$2</a>") : '';
        if (friends) {
            friends = '<div class="c-friends">' + friends + '</div>';
        }
        var children = res[6] || '';
        if (children.length > 0) {
            var firstLevel = $j(children);
            firstLevel.find('ul').remove();
            firstLevel = '<ul id="p' + this.cid + '">' + firstLevel.html() + '</ul>';
            var best = -Infinity;
            var bestArr = regArray(/-(\d+)\/\+(\d+)/g, firstLevel);
            var childCount = bestArr.length - 1;
            $j.each(bestArr,
            function(i, pair) {
                var total = pair[1] - pair[0];
                if (total > best) best = total;
            });
            children = '<a id="c-replies-' + this.cid + '" class="c-box c-replies"><em>' + childCount + ' ' + pluralize('Reply', childCount) + '</em> &#8212; best has ' + best + ' ' + pluralize('digg', best) + '</a>' + children;
        }
        var replyLink = '<a class="c-reply-link">Reply</a></div>';
        var l = /l(\d+)/.exec(c.join(' '));
        if (l && l.length > 1 && l[1] >= CommentsSettings.replytolevel) {
            replyLink = '<span class="c-reply-link"></span></div>';
            threadLink = '<a href=' + $j(stamp).attr('href') + ' class="c-thread-link">Thread</a>';
        }
        this.content = {
            'cid': this.cid,
            'user': user,
            'stamp': stamp,
            'comment': comment,
            'diggs': '<em>' + diggs[2] + '</em> ' + pluralize('digg', diggs[2]),
            'diggs-up': diggs[1],
            'diggs-dn': diggs[0],
            'friends': friends,
            'children': children,
            'block': tpl == 'buried' ? (cc('k') ? '': '<a class="c-block">Block User</a>') : '',
            'disabled-replies': childCount > 0 ? '<span class="c-disabled-replies">(' + childCount + ' ' + pluralize('reply', childCount) + ')</span>': '',
            'reply-link': replyLink,
            'thread-link': threadLink
        };
        var states = {
            'digg': 'src="/img/c-digg.png"',
            'bury': 'src="/img/c-bury.png"'
        };
        if (this.state() == -1 || mine) {
            states['bury'] = 'src="/img/c-bury-off.png" class="c-disabled"';
        }
        if (this.state() == 1 || mine) {
            states['digg'] = 'src="/img/c-digg-off.png" class="c-disabled"';
        }
        var templates = {
            'default': '<div class="c-diggs"><a>:diggs:</a>\
                <a style="display: none"><em>+:diggs-up:</em> / <span>-:diggs-dn:</span></a>\
                <img ' + states['bury'] + ' id="bury-:cid:" width="18" height="18" alt="" />\
                <img ' + states['digg'] + ' id="digg-:cid:" width="18" height="18" alt="" />\
            </div>\
            <div class="c-head">\
            <strong><a id="c-auth:cid:" href="/users/:user:">:user:<img src="/users/:user:/s.png" alt=":user:" width="16" height="16" /> </a></strong><br /> :stamp:\
            </div>:friends:\
            <div id="c-text-:cid:" class="c-body">:comment:</div><div class="c-box">:thread-link: :reply-link: :children:',
            'below': '<div class="c-diggs"><a>:diggs:</a>\
                <a style="display: none"><em>+:diggs-up:</em> / <span>-:diggs-dn:</span></a>\
                <img src="/img/c-bury-off.png" class="c-disabled" id="bury-:cid:" width="18" height="18" alt="" />\
                <img src="/img/c-digg-off.png" class="c-disabled" id="digg-:cid:" width="18" height="18" alt="" />\
            </div>\
            <div class="c-head">\
            <strong><a id="c-auth:cid:" href="/users/:user:">:user:<img src="/users/:user:/s.png" alt=":user:" width="16" height="16" /> </a></strong><br /> :stamp:\
            </div>:friends:\
            <div>Below viewing threshold. &nbsp; <a class="c-show">Show</a> :disabled-replies: </div><div id="c-text-:cid:" class="c-body">:comment:</div><div class="c-box">:thread-link: :reply-link: :children:',
            'blocked': '<div class="c-diggs"><a>:diggs:</a>\
                <a style="display: none"><em>+:diggs-up:</em> / <span>-:diggs-dn:</span></a>\
                <img src="/img/c-bury-off.png" class="c-disabled" id="bury-:cid:" width="18" height="18" alt="" />\
                <img src="/img/c-digg-off.png" class="c-disabled" id="digg-:cid:" width="18" height="18" alt="" />\
            </div>\
            <div class="c-head">\
            <strong><a id="c-auth:cid:" href="/users/:user:">:user:<img src="/users/:user:/s.png" alt=":user:" width="16" height="16" /> </a></strong><br /> :stamp:\
            </div>:friends:\
            <div>Blocked user. &nbsp; <a class="c-show">Show</a> :disabled-replies: </div><div id="c-text-:cid:" class="c-body">:comment:</div><div class="c-box">:thread-link: :reply-link: :children:',
            'buried': '<div class="c-diggs"><a>:diggs:</a>\
                <a style="display: none"><em>+:diggs-up:</em> / <span>-:diggs-dn:</span></a>\
                <img ' + states['bury'] + ' id="bury-:cid:" width="18" height="18" alt="" />\
                <img ' + states['digg'] + ' id="digg-:cid:" width="18" height="18" alt="" />\
            </div>\
            <div class="c-head">\
            <strong><a id="c-auth:cid:" href="/users/:user:">:user: <img src="/users/:user:/s.png" alt=":user:" width="16" height="16" /> </a></strong><br /> :block:\
            </div>\
            <div class="c-bury-head">\
            Comment buried! &nbsp; <a class="c-show">Show</a> :disabled-replies: <br />\
            <span> ' + reportLink + ' </span>\
            </div><div id="c-text-:cid:" class="c-body">:comment:</div><div class="c-box">:thread-link: :reply-link: :children:',
            'deleted': '<div class="c-head">\
            <strong><a id="c-auth:cid:" href="/users/:user:">:user:<img src="/users/:user:/s.png" alt=":user:" width="16" height="16" /> </a></strong><br /> :stamp: </div>\
            <div class="c-bury-head">This comment has been deleted. <a class="c-show">Show</a> :disabled-replies:</div><div class="c-box">:thread-link: :reply-link: :children:'
        }
        var _this = this;
        var finished = templates[tpl].replace(/:([\w-]*):/g,
        function() {
            var match = arguments[1];
            if (_this.content[match] != undefined{
                return _this.content[match];
            }
            return '';
        });
        $j.each(cq,
        function(key, val) {
            if (val.length > 0) _this.el[key + 'Class'](val.join(' '));
        });
        this.el.show().get(0).innerHTML = finished;
        $j('.c-body a', this.el).click(function() {
            window.open(this.href);
            return false;
        });
        if (isOff()) {
            this.toggleDisabled(this.el, 'add');
        }
        if (plusMinus) $j('.c-diggs a', this.el).toggle();
        this.tplRan = tpl;
        this.behave();
        if (cc('e') && tpl == 'default'{
            this.countDown();
        }
        if (this.animate) {
            this.el[this.animate](function() {
                _this.animateCallback();
            });
        }
    },
    behave: function() {
        var _this = this;
        var cidNum = this.el.attr('id').replace('c', '');
        $j('.c-replies', this.el).unbind().click(function(e) {
            if (this.lock == true{
                return;
            }
            this.lock = true;
            var _thisEl = $j(this);
            var parId = _this.el.id;
            var reply = this;
            _this.el.children('ul').append('<li class="c-foot">\
                <a class="c-box c-reply-link"><strong>Reply</strong> to this thread</a>\
            </li>').find('.c-reply-link').click(function(e) {
                if (CommentsSettings && CommentsSettings.isLoggedIn) {
                    _this.toggleReplyBox();
                } else {
                    _this.error('You have to be logged in to do that. <a href="/login">Login</a> or <a href="/register">join now</a>.');
                }
                e.preventDefault();
            });
            new Comments('ul > li', _this.el, {
                threadCallback: function() {
                    reply.lock = false;
                    _thisEl.toggleClass('c-open');
                    if (_thisEl.hasClass('viaReply')) {
                        $j.scrollTo($j(_this.el).children(':last-child'), 500, {
                            offset: -250
                        });
                        _thisEl.removeClass('viaReply');
                    }
                }
            });
            _thisEl.unbind().click(function(e) {
                if (this.lock == true{
                    return;
                }
                this.lock = true;
                $j("li[@class*='c-disabled'] ul", _this.el).hide();
                $j("li[@class*='c-disabled'] .c-replies").removeClass('c-open');
                $j('ul', _this.el).toggle();
                _thisEl.toggleClass('c-open');
                e.preventDefault();
                this.lock = false;
            });
            e.preventDefault();
        });
        $j('.c-reply-link', this.el).unbind().click(function(e) {
            if (CommentsSettings && CommentsSettings.isLoggedIn) {
                _this.toggleReplyBox();
            } else {
                _this.error('You have to be logged in to do that. <a href="/login">Login</a> or <a href="/register">join now</a>.');
            }
            e.preventDefault();
        });
        $j('#digg-' + this.cid, this.el).unbind().click(function(e) {
            if (_this.checkDisabled(this)) return false;
            var bury = $j('#bury-' + _this.cid);
            _this.toggleDisabled([this, bury], 'add');
            $j.ajax({
                'url': '/ajax/comments/digg',
                'async': true,
                'type': 'POST',
                'dataType': 'json',
                'data': {
                    'id': cidNum,
                    'up': 1,
                    'token': tokens.comments.digg
                },
                'success': function(json) {
                    _this.error(false);
                    _this.update(json, 1);
                    if (_this.tplRan == 'buried' || _this.tplRan == 'below'{
                        _this.transform('default');
                    } else {
                        _this.applyState();
                    }
                    analyticsEvent('event12', 'digg comment');
                },
                'error': function(xml) {
                    _this.applyState();
                    var json = eval('(' + xml.responseText + ')');
                    _this.error(json.error);
                }
            });
        });
        this.el.find('#bury-' + this.cid).unbind().click(function(e) {
            if (_this.checkDisabled(this)) return false;
            var digg = $j('#digg-' + _this.cid);
            _this.toggleDisabled([this, digg], 'add');
            $j.ajax({
                'url': '/ajax/comments/digg',
                'async': true,
                'type': 'POST',
                'dataType': 'json',
                'data': {
                    'id': cidNum,
                    'up': 0,
                    'token': tokens.comments.digg
                },
                'success': function(json) {
                    _this.error(false);
                    _this.update(json, -1);
                    if (_this.state() == -1) {
                        _this.transform('buried');
                    } else {
                        _this.applyState();
                    }
                    analyticsEvent('event12', 'bury comment');
                },
                'error': function(xml) {
                    _this.applyState();
                    var json = eval('(' + xml.responseText + ')');
                    _this.error(json.error);
                }
            });
        });
        $j('.c-show', this.el).unbind().click(function(e) {
            _this.el.children().not('ul').find('.c-disabled-replies, a.c-box, .c-body').toggle();
            _this.toggleDisabled(_this.el);
            $j(this).parent().toggleClass('c-disabled-open');
            var action = 'ShowHide'.replace($j(this).text(), '') $j(this).text(action);
            if (action == 'Show'{
                $j('.c-open', _this.el).removeClass('c-open');
                $j('ul', _this.el).hide();
                if ($j.inArray(_this.tplRan, ['below', 'blocked']) != -1) {
                    _this.toggleDisabled({
                        'add': [$j('#digg-' + _this.cid), $j('#bury-' + _this.cid)]
                    });
                } else {
                    _this.applyState();
                }
            } else {
                _this.applyState();
            }
            e.preventDefault();
        });
        $j('.c-block', this.el).unbind().click(function(e) {
            $j.ajax({
                'url': '/ajax/comments/block',
                'async': true,
                'type': 'POST',
                'dataType': 'json',
                'data': {
                    'username': $j('#c-auth' + _this.cid, _this.el).attr('href').replace('/users/', ''),
                    'token': tokens.comments.block
                },
                'success': function(json) {
                    _this.error(false);
                    _this.transform('blocked');
                    analyticsEvent('event12', 'block user');
                },
                'error': function(xml) {
                    _this.error('Sorry, your block request didn\'t send. Please try again.');
                }
            });
            e.preventDefault();
        });
        $j('.c-report', this.el).unbind().click(function(e) {
            var _thisEl = $j(this);
            $j.ajax({
                'url': '/ajax/comments/jerk',
                'async': true,
                'type': 'POST',
                'dataType': 'json',
                'data': {
                    'id': cidNum,
                    'token': tokens.comments.jerk
                },
                'success': function(json) {
                    _this.error(false);
                    _thisEl.parent().text('Report received! Thanks.');
                    analyticsEvent('event12', 'jerk report');
                },
                'error': function(xml) {
                    _this.error('Sorry, your report failed to send. Please try again.');
                }
            });
            e.preventDefault();
        });
        $j('.c-diggs a', this.el).unbind().click(function(e) {
            $j('.c-diggs a').toggle();
            $j('.comment').toggleClass('c-plus-minus');
        });
        if (this.callback) {
            this.callback();
            this.callback = null;
        }
    },
    checkDisabled: function(el) {
        return $j(el).hasClass('c-disabled');
    },
    toggleDisabled: function(el, force) {
        var _this = this;
        var force = force || 'toggle';
        if (!el) return false;
        if (el.constructor == Array && !el.jquery) {
            $j.each(el,
            function(i, val) {
                _this.toggleDisabled(val, force);
            });
            return;
        } else if (el.constructor == Object && !el.jquery) {
            $j.each(el,
            function(key, val) {
                _this.toggleDisabled(val, key);
            });
            return;
        }
        el = $j(el);
        if (el.length > 0 && el.get(0).nodeName && el.get(0).nodeName.toLowerCase() == 'img'{
            var src = el.attr('src');
            var off = src.indexOf('-off') > -1;
            if (off && force == 'remove'{
                el.attr('src', src.replace('-off', ''));
            } else if (!off && force == 'add'{
                el.attr('src', src.replace(/(.*?)(\.(png|gif|jpg|jpeg))/, "$1-off$2"));
            } else if (force == 'toggle'{
                if (off) {
                    el.attr('src', src.replace('-off', ''));
                } else {
                    el.attr('src', src.replace(/(.*?)(\.(png|gif|jpg|jpeg))/, "$1-off$2"));
                }
            }
        }
        el[force + 'Class']('c-disabled');
    },
    update: function(json, delta) {
        var reg = /-(\d+)\/\+(\d+)/;
        this.state(this.state() + delta);
        this.orig = this.orig.replace(reg,
        function(match, p1, p2, offset, s) {
            return '-' + json.down + '/+' + json.up;
        });
        var diggLinks = $j('.c-diggs a', this.el);
        $j(diggLinks.get(0)).find('em').text(json.newcount);
        $j(diggLinks.get(1)).find('em').text('+' + json.up);
        $j(diggLinks.get(1)).find('span').text('-' + json.down);
    },
    state: function(value) {
        if (value == undefined{
            return this.stateVal;
        } else {
            return this.stateVal = value;
        }
    },
    applyState: function() {
        var digg = $j('#digg-' + this.cid, this.el);
        var bury = $j('#bury-' + this.cid, this.el);
        var state = this.state() + 1;
        if (this.el.hasClass('c-mine')) state = 3;
        var stateMap = [{
            'add': bury,
            'remove': digg
        },
        {
            'remove': [digg, bury]
        },
        {
            'add': digg,
            'remove': bury
        },
        {
            'add': [digg, bury]
        }];
        this.toggleDisabled(stateMap[state]);
    },
    loadCaptcha: function() {
        var _this = this;
        $j('.c-captcha').remove();
        $j('#c-reply-' + this.cid + ' textarea').after('<div class="c-captcha"><img src="/img/c-spinner.gif" alt=""/> Loading captcha...</div>');
        $j('#c-reply-' + this.cid + ' :submit').attr('disabled', 'disabled');
        $j.ajax({
            'url': '/get_captcha',
            'async': true,
            'type': 'GET',
            'dataType': 'json',
            'data': {
                'tpl': 'json',
                'keyname': 'uuddlrlrba'
            },
            'success': function(json) {
                $j('#c-reply-' + _this.cid + ' .c-captcha').html('<img src="' + json.src + '" height="' + json.height + '" width="' + json.width + '" alt="captcha!" /><input type="hidden" id="c-md5-' + _this.cid + '" value="' + json.md5 + '" /><label for="c-captcha-' + _this.cid + '">Enter the text you see in the image.</label><input id="c-captcha-' + _this.cid + '" type="text" />');
                $j('#c-reply-' + _this.cid + ' :submit').removeAttr('disabled');
            },
            'error': function(xml) {
                var json = eval('(' + xml.responseText + ')');
                _this.error(json.error);
            }
        });
    },
    toggleReplyBox: function(dir) {
        var reply = $j('#c-reply-' + this.cid);
        if (!dir) {
            if (reply.length > 0) {
                dir = 'remove';
            } else {
                dir = 'add';
            }
        }
        if (dir == 'add'{
            $j("div[@id^='c-reply']").remove();
            this.el.append('<div id="c-reply-' + this.cid + '">\
                <form action="#">\
                <textarea cols="10" rows="6"></textarea>\
                <div class="c-note">Please allow up to 60 sec for your comment to be saved.</div>\
                <input type="submit" value="Save Reply" /> <a class="c-spellcheck">Check Spelling</a>\
                </form>\
            </div>');
            if (CommentsSettings.captcha) {
                this.loadCaptcha();
            }
            reply = $j('#c-reply-' + this.cid);
            $j('textarea', reply).focus();
            var replies = this.el.children('#c-replies-' + this.cid);
            if (replies.length > 0) {
                if (!replies.hasClass('c-open')) {
                    replies.addClass('viaReply');
                    replies.click();
                }
            }
            var _this = this;
            var cidNum = this.cid.replace('c', '');
            $j('form', reply).unbind().submit(function(e) {
                var _thisEl = $j(this);
                _thisEl.children(':submit').attr('disabled', 'disabled');
                var data = {
                    'itemid': _this.iid,
                    'parent': cidNum,
                    'cntType': 'story',
                    'comments': $j('textarea', this).val(),
                    'token': tokens.comments.post
                };
                var captcha = _thisEl.children('.c-captcha');
                if (captcha.length > 0) {
                    data['captcha'] = captcha.find(':text').val();
                    data['md5'] = captcha.find(':hidden').val();
                }
                $j.ajax({
                    'url': '/ajax/comments/post.html',
                    'async': true,
                    'type': 'POST',
                    'dataType': 'html',
                    'data': data,
                    'success': function(html) {
                        _this.error(false);
                        CommentsSettings.captcha = false;
                        var mine = $j('#c-menu-mine');
                        mine.removeClass('c-disabled');
                        var mineCheck = /(\d+)/.exec(mine.text());
                        var inc = mineCheck != null ? parseInt(/(\d+)/.exec(mine.text())[1]) + 1: 1;
                        if (mineCheck != null{
                            mine.text(mine.text().replace(/(\d+)/, inc));
                        } else {
                            mine.text(mine.text() + ' (1)');
                        }
                        reply.hide(100,
                        function() {
                            _this.addReply(html);
                        });
                        analyticsEvent('event11', 'comment');
                    },
                    'error': function(xml) {
                        var json = eval('(' + xml.responseText + ')');
                        _this.error(json.error);
                        _this.loadCaptcha();
                    }
                });
                e.preventDefault();
            });
            $j('.c-spellcheck', reply).click(function(e) {
                new spellChecker($j(this).siblings('textarea').get(0)).openChecker();
                e.preventDefault();
            });
        } else {
            reply.remove();
        }
    },
    toggleEditBox: function(dir) {
        var ticks = this.ticks || 1;
        var minutes = Math.floor(ticks / 60);
        var seconds = Math.floor(ticks % 60);
        if (!dir) {
            if (this.el.hasClass('c-editing')) {
                dir = 'remove';
            } else {
                dir = 'add';
            }
        }
        if (dir == 'add'{
            var oldComment = this.el.children('.c-body').html().replace(/<br>/gi, "\n").replace(/<a class="user" href="(.+)">.+<\/a>/, "$1");
            this.el.addClass('c-editing');
            this.el.children('.c-diggs, .c-head, .c-body, div.c-box, .c-edit').remove();
            this.el.prepend('<div class="c-edit"><strong>Edit Comment</strong> (<span class="c-tick">' + minutes + 'm ' + seconds + 's</span>...)</div>\
                <form action="#">\
                    <textarea cols="10" rows="6">' + oldComment + '</textarea>\
                    <a class="c-delete">Delete</a>\
                    <input type="submit" value="Save Changes" /> <input type="button" class="c-cancel" value="Cancel" style="color: #666;" /> <a class="c-spellcheck">Check Spelling</a>\
                </form>');
            var _this = this;
            this.el.children('form').find('textarea').focus().select();
            var cidNum = this.cid.replace('c', '');
            $j('form', this.el).unbind().submit(function(e) {
                var _thisEl = $j(this);
                _thisEl.children(':submit').attr('disabled', 'disabled');
                $j.ajax({
                    'url': '/ajax/comments/edit.html',
                    'async': true,
                    'type': 'POST',
                    'dataType': 'html',
                    'data': {
                        'id': cidNum,
                        'comments': $j('textarea', this).val(),
                        'token': tokens.comments.edit
                    },
                    'success': function(html) {
                        _this.error(false);
                        var mine = $j('#c-menu-mine');
                        var inc = parseInt(/(\d+)/.exec(mine.text())[1]) - 1;
                        if (inc < 0) inc = 0;
                        if (inc == 0) {
                            mine.addClass('c-disabled');
                        }
                        mine.text(mine.text().replace(/(\d+)/, inc));
                        var content = $j(html);
                        var newOrig = _this.preProcess(content.html());
                        var children = /(<ul>.*<\/ul>)$/.exec(_this.orig);
                        children = children ? children[1] : '';
                        var foo = newOrig + children;
                        _this.el.html(foo);
                        _this.el.removeClass('c-editing');
                        new Comments($j('#' + _this.cid));
                        analyticsEvent('event12', 'update comment');
                    },
                    'error': function(xml) {
                        var json = eval('(' + xml.responseText + ')');
                        _this.error(json.error);
                        _thisEl.children(':submit').removeAttr('disabled');
                    }
                });
                e.preventDefault();
            });
            $j('.c-delete', this.el).click(function(e) {
                if (!confirm('Are you sure you want to delete this comment? Once it\'s gone, it\'s gone for good.')) {
                    e.preventDefault();
                    return false;
                }
                $j.ajax({
                    'url': '/ajax/comments/del',
                    'async': true,
                    'type': 'POST',
                    'dataType': 'json',
                    'data': {
                        'id': cidNum,
                        'token': tokens.comments.del
                    },
                    'success': function(json) {
                        _this.error(false);
                        analyticsEvent('event12', 'delete comment');
                        var mine = $j('#c-menu-mine');
                        var inc = parseInt(/(\d+)/.exec(mine.text())[1]) - 1;
                        if (inc < 0) inc = 0;
                        if (inc == 0) {
                            mine.addClass('c-disabled');
                            inc = '';
                        }
                        if (inc != '') inc = '(' + inc + ')';
                        mine.text(mine.text().replace(/(\(\d+\))/, inc));
                        if ($j('ul', _this.el).length == 0) {
                            var sibs = _this.el.siblings(':not(.c-foot)');
                            if (sibs.length == 0) {
                                var par = _this.el.parent();
                                par.siblings('a.c-box').remove();
                                par.remove();
                            }
                            _this.el.remove();
                        } else {
                            _this.el.removeClass('c-editing');
                            _this.transform('deleted');
                        }
                    },
                    'error': function(xml) {
                        var json = eval('(' + xml.responseText + ')');
                        _this.error(json.error);
                    }
                });
                e.preventDefault();
            });
            $j('.c-cancel', this.el).click(function() {
                _this.toggleEditBox();
            });
            $j('.c-spellcheck', this.el).click(function(e) {
                new spellChecker($j(this).siblings('textarea').get(0)).openChecker();
                e.preventDefault();
            });
        } else {
            this.el.removeClass('c-editing');
            this.transform(true);
        }
    },
    addReply: function(html) {
        var orig = $j('<li>' + this.orig + '</li>');
        var ul = orig.children('ul');
        if (ul.length > 0) {
            ul.append(html);
        } else {
            orig.append('<ul>' + html + '</ul>');
        }
        this.orig = this.preProcess(orig.html());
        var content = $j(html);
        var newId = content.attr('id');
        this.callback = function() {
            $j('.c-show', this.el).click();
            $j('#c-replies-' + this.cid, this.el).click();
            var newReply = $j('#' + newId);
            newReply.css('background-color', '#DCECF4');
            newReply.animate({
                backgroundColor: '#fefad4'
            },
            2000);
        }
        this.transform(true);
    },
    countDown: function() {
        var _this = this;
        var numId = this.cid.replace('c', '');
        var editable = (CommentsSettings.editable && CommentsSettings.editable[numId]) ? CommentsSettings.editable[numId] : false;
        var start = this.ticks || editable || (60 * 5);
        this.ticks = start;
        var minutes = Math.floor(this.ticks / 60);
        var seconds = Math.floor(this.ticks % 60);
        this.el.children('.c-head').after('<div class="c-edit"><a>Edit</a> (<span class="c-tick">' + minutes + 'm ' + seconds + 's</span>...)</div>');
        this.el.children('.c-edit').click(function() {
            _this.toggleEditBox();
        });
        try {
            clearTimeout(window['tickers'][this.cid]);
        } catch(noTickerYet) {}
        this.tick();
    },
    tick: function() {
        var _this = this;
        this.ticks--;
        var minutes = Math.floor(this.ticks / 60);
        var seconds = Math.floor(this.ticks % 60);
        var edit = this.el.children('.c-edit');
        if (this.ticks < 1) {
            $j(':submit', edit).attr('disabled', 'disabled');
            edit.fadeOut(function() {
                $j(this).remove();
            });
        } else {
            $j('.c-tick', edit).text(minutes + 'm ' + seconds + 's');
            if (!window['tickers']window['tickers'] = {};
            window['tickers'][this.cid] = setTimeout(function() {
                _this.tick();
            },
            1000);
        }
    },
    error: function(msg) {
        $j('.warning').remove();
        if (!msg) return false;
        this.el.before('<li class="warning">' + msg + '</li>');
        var w = $j('.warning');
        w.show();
        $j.scrollTo(w, 500);
    }
});
var CommentsData = $j.extend(new Function().prototype, {
    get: function(filter, sort, page) {
        var _this = this;
        filter = filter || this.lastFilter || 'all';
        this.lastFilter = filter;
        sort = sort || this.lastSort || CommentsSettings.sort || 1;
        this.lastSort = sort;
        page = page || 1;
        var endpoint = '';
        switch (filter) {
        case 'all':
            endpoint = 'loadPage';
            break;
        case 'friends':
            endpoint = 'loadFriends';
            break;
        case 'mine':
            endpoint = 'loadMine';
            break;
        }
        if (page == 1) {
            $j('.comment').html('<div class="c-spinner"><img src="/img/c-spinner.gif" alt="Fetching more discussions..." /></div>');
        }
        $j.ajax({
            'url': '/ajax/comments/' + endpoint + '.html',
            'async': true,
            'type': 'POST',
            'dataType': 'html',
            'data': {
                'id': $j('.news-body').attr('id'),
                'sort': sort,
                'page': page,
                'token': tokens.comments[endpoint]
            },
            'success': function(html) {
                $j('.c-message, .warning').remove();
                _this.insert(html, page);
            },
            'error': function(xml) {
                var json = eval('(' + xml.responseText + ')');
                if (page == 1) {
                    $j('.comment').html('<ul><li class="warning"><h3>ERROR!</h3> The comments you requested failed to load. This is clearly Kevin\'s fault. Try again!</li></ul>').find('.warning').show();
                } else {
                    $j('.warning').remove();
                    $j('.show-more').parent().before('<li class="warning"><h3>ERROR!</h3> The comments you requested failed to load. This is clearly Kevin\'s fault. Try again!</li>');
                    $j('.warning').show();
                    $j('div.show-more').hide();
                    $j('a.show-more').show();
                }
            }
        });
    },
    insert: function(html, page) {
        if (page == 1) {
            $j('.comment').replaceWith(html);
            new Comments();
        } else {
            var content = $j(html);
            $j('.show-more').parent().replaceWith(content);
            new Comments(content);
        }
    }
});
var Queue = function() {
    this.init.apply(this, arguments);
}
$j.extend(Queue.prototype, {
    init: function() {
        this.q = [];
        this.on = false;
        this.i = 0;
        this.spliced = [];
        this.delay = 10;
        this.t = this.count = this.total = null;
        try {
            threadCallbacks;
        } catch(noCallbacks) {
            threadCallbacks = {};
        }
    },
    add: function(args) {
        if (!args || args.f.constructor != Functionthrow new Error('Bad param dude, not cool.');
        var splice = args.splice || false;
        var i = this.i + 1;
        if (this.spliced.indexOf(i) != -1) i++;
        if (args.obj) {
            if (splice) {
                this.q.splice(i, 0, {
                    'func': args.f,
                    'obj': args.obj
                });
                this.spliced.push(i);
            } else {
                this.q.push({
                    'func': args.f,
                    'obj': args.obj
                });
            }
        } else {
            if (splice) {
                this.q.splice(i, 0, args.f);
                this.spliced.push(i);
            } else {
                this.q.push(args.f);
            }
        }
    },
    start: function() {
        if (this.on || this.q.length == 0) return;
        this.run();
    },
    isOn: function() {
        return this.on;
    },
    run: function() {
        var _this = this;
        var l = this.q.length;
        var i = this.i;
        if (i < l) {
            this.on = true;
            clearTimeout(this.t);
            if (this.q[i].constructor == Object{
                threadCallbacks[this.q[i]['obj']] = function() {
                    _this.i++;
                    _this.run();
                }
                this.q[i]['func']();
            } else {
                setTimeout(function() {
                    _this.i++;
                    _this.run();
                },
                this.delay);
                this.q[i]();
            }
        } else {
            this.on = false;
        }
        if (window.location.hash) {
            $j.scrollTo(window.location.hash, 500);
            $j('.c-head > a').click(function() {
                hash = '#' + this.href.split('#')[1];
                $j.scrollTo(hash, 500);
                window.location.hash = hash;
                return false;
            });
        }
    }
});
var regArray = function(reg, str, cb) {
    var res,
    i = 0,
    ret = [];
    while (res = reg.exec(str)) {
        res.splice(0, 1);
        ret.push(res.length > 1 ? res: res[0]);
        i++;
    }
    ret.splice(0, 0, i);
    return ret;
}
var pluralize = function(word, i) {
    if (!word || i == undefinedreturn false;
    if (i != 1) {
        return word.replace(/y$/, 'ies').replace(/([^s])$/, '$1s');
    } else {
        return word.replace(/ies$/, 'y').replace(/s$/, '');
    }
}
$j(document).ready(function() {
    try {
        CommentsSettings;
    } catch(err) {
        return false;
    }
    iid = $j('.news-body').attr('id');
    new Comments(false, false, {
        threadCallback: function() {
            if (CommentsSettings && CommentsSettings.commentlevels == 0) {
                $j('#c-menu-all').click();
            }
        }
    });
    $j('#c-menu-mine').click(function(e) {
        if ($j(this).hasClass('c-disabled')) return false;
        var all = $j('#c-menu-all');
        all.addClass('do-work-son').text(all.text().replace('expand', 'collapse'));
        var commentsSort = $j('#c-sort option:selected').attr('value');
        CommentsData.get('mine', commentsSort);
        e.preventDefault();
    });
    $j('#c-menu-friends').click(function(e) {
        if ($j(this).hasClass('c-disabled')) return false;
        var all = $j('#c-menu-all');
        all.addClass('do-work-son').text(all.text().replace('expand', 'collapse'));
        var commentsSort = $j('#c-sort option:selected').attr('value');
        CommentsData.get('friends', commentsSort);
        e.preventDefault();
    });
    $j('#c-sort').change(function(e) {
        var val = $j(':selected', this).val();
        var all = $j('#c-menu-all');
        var action = val == 5 ? 'add': 'remove';
        all[action + 'Class']('c-disabled');
        if (action == 'add'{
            all.removeClass('do-work-son').text('expand all');
        }
        CommentsData.get(false, val);
        CommentsSettings.sort = val;
        e.preventDefault();
    });
    $j('#c-menu-all').click(function(e) {
        var _this = $j(this);
        if (_this.hasClass('c-disabled')) return false;
        _this.toggleClass('do-work-son');
        var reg = /^(\w+)\s/;
        var verb = reg.exec(_this.text())[1];
        var newVerb = 'expandcollapse'.replace(verb, '');
        _this.text(_this.text().replace(reg, newVerb + ' '));
        try {
            delete q;
        } catch(noQueue) {}
        q = new Queue();
        var ulId = $j('.comment ul').attr('id');
        $j('a.c-replies', 'li:not(.c-disabled)').each(function() {
            var _that = $j(this);
            var open = _that.hasClass('c-open');
            var work = _this.hasClass('do-work-son');
            var ulId = _that.siblings('ul').attr('id');
            if (!open && work) {
                var firstLi = _that.siblings('ul').children('li').attr('id');
                if (diggComments[firstLi]{
                    q.add({
                        f: function() {
                            _that.click();
                        }
                    });
                } else {
                    q.add({
                        f: function() {
                            _that.click();
                        },
                        obj: ulId
                    });
                }
            } else if (open && !work) {
                q.add({
                    f: function() {
                        _that.click();
                    }
                });
            }
        });
        q.start();
    });
    var cheatCode = '38384040373937399897';
    var cheat = '';
    var cheatOut = false;
    $j(document).keypress(function(key) {
        clearTimeout(cheatOut);
        if (cheat.length < cheatCode.length) {
            var k = (key.keyCode == 0) ? key.charCode: key.keyCode;
            cheat = cheat + String(k);
            if (cheat == cheatCode) {
                $j('#c-menu-all').click();
            }
        }
        cheatOut = setTimeout(function() {
            cheat = '';
        },
        2000);
    });
});