﻿function createTNode(tStampAtt) {
    var newTNode = document.createTextNode(tStampAtt[0]);
    $.getJSON("http://www.gaucho.com/handler/get_stamp_bbcode.ashx?cacheId=" + tStampAtt[1] + "&jsoncallback=?", function(ret) {
        if (ret.ret == 0) {
            var stampObj = ret.stamp;
            var stampDiv = GetStampObjDisplay(stampObj[0]);
            var stampWrapper = stampDiv.find('.stampbox');
            $(newTNode).after(stampWrapper);
            $(newTNode).remove();
        }
    });
    return newTNode;
}

jQuery.fn.RenderStampBBCode = function() {
    return this.each(function() {
        var $ = jQuery,
        c = $(this).find('*:not(iframe)').contents().filter(function() {
            try {
                return this.nodeType == 3 && $.trim(this.nodeValue).length > 0 && $(this).parents('a').length == 0 && $(this).parents('.nostampbb').length == 0;
            } catch (Error) {
                return false;
            }
        });
        c.each(function() {
            if (this.nodeValue) {
                var cNode = $(this);
                var lastPos = 0;
                var bHasStamp = false;
                while (true) {
                    var stampRe = /\[stamp:\d+\]/;
                    var tStr = this.nodeValue.substr(lastPos);
                    var stampStr = stampRe.exec(tStr);
                    if (stampStr) {
                        bHasStamp = true;
                        var iPos = this.nodeValue.indexOf(stampStr[0], lastPos);
                        if (lastPos != iPos) {
                            var sText = this.nodeValue.substr(lastPos, iPos - lastPos);
                            var newTextNode = document.createTextNode(sText);
                            cNode.after(newTextNode);
                            cNode = $(newTextNode);
                        }
                        var stampAtt = /\[stamp:(\d+)\]/.exec(stampStr[0]);
                        if (stampAtt) {
                            newTNode = createTNode(stampAtt);
                            cNode.after(newTNode);
                            cNode = $(newTNode);
                        }
                        lastPos = iPos + stampStr[0].length;
                        continue;
                    }
                    break;
                }
                if (bHasStamp) {
                    var tStr = this.nodeValue.substr(lastPos);
                    var newTextNode = document.createTextNode(tStr);
                    cNode.after(newTextNode);
                    $(this).remove();
                }
            }
        });
    })
};
$(document).ready(function() {
    $("body").RenderStampBBCode();
});
