User:Torty3/editor.js

/******************************************************************  Listing Editor v1.0 (torty3) How to use: Add to common.js    importScript('User:Torty3/editor.js'); Localisation: Translate strings at 'User:Torty3/editor-options.js' ( function ( mw, $ ) {   'use strict';    //if ( mw.config.get( 'wgNamespaceNumber' ) != 0 ) {    //    return;    //}    importStylesheet('User:Torty3/editor.css');    var allFields = {        'type': {size:8, advanced:true, newline:true, parameter:'type', label:'Type', tip:'type of listing' },        'name': {size:32, advanced:false, newline:false, parameter:'name', label:'Name', tip:'name of place'},        'alt': {size:32, advanced:false, newline:false, parameter:'alt', label:'alt', tip:'also known as'},        'url': {size:32, advanced:false, newline:false, parameter:'url', label:'Website', tip:'http://www.example.com'},        'email': {size:32, advanced:true, newline:true, parameter:'email', label:'Email', tip:'hello@example.com'},        'address': {size:32, advanced:false, newline:false, parameter:'address', label:'Address', tip:'address of place'},        'lat': {size:12, advanced:true, newline:false, parameter:'lat', label:'Latitude', tip:'11.111111'}, 'long': {size:12, advanced:true, newline:false, parameter:'long', label:'Longitude', tip:'111.111111'}, 'directions': {size:32, advanced:false, newline:true, parameter:'directions', label:'Directions', tip:'how to get here'}, 'phone': {size:20, advanced:false, newline:false, parameter:'phone', label:'Phone', tip: '+55 555 555-5555'}, 'tollfree': {size:20, advanced:true, newline:false, parameter:'tollfree', label:'Tollfree', tip:'1800 100 1000'}, 'fax': {size:20, advanced:true, newline:false, parameter:'fax', label:'Fax', tip: '+55 555 555-555'}, 'image': {size:20, advanced:true, newline:true, parameter:'image', label:'Image', tip: 'image of place'}, 'hours': {size:24, advanced:false, newline:false, parameter:'hours', label:'Hours', tip: '9AM-5PM or 9:00-17:00'}, 'checkin': {size:12, advanced:true, newline:false, parameter:'checkin', label:'Check-in', tip: 'check in time'}, 'checkout': {size:12, advanced:true, newline:false, parameter:'checkout', label:'Check-out', tip: 'check out time'}, 'price': {size:24, advanced:false, newline:true, parameter:'price', label:'Price', tip: 'entry or service price'}, 'content': {cols:30, rows:7, advanced:false, newline:true, parameter:'content', label:'Content', tip: 'description of place'} };

var listingType = {'see':'see', 'do':'do', 'buy':'buy', 'eat':'eat', 'drink':'drink', 'sleep':'sleep', 'listing':'listing'};

function addListingButtons { if ($('#guide_city').length) { var editButton = $(' ') .html(' ['+'add listing'+']' ) .click(function {                   var listingEntry = $(this).parent; console.log(listingEntry.html);                    //popupForm('add', listingEntry);                }); $('h2').append(editButton); }   }

function editListingButtons { var editButton = $(' ') .html(' '+'edit'+'' ) .click(function {               var listingEntry = $(this).parent; console.log(listingEntry.html);                //popupForm('edit', listingEntry);            }); $('.vcard').append( editButton ); } /*   function findIdentifier( entry ) { var name = entry.find('.org').text; var address = entry.find('.label').text; if (name) return name; return address; }

function findSectionNumber(entry) { //return entry.parent.parent.prevAll( 'h2' ).find( '.mw-editsection a' ).attr( 'href' ).split( '=' ).pop; return entry.find( '.mw-editsection a' ).attr( 'href' ).split( '=' ).pop; }

function findSectionHeading(entry) { var section = entry.find('.mw-headline').text.toLowerCase; for (var key in listingType) { if( section == listingType[key]) return section; }       return listingType.listing; }

function getSectionText(number) { var wikiText = $.ajax({           type: "GET",            url: '/w/index.php?title=' + wgPageName + '&action=raw&oldid=' + wgCurRevisionId + '&section=' + number,            dataType: 'text',            async: false        }).responseText; return wikiText; }

function popupForm(mode, entry) { mw.loader.using( ['jquery.ui.dialog'], function {        var listingId, sectionHeading, sectionNumber, sectionText, listing;        if (mode == 'add') {            listingId = ;                    sectionHeading = findSectionHeading(entry);            sectionNumber = findSectionNumber(entry);            sectionText = getSectionText(sectionNumber);            listing = {};        }        else {            listingId = findIdentifier(entry);            sectionHeading = ;            sectionNumber = findSectionNumber(entry.parent.parent.prevAll( 'h2' ));            sectionText = getSectionText(sectionNumber);            //listing = getListing(sectionText);             //TODO proper parsing            sectionText ='';            listing = {type:"sleep", name:listingId, address:"12 Test Ave", directions:"down the road"};        }        // GET wikisection && listing        var form = $(createForm(mode, sectionHeading, listing)); // modal form - must submit or cancel form.dialog({           modal: true,            height: 'auto',            width: 'auto',            title: mode,            buttons: [                {   text: 'Submit', click: function {                        if(validateForm) {                            formToText(mode, sectionText, sectionNumber);                            $(this).dialog('destroy').remove;                        }                       }                },                {text: 'Cancel', click: function {$(this).dialog('destroy').remove}}            ],            close: function { $(this).dialog('destroy').remove}        }); });   }    function createForm(mode, type, listing) {        var form = $('');        // only show primary fields, hide secondary fields        var requiredFields = $('').appendTo(form);        var advancedFields = $('').appendTo(form).hide;        var advancedButton = $( ' ')            .html('more fields' )            .appendTo(form)            .click(function { if ( $('#advanced-fields').css('display') == 'none' ) { $('#advanced-fields').show; $('.expand a.text').text('less fields'); }               else { $('#advanced-fields').hide; $('.expand a.text').text('more fields'); }           });        //create form according to fields        for (var key in allFields) {            var node = $(' ')                .attr('id', 'div_' + key);            var label = $(' ').appendTo(node)                .text(allFields[key]['label'])                .attr('for', 'form-' + key);            // input text for everything except content which gets textarea            if (key != 'content') {                var subnode = $(' ').appendTo(node)                    .attr('type', 'text')                    .attr('size', allFields[key]['size']);            }            else {                var subnode = $(' ').appendTo(node)                    .attr('cols', allFields[key]['cols'])                    .attr('rows', allFields[key]['rows']);            }            subnode.attr('placeholder', allFields[key]['tip'])                   .attr('id', 'input-' + key);            var parameter = allFields[key]['parameter']; if (listing[parameter]) { subnode.attr( 'value', listing[parameter] ); }           if (mode == 'add') { if (key == 'type') { subnode.attr('value', type); subnode.attr('readonly', 'readonly') .attr('style', 'font-weight:bold; border: 1px solid #ffffff; outline:none;'); }           }            else { if (key == 'type' || key == 'name') { subnode.attr('readonly', 'readonly') .attr('style', 'font-weight:bold; border: 1px solid #ffffff; outline:none;'); }           }            if (allFields[key]['advanced'] == true) { // only sleep listings get checkin and checkout if (key == 'checkin' || key == 'checkout') { if (listing[allFields['type']['parameter']] != listingType.sleep.toLowerCase) { node.hide; }               }                advancedFields.append(node); }           else { requiredFields.append(node); }       }        return form; }   function validateForm { //TODO more form validation? if ($('#input-name').val ==  && $('#input-address').val == ) { alert('Please enter either a name or an address'); return false; }       return true; }   function upperCaseFirst(str) { str = str.toLowerCase.replace(/\b[a-z]/g, function(letter) {           return letter.toUpperCase;        }); return str; }   function formToText(mode, sectiontext, number) { var listing = {}; for ( var key in allFields ) { var parameter = allFields[key]['parameter']; listing[parameter]= $("#input-"+key).val; }       if (listing[allFields['type']['parameter']] != listingType.sleep.toLowerCase) { listing[allFields['checkin']['parameter']] = null; listing[allFields['checkout']['parameter']] = null; }       var text = listingToStr(listing); var summary = '/* ' +upperCaseFirst($("#input-type").val) + ' */ '; if (mode == 'add') { summary += 'Added listing for '; sectiontext += '\n'+ '* ' +text; }       else { summary += 'Edited listing for '; //sectiontext += text; sectiontext = sectiontext.replace(oldtext,text); }       summary += $("#input-name").val; //alert(summary+'\n'+sectiontext); saveForm(summary, sectiontext, number); return; }   function saveForm(summary, content, number) { $.ajax( {           url: mw.util.wikiScript( 'api' ),            data: {                'format': 'json',                'action': 'edit',                'title': mw.config.get('wgPageName'),                'section': number,                'token': mw.user.tokens.get( 'editToken' ),                'text': content,                'summary': summary,            },            type: 'POST',            datatype: 'json',            success: function( data ) {                if ( data && data.edit && data.edit.result == 'Success' ) {                  window.location.reload; // reload page if edit was successful                } else if ( data && data.error ) {                    alert( 'Error: API returned error code "' + data.error.code + '": ' + data.error.info );                } else {                    alert( 'Error: Unknown result from API.' );                }            },            error: function( xhr ) { alert( 'Error: Request failed.' ); }       } )    }    function listingToStr(listing) {        var saveStr = '';        return saveStr;    }    */    $( document ).ready( function  { addListingButtons; editListingButtons; }; } ( mediaWiki, jQuery ) );