FANDOM


/*

Wikimarks Editor

More info at: http://wikimarks.wikia.com/Code

© Peter Coester, 2012

Module "Parser"

 */
 
(function (ns) {
 
 
    function parse (wikitext) {
 
        ns.Document.resetDoc();
 
        var NORMAL = 0, NO_LINK = 1, UNREADABLE = 2, BAD_NESTING = 4, BAD_LINK = 5;
 
        var prevLevel = 0, currentLine = -1;
        var level, title, href, parts, shade;
        var lines = wikitext.split(/\r\n|\r|\n/);
 
        if (ns.Shadow) {
            ns.Shadow.init();
            currentLine = ns.Shadow.getCurrentLine();
        }
 
        for (var i = 0, n = lines.length; i < n; i++) {
            parts = lines[i].match(/^[ \t]*(\*{1,3})([^*=][^=]*)(?:=(.+))?$/);
            //console.log('parts: ', parts);
            if (!parts) {
                shade = UNREADABLE;
            } else {
                level = parts[1].length;
                if (prevLevel != 3 && Math.abs(prevLevel - level) > 1) {
                    shade = BAD_NESTING;
                } else {
                    prevLevel = level;
                    title = parts[2].trim();
                    href = false;
                    if (!parts[3]) {
                        shade = NO_LINK;
                    } else {
                        href = ns.Linker.parseLink(parts[3].trim());
                        if (!href) {
                            shade = BAD_LINK;
                        } else {
                            shade = NORMAL;
                        }
                    }
                    //console.log('level: ', level, ', title: ', title, ', href: ', href);
                    ns.Document.addLink(level, href, title, i == currentLine, i);
                }
            }
            if (ns.Shadow) ns.Shadow.setShadow(i, shade);
        }
    }
 
    ns.Parser = {
        parse: parse
    };
 
}(window.Wikimarks = window.Wikimarks || {}));
 
/*

Module "Document"

*/
 
(function (ns) {
 
    var doc = [];
 
    var chevronClasses = ['chevron', 'chevron-right', false];
    function getChevron (depth) {
        var c = chevronClasses[depth];
        if (!c) return '';
        return ' <img src="data:image/gif;base64,R0lGODlhAQABAIABAAAAAP///yH5BAEAAAEALAAAAAABAAEAQAICTAEAOw%3D%3D" class="' + c + '">';
    }
 
    function addLink (level, href, title, hover, line) {
        var link = {
            href:  href ? href.replace(/</g, '&lt;').replace(/>/g, '&gt;') : false,
            title: title.replace(/</g, '&lt;').replace(/>/g, '&gt;'),
            hover: hover, line: line,
            sublist: []
        };
        function pushLinkAtDepth (depth, sublist) {
            if (depth == level) {
                sublist.push(link);
            } else {
                pushLinkAtDepth(depth+1, sublist[sublist.length-1].sublist);
            }
        }
        pushLinkAtDepth(1, doc);
    }
 
    var format;
    var saveOnly;
    function getRenderer (cssClasses) {
        return function () {
            saveOnly = arguments.length ? Boolean(arguments[0]) : false;
            format = function (element, depth, attributes) {
                var e = '<' + element;
                var c = cssClasses[element][depth]
                if (c) e += ' class="' + c + '"';
                if (attributes) e += ' ' + attributes;
                return e + '>';
            }
            return render();
        };
    }
 
    function render () {
 
        function renderList (list, d) {
            var html = format('ul', d, false);
            for (var i = 0; i < list.length; i++) {
                html += format('li', d, false);
                var attributes = list[i].href ? 'href="' + list[i].href + '"': 'name="menu"';
                if (ns.Editor && !saveOnly) {
                    if (list[i].hover) attributes += ' rel="current"';
                    attributes += ' line="' + list[i].line + '"';
                }
                html += format('a' , d, attributes);
                html += list[i].title;
                if (list[i].sublist.length) {
                    html += getChevron(d);
                    html += '</a>';
                    html += renderList(list[i].sublist, d + 1);
                } else {
                    html += '</a>';
                }
                html += '</li>';
            }
            return html + '</ul>';
        }
 
        return renderList(doc, 0);
    }
 
    var getRestyle = getRenderer({
        ul: ['subnav-2 accent', 'subnav subnav-3', false],
        li: ['subnav-2-item', false, false],
        a:  ['subnav-2a', 'subnav-3a', false]
    });
 
    ns.Document = {
        resetDoc: function () { doc = []; },
        isEmpty: function () { return doc.length === 0; },
        addLink: addLink,
        getMenu: getRestyle
    };
 
}(window.Wikimarks = window.Wikimarks || {}));
 
/*

Module "Shadow"

*/
 
(function (ns) {
 
    var NORMAL = 0, NO_LINK = 1, UNREADABLE = 2, CURRENT = 3, BAD_NESTING = 4, BAD_LINK = 5;
 
    var lines, shadows, currentLine;
 
    function init () {
        var wikitext = ns.Editor.getEditor().val();
 
        lines = wikitext.split(/\r\n|\r|\n/);
        shadows = [];
        currentLine = -1;
        //console.log('init', ns.Editor.getEditor().text());
        var sel = ns.Editor.getEditor().getSelection();
        if (sel) {
            currentLine = wikitext
            .substring(0, sel.start)
            .split(/\r\n|\r|\n/).length - 1;
        } else {
            currentLine = 1;
        }
    }
 
    function getCurrentLine () {
        return currentLine;
    }
 
    function getCurrentPreviewable () {
        return UNREADABLE != shadows[currentLine] && BAD_NESTING != shadows[currentLine];
    }
 
    function setShadow (i, shade) {
        shadows[i] = shade;
    }
 
    function moveCaretToCurrent () {
        var current = $('.wikimarks-current', ns.Editor.getShadow());
        if (!current.length || !current.attr('line')) return;
        var line = parseInt(current.attr('line'), 10) + 1;
        console.log('Line: ', line);
        var text = ns.Editor.getEditor().val();
        var caret = 0, raw = text.split(/([\r\n]+)/);
        for (var i = 0, l = 1, m = Math.min(text.split(/[\r\n]+/).length, line); l < m; i++) {
            caret += raw[i].length;
            if (/\r|\n/.test(raw[i])) {
                l++;
            } 
        }
        console.log('Caret: ', caret, ': ', text.substring(caret, caret+30));
        ns.Editor.setCaret(caret);
    }            
 
    function update (line) {
 
        //console.log('updating: ', line);
        if ('undefined' != typeof line) {
            if (CURRENT == shadows[currentLine]) shadows[currentLine] = NORMAL;
            currentLine = line;
        }
        if (UNREADABLE != shadows[currentLine] && BAD_NESTING != shadows[currentLine]) shadows[currentLine] = CURRENT;
        //console.log('shadows: ', shadows, ', lines: ', lines);
        //console.log(currentLine);
        var l, type, result = '';
        for (var i = 0, n = shadows.length; i < n; i++) {
            l = lines[i];
            if (!l.length) {
                result += '&nbsp;<br />';
                continue;
            }
            var inView = i == currentLine ? ' id="inView" line="'+line+'"' : '';
            switch (shadows[i]) {
                case NORMAL: case NO_LINK: case BAD_LINK:
                    result += l + '<br />';
                    break;
                case UNREADABLE: case BAD_NESTING:
                    result += '<div class="wikimarks-error">'   + l + '</div>';
                    break;
                case CURRENT:
                    result += '<div class="wikimarks-current"' + inView + '>' + l + '</div>';
                    break;
            }
        }
        //console.log(result);
        ns.Editor.getShadow().html(result);
        if ('undefined' != typeof line) {
            ns.Submenu.show();
            var shadowHeight = ns.Editor.getShadow().height();
            var shadowTop = ns.Editor.getShadow().offset().top;
            var middle = shadowHeight/2 + shadowTop;
            if (shadowTop + 21*line > middle) {
                ns.Editor.getShadow().scrollTop(shadowTop + 21*line - middle);
                ns.Editor.getEditor().scrollTop(shadowTop + 21*line - middle);
            } else {
                ns.Editor.getShadow().scrollTop(0);
                ns.Editor.getEditor().scrollTop(0);
            }
            console.log('moveCaretToCurrent');
            moveCaretToCurrent();
        }
    }
 
    ns.Shadow = {
        init: init,
        getCurrentLine: getCurrentLine,
        getCurrentPreviewable: getCurrentPreviewable,
        setShadow: setShadow,
        update: update
    }
 
}(window.Wikimarks = window.Wikimarks || {}));
 
/*

Module "Submenu"

*/
 
(function (ns) {
 
    var container, wikimarks, urlPreview;
 
    var current, submenu;
 
    function load () {
 
        $('.module', '#WikiaRail').css('display', 'none');
 
        $('input[type="text"]','#WikiaSearch').attr('placeholder', 'Search Wikia');
 
        $('#wikimarks-submenu').remove();
        $('#WikiaSearch').after('<header id="wikimarks-submenu"><nav>' +
            '<ul class="subnav-2 accent" style="display: block"></ul>' +
            '<div class="navbackground"><div></div><img width="0" height="0" class="chevron" src="data:image/gif;base64,R0lGODlhAQABAIABAAAAAP///yH5BAEAAAEALAAAAAABAAEAQAICTAEAOw%3D%3D"></div>' +
        '</nav></header>');
 
        submenu = $('#wikimarks-submenu').attr('class', $('#WikiHeader').attr('class'));
        $('#wikimarks-submenu .marked a');
        container = $('ul.subnav-2', submenu);
        wikimarks = $('#wikimarks');
 
        $('#url-preview').remove();
        $('#wikimarks-submenu').append('<div id="url-preview" class="wikimarks-current" style="display: none;"></div>');
        urlPreview = $('#url-preview');
 
        function adjustUrlPreviewSize () {
            var urlPreview = $('#url-preview');
            var urlPreviewMaxWidth = $(window).width() - urlPreview.offset().left;
            urlPreview.css('width', Math.max(300, urlPreviewMaxWidth - urlPreviewMaxWidth/8)  + 'px');
        }
        adjustUrlPreviewSize();
        $(window).resize(adjustUrlPreviewSize);
    }
 
    function show () {
 
        container.empty();
        urlPreview.css('display', 'none');
        //console.log(urlPreview);
 
        var currentLink = $('a[rel="current"]', '#WikiHeader');
        if (!currentLink.length) return;
 
        var currentLi = currentLink.parent();
        while (!currentLi.parent().hasClass('subnav-2')) {
            currentLi = currentLi.parent().parent();
        }
 
        var rootLi = currentLi.clone();
 
        currentLink = $('a[rel="current"]', rootLi);
        currentLi = currentLink.parent();
        currentLi.children('ul').remove();
        while (currentLi.siblings().length) {
            currentLi.siblings().children('ul').remove();
            currentLi = currentLi.parent().parent();
        }
 
        rootLi.appendTo(container)
        .addClass('marked2')
        .find('ul').css('display', 'block');
 
        var href = currentLink.attr('href');
        currentLink.addClass('wikimarks-current');
        rootLi.find('a').removeAttr('href');
 
        if (href && ns.Shadow.getCurrentPreviewable()) {
            urlPreview.html(href).css({ display: 'block',
                top: currentLink.offset().top - 175 + 'px'
            });
        }
    }
 
    ns.Submenu = {
        show: show,
        load: load
    };
 
}(window.Wikimarks = window.Wikimarks || {}));
 
/*

Module "Editor"

*/
 
(function (ns) {
 
    var container, editor, shadow, wikimarks, caret = -1, editMode = true, lastSaved;
 
    function initPanels () {
 
        var setHeight = (function () {
            var offsetTop = container.offset().top;
            var main = $("#WikiaMainContent");
            var mainTop = main.offset().top;
            var sub = $('#wikimarks-submenu');
            return function () {
                var windowHeight = $(window).height();
                if (editMode) {
                    var height = windowHeight - offsetTop - 50 + 'px';
                    container.css({
                        height: height,
                        overflow: 'hidden',
                        width: '645px',
                        left: '15px'
                    });
                    editor.css('height', height);
                    shadow.css('height', height);
                    sub.css('visibility', 'visible');
                } else {
                    container.css({
                        height: windowHeight - mainTop - 95 + 'px',
                        overflowY: 'auto',
                        width: '750px',
                        left: '115px'
                    });
                    sub.css('visibility', 'hidden');
                }
                main.css('height', windowHeight - mainTop - 25 + 'px' );
            };
        }());
 
        function Panel (panel) {
            this.button = $('<a href="javascript:void(0)" id="' + panel.name +
                '" class="side-button sideways' + (panel.on ? '' : ' off') +
                '">' + panel.name + '</a>')
            .appendTo(document.body);
            if (panel.url) {
                this.content = $('<div id="' + panel.name +
                    '-contents" class="external" style="display: none;"></div>')
                .appendTo(container);
                this.url = panel.url;
            }
        }
 
        Panel.list = [];
 
        Panel.toggle = function (event) {
            var targetId = $(event.target).data('id');
            $.each(Panel.list, function (id, panel) {
                console.log('(panel,id,targetId):',panel, id, targetId);
                if (id === targetId) {
                    panel.activate();
                } else {
                    panel.deactivate();
                }
            });
        }
 
        Panel.addButton = function (panel) {
            var newPanel = new Panel(panel);
            Panel.list.push(newPanel);
            var id = Panel.list.length - 1;
            newPanel.button
            .data('id', id)
            .click(Panel.toggle)
            .css('top', 260 + id * 84 + 'px');
            return newPanel;
        }
 
        Panel.prototype.activate = function () {
            this.button.removeClass('off');
            var c = this.content.css('display', 'block');
            if (c.is(':empty')) {
                $.get(this.url).done(function (data) {
                    c.append(data);
                    $('.insertusername').text(wgUserName);
                    setHeight();
                });
            } else {
                setHeight();
            }
        }
 
        Panel.prototype.deactivate = function () {
            this.button.addClass('off');
            this.content.css('display', 'none');
        }
 
        var edit = Panel.addButton({
            name: 'Edit',
            on: true
        });
 
        edit.activate = function () {
            editMode = true;
            this.button.removeClass('off');
            editor.css('display', 'block');
            shadow.css('display', 'block');
            setHeight();
        };
 
        edit.deactivate = function () {
            editMode = false;
            this.button.addClass('off');
            editor.css('display', 'none');
            shadow.css('display', 'none');
        }
 
        Panel.addButton({
            name: 'Start',
            url: '//wikimarks.wikia.com/wiki/Start?action=render'
        });
 
        Panel.addButton({
            name: 'Manual',
            url: '//wikimarks.wikia.com/wiki/Manual?action=render'
        });
 
        $('.WikiaPage').css('margin', '0 auto');
 
        editor.scroll(function () {
            shadow.scrollTop(editor.scrollTop());
            shadow.scrollLeft(editor.scrollLeft());
        });
 
        $(document.body).css('overflow', 'hidden');
        $(window).resize(setHeight);
        setHeight();
    }
 
    function initEditor (data) {
 
        editor.val(data).focus().setSelection(0,0);
        ns.Parser.parse(data);
        ns.Menu.populate(ns.Document.getMenu());
        ns.Shadow.update();
        ns.Submenu.show();
 
        function updatePreview () {
            ns.Parser.parse(editor.val());
            ns.Menu.populate(ns.Document.getMenu());
            ns.Shadow.update();
            ns.Submenu.show();
            wikimarks.mouseover();
        }
 
        var firstLine = false, lastLine = false;
 
        editor
        .focus(function () { 
            wikimarks.mouseover();
        })
        .keyup(function (e) {
            var sel, text, diff;
            if (38 === e.which) {
                sel =  editor.getSelection();
                text = editor.val();
                diff = text.substring(0, sel.start);
                if (!/[\r\n]/.test(diff)) {
                    if (!firstLine) {
                        firstLine = true;
                    } else {
                        editor.setSelection(text.length, text.length);
                        firstLine = false;
                        lastLine = true;
                    }
                } else {
                    firstLine = false;
                    lastLine = false;
                }
            } else if (40 === e.which) {
                sel =  editor.getSelection();
                text = editor.val();
                diff = text.substring(sel.end);
                if (!/[\r\n]/.test(diff)) {
                    if (!lastLine) {
                        lastLine = true;
                    } else {
                        editor.setSelection(0, 0);
                        lastLine = false;
                        firstLine = true;
                    }
                } else {
                    firstLine = false;
                    lastLine = false;
                }
            }
        })
        .keyup(updatePreview)
        .click(updatePreview)
        .mouseover(function () {
            editor.focus();
            if (-1 != caret) editor.setSelection(caret, caret);
            caret = -1;
        });
 
        lastSaved = data;
 
        $('#wikimarks-save').off('click').on('click', function () {
 
            function fail () {
                $('#coverup').remove();
                alert('Failure');
            }
 
            $(document.body).append('<div id="coverup" class="loader" style="position: absolute; left: 0; top: 0; width: 100%; height: 100%; z-index: 99999999; background-color: black; opacity: 0.8;"></div>');
 
            $.get('/api.php?action=query&prop=info&titles=' + encodeURIComponent(wgPageName) + '&intoken=edit&format=json', function (data) {
                var pageId = wgArticleId || -1;
                if (data.query && data.query.pages && data.query.pages[pageId] && data.query.pages[pageId].edittoken) {
                    var postData = {
                        action: 'edit',
                        title: wgPageName,
                        token: data.query.pages[pageId].edittoken,
                        text: editor.val(),//.replace(/<br ?\/?>/g, "\n"),
                        format: 'json'
                    };
                    if (ns.isDebug()) console.log('Wikimarks Editor: post data of save request: ', postData);
                    $.post('/api.php', postData, function (data) {
                        var success = data.edit && data.edit.result && 'Success' == data.edit.result;
                        if (success) {
                            var storage = {
                                user: wgUserName,
                                expires: Date.now().valueOf() + 60 * 60 * 1000,
                                menu: ns.Document.getMenu()
                            };
                            localStorage.setItem('Wikimarks', JSON.stringify(storage));
                            lastSaved = editor.val();
                            $('#coverup').remove();
                            if (ns.isDebug()) console.log('Wikimarks Editor: overwrote localStorage: ', localStorage.getItem('Wikimarks'));
                        } else {
                            fail();
                        }
                        if (ns.isDebug()) console.log('Wikimarks Editor: API reply to save request: ', data);
                    });
                } else {
                    console.log('Wikimarks Editor: failed to get token: ', data);
                    fail();
                }
            });
        });
 
        window.onbeforeunload = function () {
            if (lastSaved !== editor.val()) {
                return 'You haven\'t saved your edits yet. Are you sure you want to leave?';
            }
            return void(0);
        }
    }
 
    function load () {
 
        if (ns.isUserPage && ns.isUserPage()) $(function () {
 
            ns.Menu.init();
 
            $('#WikiaPageHeader').css('display', 'block');
 
            $('h1', '#WikiaPageHeader')
            .add('h2', '#WikiaPageHeader')
            .add('a[data-id="comment"]', '#WikiaPageHeader')
            .add('.tally', '#WikiaPageHeader')
            .add('footer.CorporateFooter')
            .add('section', '#WikiaFooter')
            .add('FooterAd', '#WikiaFooter')
            .css('display', 'none');
 
            $('a[data-id="edit"]', '#WikiaPageHeader')
            .attr('href', 'javascript:void(0)').html('Save').attr('id', 'wikimarks-save');
 
            var referer = $('#wikimarks-referer');
            if (referer) {
                referer.prev().remove();
                referer.remove();
            }
            $('#WikiaPageHeader').append(
                '<label for="wikimarks-referer">You came from:</label>' +
                '<input type="text" readonly="readonly" value="" id="wikimarks-referer">'
            );
 
            var firstRun = $('.noarticletext').length;
 
            $('#WikiaArticle').empty().append('<div id="wikimarks-container">' +
                '<textarea id="wikimarks-input" class="wikimarks-overlap"></textarea>' +
                '<div id="wikimarks-shadow" class="wikimarks-overlap"></div>' +
            '</div>');
 
            container = $('#wikimarks-container');
            editor    = $('#wikimarks-input');
            shadow    = $('#wikimarks-shadow');
            wikimarks = $('#wikimarks');
 
            if (!$.browser.msie) {
                editor.attr('wrap', 'off');
                shadow.css({ whiteSpace: 'pre' });
            }
 
            $('#article-throbber').remove();
            $('#article-lid').remove();
 
            ns.Submenu.load();
 
            if (firstRun) {
                initEditor("* Wiki Activity = Special:WikiActivity\n* Random Page = Special:Random\n* Videos = Special:Videos\n* New Photos = Special:NewFiles\n* Chat = Special:Chat\n* Forum = Forum:Index\n");
            } else {
                $.get('/wiki/User:' + encodeURIComponent(wgUserName) + '/Wikimarks?action=raw&maxage=0&smaxage=0')
                .done(initEditor);
            }
 
            if (document.referrer) {
                var m = document.referrer.match(/http:\/\/([\w\-.]+)\.wikia\.com\/wiki\/([^?]*)/);
                if (m) {
                    var server = 'community' == m[1] ? 'w:' : 'w:c:' + m[1] + ':';
                    $('#wikimarks-referer').val(server + m[2]);
                }
            }
 
            initPanels();
        });
    }
 
    ns.Editor = {
        setCaret: function (c) { caret = c; },
        getEditor: function () { return editor; },
        getShadow: function () { return shadow; },
        load: load
    };
 
}(window.Wikimarks = window.Wikimarks || {}));
 
//

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.