Benutzer:Sphinx/hilit npcs.js

aus FreewarWiki, der Referenz für Freewar
Zur Navigation springen Zur Suche springen
Hinweis
Nach dem Speichern sollte zunächst der Browser-Cache geleert werden, bevor man die Auswirkungen der Änderung sehen kann.
  • Mozilla/Firefox/Safari: Strg + R (Mactaste + R bei Macintosh) drücken
  • Konqueror: F5 drücken
  • Opera: kompletten Cache unter Extras → Internetspuren löschen → Individuelle Auswahl leeren
  • Internet Explorer: Strg + F5


(function ( window, __undefined ) {
    'use strict';
    var HILIT_VAR_NAME = 'npcs_hilit',
        document = window.document,
        get_href_prop = function (elem) {
            var props = ['href', 'action'],
                i = 0, length = props.length;
                
            for ( i, length; i < length; i += 1 ) {
                if ( elem[props[i]] !== __undefined ) {
                    return props[i];
                }
            }
            
            return null;
        },
        get_npc_name_container = function ( document ) {
            var container = $( '#npc_name_for_hilit', document );
            
            if ( container.length ) {
                return container;
            }
            
            // fallback
            return $( 'table.layout_color_npc tr:first td:last b', document );
        },
        get_occurences = function ( document ) {
            var occurences = $( 'ul#npc_occurences li' );
            
            if ( occurences.length ) {
                return occurences;
            }
            
            // fallback
            return $( 'td[rowspan="3"][width="49%"] > b:contains("Vorkommen:") + ul li', document );
        },
        Hashbang = function ( origin ) {
                // const
            var delimiters = {
                    param: '?',
                    params: '&',
                    path: '/'
                },
                hashbang = '#!',
                path_file_pattern = /^(.*\/?)(.*)$/,
                // construct vars
                i = 0,
                length = 0,
                location = origin[get_href_prop( origin )].split( hashbang ),
                param_parts = [],
                params = {},
                path_parts = [],
                query_parts = [],
                // private
                path = '',
                query_string = '',
                file = '';
                
            
            if ( location.length > 1 ) { // hashbang given
                path_parts = location[1].split( delimiters.param );
                    
                // init private vars
                path = path_parts[0].match( path_file_pattern )[1] || '';
                file = path_parts[0].match( path_file_pattern )[2] || '';
                query_string = path_parts[1] || '';
            }
            
            
            if ( query_string !== '' ) { // hashbang set
                query_parts = query_string.split( delimiters.params );
                // loop through each key-value pa
                for ( i = 0, length = query_parts.length; i < length; i += 1 ) {
                    param_parts = query_parts[i].split( '=' ); // split pair
                    params[param_parts[0]] = param_parts[1] === __undefined ? '' : decodeURIComponent( param_parts[1] );
                }
            }
            
            /*
            console.log('Path        : ', path);
            console.log('File        : ', file);
            console.log('query_string: ', query_string);
            console.log('Params      : ', params);//*/
            
            this.apply = function (to) { // applies hashbang to the origin
                to = to || origin;
                
                to[get_href_prop( to )] = location[0] + hashbang + this.full_path();
            };
            
            this.file = function (new_file) {
                var delimiter_name = '',
                    pattern = [];
                if (new_file !== __undefined) {
                    for ( delimiter_name in delimiters ) {
                        // escape the delimiter
                        pattern.push( '\\' + delimiters[delimiter_name] ); 
                    }
                    
                    // replace delimiters
                    file = new_file.replace( new RegExp( '(' + pattern.join( '|' ) + ')', 'g' ), '' ); 
                }
                
                return '' + file;
            };
            
            this.full_path = function () {
                var full_path = this.path() + this.file(),
                    query_string = this.query_string();
                
                if ( query_string ) {
                    full_path += delimiters.param + query_string;
                }
                
                return full_path;
            };
            
            this.param = function ( name, value ) {
                if ( name === __undefined ) { // get all
                    return params;
                }
                if ( value !== __undefined ) { // setter
                    params[name] = value;
                }
                return params[name]; // getter
            };
            
            this.path = function (new_path) {
                if (new_path !==  __undefined) {
                    // no trailing `/`
                    if (!new_path.match( new RegExp( delimiters.path + '$', 'g' ) )) { 
                        new_path += delimiters.path;
                    }
                    
                    // replace param delimiter in path
                    path = new_path.replace( delimiters.param, '' );
                }
                
                return ('' + path) || delimiters.path;
            };
            
            this.query_string = function () { // computes query_string
                var name = '',
                    parts = [];
                for ( name in params ) {
                    // we better escape the value
                    parts.push( name + '=' + encodeURIComponent( params[name] ) ); 
                }

                return parts.join( delimiters.params );
            };
        };
    
    $(document).ready( function () {
        // mw environment. not needed in production
        if ( mw === __undefined ) {
            var mw = (function () {
                var config = {
                        wgArticlePath: 'http://www.fwwiki.de/index.php/$1',
                        wgNamespaceNumber: 0
                    },
                    namespaces = {
                        108: "karte",
                        0  : __undefined
                    },
                    namespace_number = 0,
                    parts = window.location.href.match( /index\.php\/([a-z]*:)?(\w+)/i );

                //console.log( parts );

                if ( parts[1] !== __undefined ) {
                    parts[1] = parts[1].slice( 0, -1 ).toLowerCase(); // strip `:` and lc

                    for ( namespace_number in namespaces ) {
                        if ( namespaces[namespace_number] == parts[1] ) {
                            config.wgNamespaceNumber = namespace_number;
                            break;
                        }
                    }
                }

                return {
                    config: {
                        get: function ( name ) {
                            return config[name];
                        }
                    }
                };
            }());
        }
        // mw environment end

        if ( mw.config.get( 'wgNamespaceNumber' ) == 108 ) { // Karte
            // match the top div to apply the css to the top container
            $( '.maplink div[style="position:relative;"]' ).each( function ( i, elem ) {
                var npcs = [];
                // npc links
                $( '.NPC', elem ).each( function ( i, npc ) {
                   npcs.push( '/' + $( npc ).text() + '/' ); 
                });

                $( elem ).attr( 'data-npcs', npcs );
            });

            // loadscript karte_hilit
            (function ( window, __undefined )  {
                var document = window.document,
                    form = null,
                    hashbang = new Hashbang( window.location ),
                    apply_hilit = function ( hashbang ) {
                        var found = 0;
                        if ( hashbang.param( HILIT_VAR_NAME ) !== __undefined ) {
                            // mark it
                            found = hilit_npcs( hashbang.param( HILIT_VAR_NAME ).split( ',' ) );

                            // and display number of occurences
                            $( '#npc_hilit_hint' ).text( found + ' NPC angezeigt' );
                        }
                    },
                    hilit_npcs = function ( hilit_npc_names ) {
                        var class_name = 'npc_hilit',
                            hilit_count = 0,
                            fields = [],
                            i = 0,
                            length = hilit_npc_names.length;

                        // reset
                        $( '.' + class_name ).removeClass( class_name );

                        for ( i, length; i < length; i += 1 ) { // loop through each name
                            // and mark it TODO: case-sensitive?
                            fields = $( 'div[data-npcs*="/' + hilit_npc_names[i] + '/"]' ); 
                            fields.addClass( class_name );

                            // save number of hilits
                            hilit_count += fields.length;
                        }

                        return hilit_count;
                    };

                // create hilit_form
                form = $( '<form/>', {
                    id: 'npc_hilit_form',
                    method: '',
                    submit: function ( event ) {
                        var npc_names = $( '#npc_hilit_name' ).val();

                        // save new hilit_npc
                        hashbang.param( HILIT_VAR_NAME, npc_names);
                        hashbang.apply();

                        // mark it
                        apply_hilit( hashbang );

                        return false; // prevent submit on 1st try
                    }
                } ).append( $( '<label/>', {
                                'for': 'npc_hilit_name',
                                text: 'NPC: '
                            } ),
                            $( '<input/>', {
                                id: 'npc_hilit_name',
                                type: 'text'
                            } ).val( hashbang.param( HILIT_VAR_NAME ) ), 
                            $( '<input/>', {
                                type: 'submit',
                                value: 'Anzeigen'
                            } ),
                            $( '<div/>', {
                                id: 'npc_hilit_hint'
                            }) );
                // display form
                $( '#map_redZK' ).before( form );

                // initial hilit
                apply_hilit( hashbang );
            }( window ));
        } else {
            if ( get_npc_name_container( document ).length ) { // ncp article
                // loadscript link_for_karte_hilit
                (function ( window, __undefined ) {
                    var document = window.document,
                        npc_name = get_npc_name_container( document ).text();

                    //console.log( npc_name, get_occurences( document ) );

                    get_occurences( document ).each( function ( i, li ) { // all occurence entries
                        var link = $( '<a/>', {
                                        href: mw.config.get( 'wgArticlePath' ).
                                              replace( '$1', 'Karte:' + $( 'a:first', li ).text() ),
                                        html: '&nbsp;&nbsp;&nbsp;'
                                    }).addClass( 'linktomap' ),
                             hashbang = new Hashbang( link[0] );

                        // add hilit npc
                        hashbang.param( HILIT_VAR_NAME, npc_name );
                        hashbang.apply();

                        $( li ).append( link );
                    });
                }( window ) );
            }
        }
        
    } );
}( window ) );