All pastes #1032002 Raw Edit

Untitled

public javascript v1 · immutable
#1032002 ·published 2008-05-28 12:00 UTC
rendered paste body
// ==UserScript==// @name           search_and_navigation.js// @namespace      http://example.org// @description    adds navigational shortcuts and an instant-search features// @include        http://www.norbits.net/*// @include        http://norbits.net/*// @include        https://www.norbits.net/*// @include        https://norbits.net/*// ==/UserScript== (function () {     if (location.hostname.indexOf('norbits.net') == -1) {        return false;    }    var    labelColor = 'green',    //whether or not to focus the input field when pressing "s" or "l"    autoFocusInputField = true,    //should the modifier keys be appended to the side panel    //with uppercased letters?    upperCasedLabels = true,       closeButton = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAAXNSR0IArs' +'4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9gFERYGGE9ha3' +'oAAAFfSURBVBjTBcHLahNhGIDh9/sPM+OkmKRNJFKiVnugMVBqKW7UlYVegAtvwZW34j14D90JupDair' +'S4kOIBjMRQtYVkKkb/mfyfzyMr4E8xnRJ9rGhPoQmCoIUgny3y/CpxKKlzXVNVT3KkW4PXXvRIRGIZ6U' +'/hwW+hKI17ZusxPl1G7u8I35cs4VEipo52d6ykXaUWVDemqk3XQO5uG6ltpbF3LGwdKOO/jvxeqj9bgX' +'n+Sf4nsm36RlfXvUrnEtVuxuCwZGXd86vlmHZyytsJ9Ay3TEso6okWc5bhi0B+x/PuY4ksGIYNw7e618' +'k8euEmlpczww2v/Nj0jB5e5svelHYmBKeEmdC4sHywbYdpKtevCUU/Y+A949WMM5RYVNSOSubez9iz59' +'4VMcbxRFgcQXoKcRBJjgMLbyuy/ZJXb7AH4lPTdBqTNZGljtWbVxLaBjgLcj5S+Xqi8VNQE/4DwQmN67' +'EZdgMAAAAASUVORK5CYII=';   /* ---------------------------------- No edit ---------------------------------- */   // increased by 5 for each search box, enables stacks of boxes   // var displayAt = '50';//percentage        function getNodes(expression, startElement) {        startElement = startElement || document;        return document.evaluate(expression, startElement, null,                                   XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);    }     function toggleVisibility(boxContainer) {        if (typeof(boxContainer) == 'string') {            boxContainer = document.getElementById(boxContainer);        }                if (!boxContainer) {            return;        }        if (boxContainer.style.display == 'block') {            boxContainer.style.display = 'none';        } else {                           boxContainer.style.display = 'block';            var searchBox =  boxContainer.getElementsByTagName('input')[0];            if (searchBox && autoFocusInputField) {                searchBox.focus();                searchBox.select();            }        }     }            function createSearchBox(windowTitle, action, labelString,                               submitText, /* hash */ search /*{name, value */) {        var inputName = search.name || 'search';        var searchValue =  search.value || '';        windowTitle = windowTitle || 'Search!';        labelString = labelString || ' Search:';        submitText  = submitText  || 'Go!';               var container = document.createElement('div');        container.style.backgroundColor = '#e8e8e8';        container.style.display = 'none';        container.style.width = '240px';        container.style.height = '50px';        container.style.position = 'fixed';        container.style.top = '50%';//displayAt + '%';        container.style.left = '50%';         container.style.marginTop = '-25px';        container.style.marginLeft = '-100px';        container.style.border = '2px solid black';       // displayAt =Number(displayAt) + 3;              var win =  document.createElement('div');        win.style.backgroundColor = '#d7d7d7';                win.style.fontSize = '11px';                var btn = new Image();        btn.src = closeButton;        btn.addEventListener('mouseover', function () {            btn.style.opacity = 0.8;        }, false);               btn.addEventListener('mouseout', function () {            btn.style.opacity = 1;               }, false);               //box.appendChild(btn) ;         win.appendChild(btn);                var winTitle = document.createElement('span');        winTitle.style.color = 'gray';        winTitle.appendChild(document.createTextNode(windowTitle));        win.appendChild(winTitle);                                //change visibility when pressing close button        //box.addEventListener('click', _toggleVisibility, false);                container.appendChild(win);                var form = document.createElement('form');        form.method = "get";        form.action = action;        var controlsContainer = document.createElement('div');        controlsContainer.style.margin = '20px';        var searchLabel = document.createElement('label');        searchLabel.setAttribute('for', 'search');        searchLabel.appendChild(document.createTextNode(labelString));        controlsContainer.appendChild(searchLabel);        var searchElm = document.createElement('input');        searchElm.name = inputName;               searchElm.type = 'text';        searchElm.value = searchValue;        controlsContainer.appendChild(searchElm);        var submit = document.createElement('input');        submit.type = 'submit';        submit.value = submitText;         controlsContainer.appendChild(submit);        form.appendChild(controlsContainer);        container.appendChild(form);                btn.addEventListener('click', function () {            toggleVisibility(container);        }, false);        return container;    }                       var get = {};   // http://www.bennadel.com/blog/695-Ask-Ben-Getting-Query-String-Values-In-JavaScript.htm    window.location.search.replace(    new RegExp("([^?=&]+)(=([^&]*))?", "g"),    function ($0, $1, $2, $3) {        get[$1] = unescape($3).replace(/\+/g, ' ');    }    );     function start(e) {         try {             var body = document.body;            if (!body) {                return;            }                        //s and l are reserved, and will not be triggered            var labels = {h: ['Hjem'], c: ['Chat'], f: ['Forum'],                         r: ['Regler'], q: ['FAQ'],                         b: ['Liste over torrents'],                         u: ['Last opp'], p: ['Profil'], d: ['Detaljer'],                         v: ['Venner'], t: ['Mine torrents']};                       //add labels to the links present in the dom            var sidePanel = getNodes('//table[@class="main"]//td[@class="embedded"]' +                        '//h2[contains(text(), "Generelt")]/..').snapshotItem(0);            if (!sidePanel) {                return;            }            //opera before 9.5 would return a text node (nodeType=3),            //newer versions plus fx skips text nodes            //and returns a node with nodeType=1            //"../" in opera before 9.5 would jump one node in the DOM            //while it should jump to the previous node            //defined in the xpath, the "td"                       if (sidePanel.nodeType == Node.TEXT_NODE) {                sidePanel = sidePanel.parentNode.parentNode;            }                        //finds the modifier(f,h etc) and its label            //appends the modifier value to the label            for (var modifier in labels) {                if (labels.hasOwnProperty(modifier)) {                      var text = labels[modifier][0];                    var node = getNodes('.//a[text()="' + text + '"]', sidePanel).snapshotItem(0);                    if (!node) {                        continue;                    }                    //save nodes for later use                    labels[modifier][1] = node;                                        if (upperCasedLabels) {                        modifier = modifier.toUpperCase();                    }                                        var label = document.createElement('span');                    label.style.color = labelColor;                    label.style.fontWeight = 'bolder';                    label.appendChild(document.createTextNode(' [' + modifier + ']'));                    node.appendChild(label);                  }             }             //windowTitle, action, labelString,  submitText, /* hash */ search /*{name, value */)            var torrentSearch = createSearchBox(' Torrentsearch', 'browse.php',                                                null, null,                                        {name: 'search', value: get.search});            var logSearch = createSearchBox(' LogSearch', 'log.php',                                            null, null,                                            {name: 'query', value: get.query});                                    body.appendChild(torrentSearch);            body.appendChild(logSearch);            window.addEventListener('keypress',             function (event) {                var target = event.target;                var isFormElement = (target.form !== undefined);                 //let user type normally on form elements                //do not listen if modifiers are present                if (isFormElement || event.altKey || event.ctrlKey ||                        event.metaKey || event.shiftKey || event.which === 0) {                    return;                }                var keyPressed = String.fromCharCode(event.which).toLowerCase();                                //e.isChar hack                if (!keyPressed) {                    return;                }                if (keyPressed == 's') {                    //stops focused element from recieving char "s"                    event.preventDefault();                    toggleVisibility(torrentSearch);                } else if (keyPressed == 'l') {                    //stops focused element from recieving char "l"                    event.preventDefault();                    toggleVisibility(logSearch);                                } else {                    if (labels.hasOwnProperty(keyPressed)) {                                            var anchor = labels[keyPressed][1];                        if (!anchor) {                            throw new Error('failure to get href associated with modifier ' + keyPressed);                        }                        anchor.focus();                        //alert(newLocation);                        window.location = anchor.href;                                        }                }            }, false);                } catch (ex) {            alert('feil: ' + ex);        }    }    if (window.opera) {        window.addEventListener('DOMContentLoaded', start, false);    } else {        window.addEventListener('load', start, false);    }})();