/*
Config
*/
var commentOptions = {
    submitUrl: '/Commenti/CommentInserter',
    pageUrl: {
        'detail': '/informativos/formula1/detail/#{shortItemId}/#{contentItemId}/commenti_#{contentItemId}_#{pageIndex}.html'
    },
    anchorUrl: 'comentario',
    elmTotalLink: 'link_commenti',
    totalLinkPostfix: ' commenti',
    elmPaginazione: 'comment-pagination',
    elmNavigazione: 'comment-navigation',
    elmList: 'commenti_list_',
    pageGroup: 3, /* usato per la visualizzazione dei "..." nell'elenco delle pagine */
    startAtLast: false,
    firstIsZero: false,
    singleTargetDiv: false,
    firstPageName: 'first',
    isShort: false,
    invert: true,
    twoLines: true,
    maxCharCount: 500
};

var commentSectionOptions = {
    submitUrl: '/Commenti/CommentInserter',
    pageUrl: {
        'detail': '#{section}detail/#{shortItemId}/#{contentItemId}/commenti_#{contentItemId}_#{pageIndex}.html'
    },
    anchorUrl: 'comentario',
    elmTotalLink: 'link_commenti',
    totalLinkPostfix: ' commenti',
    elmPaginazione: 'comment-pagination',
    elmNavigazione: 'comment-navigation',
    elmList: 'commenti_list_',
    pageGroup: 3, /* usato per la visualizzazione dei "..." nell'elenco delle pagine */
    startAtLast: false,
    firstIsZero: false,
    singleTargetDiv: false,
    firstPageName: 'first',
    isShort: false,
    invert: true,
    twoLines: true,
    maxCharCount: 500
};

/*
Class Paginator
*/
var Paginator = Class.create();
Paginator.prototype = {
    initialize: function(options) {
        this.options = options;
        this.linkedPaginators = $A([]);
    },

    prepare: function(iAllItemCount, iItemsPerPage, iFirstPageMaxItems, contentTypeId, contentItemId) {
        this.contentItemId = contentItemId;
        this.urlTemplate = new Template(this.options.pageUrl[contentTypeId]);

        this.innerPrepare(iAllItemCount, iItemsPerPage, iFirstPageMaxItems);
    },

    prepareWithFunction: function(iAllItemCount, iItemsPerPage, iFirstPageMaxItems, urlGetter, postBodyGetter) {
        this.urlTemplate = null;
        this.urlGetter = urlGetter;
        if (postBodyGetter) {
            this.postBodyGetter = postBodyGetter;
        } else {
            this.postBodyGetter = null;
        }

        this.innerPrepare(iAllItemCount, iItemsPerPage, iFirstPageMaxItems);
    },

    innerPrepare: function(iAllItemCount, iItemsPerPage, iFirstPageMaxItems) {

        this.iAllItemCount = iAllItemCount;
        this.iItemsPerPage = iItemsPerPage;
        this.iFirstPageMaxItems = iFirstPageMaxItems;

        this.totalPages = 1;
        if (iAllItemCount > iFirstPageMaxItems) {
            this.totalPages = 1 +
       			Math.floor((iAllItemCount - iFirstPageMaxItems + iItemsPerPage - 1) / iItemsPerPage);
            this.iFirstPageItemCount = iAllItemCount - (this.totalPages - 1) * iItemsPerPage;
        }
        if (this.options.startAtLast) {
            this.currentPage = this.totalPages;
        } else {
            this.currentPage = 1;
        }

        if (this.options.elmTotalLink && $(this.options.elmTotalLink)) {
            $(this.options.elmTotalLink).innerHTML = iAllItemCount + this.options.totalLinkPostfix;
        }

        this.handlers = new Array();
        this.updatePagination();
    },

    updatePagination: function() {
        // unregistering previous event handlers
        $A(this.handlers).each(function(hndl) {
            Event.stopObserving(hndl.target, 'click', hndl.fnct);
        });
        this.handlers.clear();

        var pagElm = $(this.options.elmPaginazione);
        if (pagElm) {
            pagElm.innerHTML = '';
        }

        var navElm = pagElm;
        if (this.options.twoLines) {
            if (pagElm) {
                pagElm.up().addClassName('commentPagination');
            }
            navElm = $(this.options.elmNavigazione);
            if (navElm) {
                navElm.innerHTML = '';
            } else {
                new Insertion.After(pagElm, '<div id="' + this.options.elmNavigazione + '"></div>');
                navElm = $(this.options.elmNavigazione);
            }
        }

        if (this.currentPage == 1) {
            //new Insertion.Bottom(pagElm, '<li class="link_previous">&laquo; Precedente</li> |');
        } else {
            new Insertion.Bottom(navElm, '<a class="link_previous" href="javascript:;" title="P&aacute;gina anterior">&laquo; P&aacute;gina anterior</a>');
            var target = navElm.getElementsByClassName('link_previous')[0];
            var fnct = this.switchTo.bind(this, this.currentPage - 1);
            Event.observe(target, 'click', fnct);
            this.handlers.push({ target: target, fnct: fnct });
        }

        if (!this.options.isShort) {
            var dots = false;
            for (var i = 1; i <= this.totalPages; i++) {
                if ((i > this.options.pageGroup) &&
						(this.totalPages - i >= this.options.pageGroup) &&
						(Math.abs(i - this.currentPage) > this.options.pageGroup)) {
                    if (!dots) {
                        new Insertion.Bottom(pagElm, '...');
                        dots = true;
                    }
                    continue;
                }
                dots = false;

                var lastPage = i == this.totalPages;

                if (i == this.currentPage) {
                    new Insertion.Bottom(pagElm, '<a title="' + i + '" class="selected">' + i + '</a>');
                } else {
                    new Insertion.Bottom(pagElm, '<a href="javascript:;" title="' + i + '" class="pag_btn_' + i + '">' + i + '</a>');

                    var target = pagElm.getElementsByClassName('pag_btn_' + i)[0];
                    var fnct = this.switchTo.bind(this, i);
                    Event.observe(target, 'click', fnct);
                    this.handlers.push({ target: target, fnct: fnct });
                }
            }

            var firstItemIndex = (this.currentPage - 1) * this.iItemsPerPage + 1;
            var lastItemIndex = this.currentPage == this.totalPages ?
				this.iAllItemCount : (this.currentPage * this.iItemsPerPage);

            if (this.options.invert) {
                firstItemIndex = this.currentPage == 1 ? 1 :
					(this.iAllItemCount + 1 - (this.iItemsPerPage * (this.totalPages + 1 - this.currentPage)));
                lastItemIndex = this.iAllItemCount - (this.iItemsPerPage * (this.totalPages - this.currentPage));
            }

            if (this.iAllItemCount == 0) {
                firstItemIndex = 0;
                lastItemIndex = 0;
            }

            /*new Insertion.Bottom(navElm, '<li class="ItemNumber">[ da ' + firstItemIndex + 
            ' a ' + lastItemIndex + ' di ' + this.iAllItemCount + ' ]</li>');*/
        }

        if (this.currentPage == this.totalPages) {
            //new Insertion.Bottom(navElm, '<li class="link_next">Successiva &raquo;</li>');
        } else {
            new Insertion.Bottom(navElm, '<a class="link_next" href="javascript:;" title="P&aacute;gina siguiente">P&aacute;gina siguiente &raquo;</a>');
            var target = navElm.getElementsByClassName('link_next')[0];
            var fnct = this.switchTo.bind(this, this.currentPage + 1);
            Event.observe(target, 'click', fnct);
            this.handlers.push({ target: target, fnct: fnct });
        }
    },

    switchTo: function(page) {
        if (page == this.currentPage) {
            return;
        }

        var pageIndex = this.options.invert ? (this.totalPages + 1 - page) : page;
        var currentPageIndex = this.options.invert ? (this.totalPages + 1 - this.currentPage) : this.currentPage;

        if (this.options.firstIsZero) {
            pageIndex--;
            currentPageIndex--;
            if (this.options.firstPageName) {
                if (pageIndex == this.totalPages - 1) {
                    pageIndex = this.options.firstPageName;
                }
                if (currentPageIndex == this.totalPages - 1) {
                    currentPageIndex = this.options.firstPageName;
                }
            }
        } else {
            if (this.options.firstPageName) {
                if (pageIndex == this.totalPages) {
                    pageIndex = this.options.firstPageName;
                }
                if (currentPageIndex == this.totalPages) {
                    currentPageIndex = this.options.firstPageName;
                }
            }
        }

        if (!this.options.singleTargetDiv && $(this.options.elmList + pageIndex) != undefined) {
            // page already downloaded
            $(this.options.elmList + currentPageIndex).hide();
            $(this.options.elmList + pageIndex).show();
            this.currentPage = page;
            this.updatePagination();
            this.updateLinkedPaginators();
        } else {
            // page to be downloaded
            var url;
            var postBody = "";
            if (this.urlTemplate != null) {
                url = this.urlTemplate.evaluate({
                    pageIndex: pageIndex,
                    contentItemId: this.contentItemId,
                    shortItemId: (this.contentItemId % 100)
                });
            } else {
                url = this.urlGetter(pageIndex);
                if (this.postBodyGetter != null) {
                    postBody = this.postBodyGetter(pageIndex);
                }
            }

            new Ajax.Request(url, {
                method: (postBody != '' ? 'POST' : 'GET'),
                postBody: postBody,
                onSuccess: function(transport) {
                    if (this.options.singleTargetDiv) {
                        $(this.options.elmList).update(transport.responseText);
                    } else {
                        $(this.options.elmList + currentPageIndex).hide();
                        if (this.options.insertAfter) {
                            new Insertion.After($(this.options.elmPaginazione).up(), transport.responseText);
                        } else {
                            new Insertion.Before($(this.options.elmPaginazione).up(), transport.responseText);
                        }
                    }

                    this.currentPage = page;
                    this.updatePagination();
                    this.updateLinkedPaginators();
                } .bind(this)
            });
        }

        if (this.options.anchorUrl) {
            document.location.href = '#' + this.options.anchorUrl;
        }
    },

    updateLinkedPaginators: function() {
        this.linkedPaginators.each(function(paginator) {
            if (paginator.currentPage != this.currentPage) {
                paginator.currentPage = this.currentPage;
                paginator.updatePagination();
            }
        } .bind(this));
    }
};

var commentPaginator = new Paginator(commentOptions);

/*
Class SectionPaginator
*/
var SectionPaginator = Class.create();
SectionPaginator.prototype = {
    initialize: function(options) {
        this.options = options;
        this.linkedPaginators = $A([]);
    },

    prepare: function(iAllItemCount, iItemsPerPage, iFirstPageMaxItems, contentTypeId, contentItemId, section) {
        this.contentItemId = contentItemId;
        this.section = section;
        this.urlTemplate = new Template(this.options.pageUrl[contentTypeId]);

        this.innerPrepare(iAllItemCount, iItemsPerPage, iFirstPageMaxItems);
    },

    prepareWithFunction: function(iAllItemCount, iItemsPerPage, iFirstPageMaxItems, urlGetter, postBodyGetter) {
        this.urlTemplate = null;
        this.urlGetter = urlGetter;
        if (postBodyGetter) {
            this.postBodyGetter = postBodyGetter;
        } else {
            this.postBodyGetter = null;
        }

        this.innerPrepare(iAllItemCount, iItemsPerPage, iFirstPageMaxItems);
    },

    innerPrepare: function(iAllItemCount, iItemsPerPage, iFirstPageMaxItems) {

        this.iAllItemCount = iAllItemCount;
        this.iItemsPerPage = iItemsPerPage;
        this.iFirstPageMaxItems = iFirstPageMaxItems;

        this.totalPages = 1;
        if (iAllItemCount > iFirstPageMaxItems) {
            this.totalPages = 1 +
       			Math.floor((iAllItemCount - iFirstPageMaxItems + iItemsPerPage - 1) / iItemsPerPage);
            this.iFirstPageItemCount = iAllItemCount - (this.totalPages - 1) * iItemsPerPage;
        }
        if (this.options.startAtLast) {
            this.currentPage = this.totalPages;
        } else {
            this.currentPage = 1;
        }

        if (this.options.elmTotalLink && $(this.options.elmTotalLink)) {
            $(this.options.elmTotalLink).innerHTML = iAllItemCount + this.options.totalLinkPostfix;
        }

        this.handlers = new Array();
        this.updatePagination();
    },

    updatePagination: function() {
        // unregistering previous event handlers
        $A(this.handlers).each(function(hndl) {
            Event.stopObserving(hndl.target, 'click', hndl.fnct);
        });
        this.handlers.clear();

        var pagElm = $(this.options.elmPaginazione);
        if (pagElm) {
            pagElm.innerHTML = '';
        }

        var navElm = pagElm;
        if (this.options.twoLines) {
            if (pagElm) {
                pagElm.up().addClassName('commentPagination');
            }
            navElm = $(this.options.elmNavigazione);
            if (navElm) {
                navElm.innerHTML = '';
            } else {
                new Insertion.After(pagElm, '<div id="' + this.options.elmNavigazione + '"></div>');
                navElm = $(this.options.elmNavigazione);
            }
        }

        if (this.currentPage == 1) {
            //new Insertion.Bottom(pagElm, '<li class="link_previous">&laquo; Precedente</li> |');
        } else {
            new Insertion.Bottom(navElm, '<a class="link_previous" href="javascript:;" title="P&aacute;gina anterior">&laquo; P&aacute;gina anterior</a>');
            var target = navElm.getElementsByClassName('link_previous')[0];
            var fnct = this.switchTo.bind(this, this.currentPage - 1);
            Event.observe(target, 'click', fnct);
            this.handlers.push({ target: target, fnct: fnct });
        }

        if (!this.options.isShort) {
            var dots = false;
            for (var i = 1; i <= this.totalPages; i++) {
                if ((i > this.options.pageGroup) &&
						(this.totalPages - i >= this.options.pageGroup) &&
						(Math.abs(i - this.currentPage) > this.options.pageGroup)) {
                    if (!dots) {
                        new Insertion.Bottom(pagElm, '...');
                        dots = true;
                    }
                    continue;
                }
                dots = false;

                var lastPage = i == this.totalPages;

                if (i == this.currentPage) {
                    new Insertion.Bottom(pagElm, '<a title="' + i + '" class="selected">' + i + '</a>');
                } else {
                    new Insertion.Bottom(pagElm, '<a href="javascript:;" title="' + i + '" class="pag_btn_' + i + '">' + i + '</a>');

                    var target = pagElm.getElementsByClassName('pag_btn_' + i)[0];
                    var fnct = this.switchTo.bind(this, i);
                    Event.observe(target, 'click', fnct);
                    this.handlers.push({ target: target, fnct: fnct });
                }
            }

            var firstItemIndex = (this.currentPage - 1) * this.iItemsPerPage + 1;
            var lastItemIndex = this.currentPage == this.totalPages ?
				this.iAllItemCount : (this.currentPage * this.iItemsPerPage);

            if (this.options.invert) {
                firstItemIndex = this.currentPage == 1 ? 1 :
					(this.iAllItemCount + 1 - (this.iItemsPerPage * (this.totalPages + 1 - this.currentPage)));
                lastItemIndex = this.iAllItemCount - (this.iItemsPerPage * (this.totalPages - this.currentPage));
            }

            if (this.iAllItemCount == 0) {
                firstItemIndex = 0;
                lastItemIndex = 0;
            }

            /*new Insertion.Bottom(navElm, '<li class="ItemNumber">[ da ' + firstItemIndex + 
            ' a ' + lastItemIndex + ' di ' + this.iAllItemCount + ' ]</li>');*/
        }

        if (this.currentPage == this.totalPages) {
            //new Insertion.Bottom(navElm, '<li class="link_next">Successiva &raquo;</li>');
        } else {
            new Insertion.Bottom(navElm, '<a class="link_next" href="javascript:;" title="P&aacute;gina siguiente">P&aacute;gina siguiente &raquo;</a>');
            var target = navElm.getElementsByClassName('link_next')[0];
            var fnct = this.switchTo.bind(this, this.currentPage + 1);
            Event.observe(target, 'click', fnct);
            this.handlers.push({ target: target, fnct: fnct });
        }
    },

    switchTo: function(page) {
        if (page == this.currentPage) {
            return;
        }

        var pageIndex = this.options.invert ? (this.totalPages + 1 - page) : page;
        var currentPageIndex = this.options.invert ? (this.totalPages + 1 - this.currentPage) : this.currentPage;

        if (this.options.firstIsZero) {
            pageIndex--;
            currentPageIndex--;
            if (this.options.firstPageName) {
                if (pageIndex == this.totalPages - 1) {
                    pageIndex = this.options.firstPageName;
                }
                if (currentPageIndex == this.totalPages - 1) {
                    currentPageIndex = this.options.firstPageName;
                }
            }
        } else {
            if (this.options.firstPageName) {
                if (pageIndex == this.totalPages) {
                    pageIndex = this.options.firstPageName;
                }
                if (currentPageIndex == this.totalPages) {
                    currentPageIndex = this.options.firstPageName;
                }
            }
        }

        if (!this.options.singleTargetDiv && $(this.options.elmList + pageIndex) != undefined) {
            // page already downloaded
            $(this.options.elmList + currentPageIndex).hide();
            $(this.options.elmList + pageIndex).show();
            this.currentPage = page;
            this.updatePagination();
            this.updateLinkedPaginators();
        } else {
            // page to be downloaded
            var url;
            var postBody = "";
            if (this.urlTemplate != null) {
                url = this.urlTemplate.evaluate({
                    pageIndex: pageIndex,
                    contentItemId: this.contentItemId,
                    shortItemId: (this.contentItemId % 100),
                    section: (this.section)
                });
            } else {
                url = this.urlGetter(pageIndex);
                if (this.postBodyGetter != null) {
                    postBody = this.postBodyGetter(pageIndex);
                }
            }

            new Ajax.Request(url, {
                method: (postBody != '' ? 'POST' : 'GET'),
                postBody: postBody,
                onSuccess: function(transport) {
                    if (this.options.singleTargetDiv) {
                        $(this.options.elmList).update(transport.responseText);
                    } else {
                        $(this.options.elmList + currentPageIndex).hide();
                        if (this.options.insertAfter) {
                            new Insertion.After($(this.options.elmPaginazione).up(), transport.responseText);
                        } else {
                            new Insertion.Before($(this.options.elmPaginazione).up(), transport.responseText);
                        }
                    }

                    this.currentPage = page;
                    this.updatePagination();
                    this.updateLinkedPaginators();
                } .bind(this)
            });
        }

        if (this.options.anchorUrl) {
            document.location.href = '#' + this.options.anchorUrl;
        }
    },

    updateLinkedPaginators: function() {
        this.linkedPaginators.each(function(paginator) {
            if (paginator.currentPage != this.currentPage) {
                paginator.currentPage = this.currentPage;
                paginator.updatePagination();
            }
        } .bind(this));
    }
};

var commentSectionPaginator = new SectionPaginator(commentSectionOptions);

var captchaOptions = {
    captchaUrl: '/Commenti/GetCaptcha'
}



/*
Class CommentSubmitter
*/
var CommentSubmitter = Class.create();
CommentSubmitter.prototype = {
    initialize: function(idForm, statusBar, captchaImg) {
        this.idForm = idForm;
        this.statusBar = statusBar;
        this.captchaImg = captchaImg;
        this.overMax = false;

        this.options = commentOptions;
		this.reloadCaptcha();

        Event.observe(this.idForm, 'submit', this.salvaCommento.bind(this));
        Event.observe($(this.idForm)['commento'], 'keyup', this.onCommentChange.bind(this));
        Event.observe($(this.idForm)['commento'], 'change', this.onCommentChange.bind(this));
        Event.observe($(this.idForm)['commento'], 'mouseover', this.onCommentChange.bind(this));

        if ($(this.idForm).getElementsByClassName('char_count').length > 0) {
            this.charCountElm = $(this.idForm).getElementsByClassName('char_count')[0];
            this.onCommentChange();
        }
    },

    reloadCaptcha: function() {
        $(this.captchaImg).src = captchaOptions.captchaUrl + '?' + (new Date().getTime()); ;
    },

    salvaCommento: function() {
        this.hideStatus();

        var myForm = $(this.idForm);

        if ($F(myForm['commento']) == '') {
            this.showError('commento', 'Campo "comentario" vac\u00EDo');
            myForm['commento'].focus();
            return;
        }

        this.onCommentChange();
        if (this.overMax) {
            myForm['commento'].focus();
            return;
        } else {
            this.hideError('commento');
        }

        if ($F(myForm['nome']) == '') {
            this.showError('nome', 'Campo "nombre" vac\u00EDo');
            myForm['nome'].focus();
            return;
        } else {
            this.hideError('nome');
        }

        if ($F(myForm['email']) == '') {
            this.showError('email', 'Campo "correo" vac\u00EDo');
            myForm['email'].focus();
            return;
        } else if (!emailCheck($F(myForm['email']))) {
            this.showError('email', 'El correo insertado no es un correo v\u00E1lido');
            myForm['email'].focus();
            return;
        } else {
            this.hideError('email');
        }
        if ($F(myForm['captcha_text']) == '') {
            this.showError('captcha_text', "Insertar el c\u00F3digo que ves en la imagen");
            myForm['captcha_text'].focus();
            return;
        } else {
            this.hideError('captcha_text');
        }

        myForm['captcha_text'].value = $F(myForm['captcha_text']).toLowerCase();

        var params = myForm.serialize(true);
        myForm.disable();

        new Ajax.Request(commentOptions.submitUrl, {
            method: 'post',
            parameters: params,
            onSuccess: function(transport) {
                eval(transport.responseText);
                if (status.ok) {
                    this.showStatus(false, '\u00A1Gracias!<br/> El mensaje ha sido enviado con \u00E9xito.<br/> En breve ser\u00E1 publicado.');
                    $($(this.idForm)['commento']).clear();
                } else if (status.type == 'missing') {
                    this.showStatus(true, 'Campo "' + status.what + '" vac\u00EDo');
                } else if (status.type == 'spam') {
                    this.showStatus(true, 'Tu mensaje ha sido considerado spam y no ser\u00E0 publicado');
                } else if (status.type == 'blacklist') {
                    this.showStatus(true, 'Tu mensaje tiene una o m\u00E1s palabras no consentidas');
                } else if (status.type == 'generic' && status.message.startsWith('Invalid ID')) {
                    this.showStatus(true, 'Usuario no v\u00E1lido. Vuelve a intentar escribir el mensaje con otro nombre.');
                } else {
                    this.showStatus(true, status.message);
                }
            } .bind(this),
            onFailure: function() {
                this.showStatus(true, 'Error en el guardar el comentario');
            } .bind(this),
            onComplete: function() {
                //this.reloadCaptcha();
                //$($(this.idForm)['captcha_text']).clear();
                //$(this.idForm).enable();
                $('btn_submit').href = "javascript:void();";
            } .bind(this)
        });
    },

    onCommentChange: function() {
        var myForm = $(this.idForm);
        var text = $F(myForm['commento']);
        var textLength = dbStringLength(text);

        if (textLength > this.options.maxCharCount) {
            if (this.charCountElm) {
                this.charCountElm.innerHTML = '0';
            }
            this.showError('commento', "El total de caracteres es superior al m\u00E1ximo. " + (textLength - this.options.maxCharCount) +
				" caracteres mas del m\u00E1ximo");
            this.overMax = true;
        } else {
            if (this.charCountElm) {
                this.charCountElm.innerHTML = this.options.maxCharCount - textLength;
            }
            if (this.overMax) {
                this.hideError('commento');
            }
            this.overMax = false;
        }
    },

    showStatus: function(error, message) {
        $(this.statusBar).className = (error ? 'MessageERROR' : 'MessageINFO') + ' clearBoth';
        $(this.statusBar).innerHTML = message;
        $(this.statusBar).show();
        $(this.statusBar).scrollTo();
    },

    hideStatus: function() {
        $(this.statusBar).hide();
    },

    showError: function(where, message) {
        $('error_' + where).innerHTML = message;
        $('error_' + where).up(1).show();
        $('error_' + where).scrollTo();
        if ($(this.idForm)[where].addClassName) {
            $(this.idForm)[where].addClassName('errorInput');
        }
    },

    hideError: function(where) {
        $('error_' + where).up(1).hide();
        if ($(this.idForm)[where].removeClassName) {
            $(this.idForm)[where].removeClassName('errorInput');
        }
    },

    resetForm: function(captchaImg) {
        this.captchaImg = captchaImg;
        this.hideStatus();
        var myForm = $(this.idForm);

        $(myForm['commento']).clear();
        $(myForm['nome']).clear();
        $(myForm['email']).clear();
        $(myForm['sito']).clear();

        this.reloadCaptcha();
        $(myForm['captcha_text']).clear();
        myForm.enable();
        $('btn_submit').href = "javascript:submitForm();";
    }
}
// String length for db saving
// char count: & -> 5; <, > -> 4; \n -> 5
function dbStringLength(string) {
    var stringLength = string.length;
    string.replace(/[\n&]/g, function() { stringLength += 4 });
    string.replace(/[<>]/g, function() { stringLength += 3 });
    return stringLength;
};
