/*jshint smarttabs:true, loopfunc:true,forin:false*/
/*global mw, $, importScript */
// TODO: make autodate an option in the CiteTemplate object, not a preference  
// Global object
// TODO:
// * Remove this once the page is moved to a module 'ext.gadget.refToolbarDialogs' depending on 'ext.gadget.refToolbarBase'
if (typeof CiteTB === 'undefined') {
var CiteTB = {
"Templates" : {}, // All templates
"Options" : {}, // Global options
"UserOptions" : {}, // User options
"DefaultOptions" : {}, // Script defaults
"ErrorChecks" : {} // Error check functions
};
}  
// Only execute on edit, unless it is a user JS/CSS page
// TODO: Remove tests already done by MediaWiki:Gadget-refToolbar.js
if (
( mw.config.get('wgAction') === 'edit' || mw.config.get('wgAction') === 'submit' ) &&
( ( mw.config.get('wgNamespaceNumber') !== 2 && mw.config.get('wgNamespaceNumber') !== 4 ) ||
( mw.config.get('wgPageName').indexOf('.js') === -1 && mw.config.get('wgPageName').indexOf('.css') === -1 ) )
) {  
// TODO: Move this to MediaWiki:Gadget-refToolbarDialogs.css and add it to the definition of module 'ext.gadget.refToolbarDialogs'
mw.util.addCSS(".cite-form-td {"+
"height: 0 !important;"+
"padding: 0.1em !important;"+
"}");  
// Default options, these mainly exist so the script won't break if a new option is added
CiteTB.DefaultOptions = {
"date format" : "<year>-<zmonth>-<zdate>",
"autodate fields" : [],
"months" : ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
"modal" : true,
"autoparse" : false,
"expandtemplates": false
};  
// Get an option - user settings override global which override defaults
CiteTB.getOption = function(opt) {
if (CiteTB.UserOptions[opt] !== undefined) {
return CiteTB.UserOptions[opt];
} else if (CiteTB.Options[opt] !== undefined) {
return CiteTB.Options[opt];
}
return CiteTB.DefaultOptions[opt];
};  
CiteTB.init = function {
/* Main stuff, build the actual toolbar structure
- 1. get the template list, make the dropdown list and set up the template dialog boxes
- 2. actually build the toolbar:
- * A section for cites
- ** dropdown for the templates (previously defined)
- ** button for named refs with a dialog box
- ** button for errorcheck
- 3. add the whole thing to the main toolbar
- /  
if (typeof $('div[rel=cites]')[0] !== 'undefined') { // Mystery IE bug workaround
return;
}
$('head').trigger('reftoolbarbase');
var $target = $('#wpTextbox1');
var temlist = {};
for (var t in CiteTB.Templates) {
var tem = CiteTB.Templates[t];
var sform = CiteTB.escStr(tem.shortform);
var actionobj = {
type: 'dialog',
module: 'cite-dialog-'+sform
};
var dialogobj = {};
dialogobj['cite-dialog-'+sform] = {
resizeme: false,
titleMsg: 'cite-dialog-'+sform,
id: 'citetoolbar-'+sform,
init: function {},
html: tem.getInitial,
dialog: {
width:675,
open: function {
$(this).html(CiteTB.getOpenTemplate.getForm);
/** @param {jQuery.Event} e */
$('.cite-prev-parse').on( 'click', function ( e ) {
e.preventDefault;
CiteTB.prevParseClick;
});
},
buttons: {
'cite-form-submit': function {
var ref = CiteTB.getRef(false, true);
$(this).dialog( 'close' );
$.wikiEditor.modules.toolbar.fn.doAction( $(this).data( 'context' ), {
type: 'encapsulate',
options: {
post: ref
}
}, $(this) );
},
'cite-form-showhide': CiteTB.showHideExtra,
'cite-refpreview': function {
var ref = CiteTB.getRef(false, false);
var template = CiteTB.getOpenTemplate;
var div = $("#citetoolbar-"+CiteTB.escStr(template.shortform));
div.find('.cite-preview-label').show;
div.find('.cite-ref-preview').text(ref).show;
if (CiteTB.getOption('autoparse')) {
CiteTB.prevParseClick;
} else {
div.find('.cite-prev-parse').show;
div.find('.cite-prev-parsed-label').hide;
div.find('.cite-preview-parsed').html('');
}
},
'wikieditor-toolbar-tool-link-cancel': function {
$(this).dialog( 'close' );
},
'cite-form-reset': function {
CiteTB.resetForm;
}
}
}
};
$target.wikiEditor('addDialog', dialogobj);
//if (!CiteTB.getOption('modal')) {
//$('#citetoolbar-'+sform).dialog('option', 'modal', false);
//}
temlist[sform] = {label: tem.templatename, action: actionobj };
}  
var refsection = {
'sections': {
'cites': {
type: 'toolbar',
labelMsg: 'cite-section-label',
groups: {
'template': {
tools: {
'template': {
type: 'select',
labelMsg: 'cite-template-list',
list: temlist
}
}
},
'namedrefs': {
labelMsg: 'cite-named-refs-label',
tools: {
'nrefs': {
type: 'button',
action: {
type: 'dialog',
module: 'cite-toolbar-namedrefs'
},
icon: '//upload.wikimedia.org/wikipedia/commons//b/be/Nuvola_clipboard_lined.svg/-Nuvola_clipboard_lined.svg.png',
section: 'cites',
group: 'namedrefs',
labelMsg: 'cite-named-refs-button'
}
}
},
'errorcheck': {
labelMsg: 'cite-errorcheck-label',
tools: {
'echeck': {
type: 'button',
action: {
type: 'dialog',
module: 'cite-toolbar-errorcheck'
},
icon: '//upload.wikimedia.org/wikipedia/commons//a/a3/Nuvola_apps_korganizer-NO.png/-Nuvola_apps_korganizer-NO.png',
section: 'cites',
group: 'errorcheck',
labelMsg: 'cite-errorcheck-button'
}
}
}
}
}
}
};  
var defaultdialogs = {
'cite-toolbar-errorcheck': {
titleMsg: 'cite-errorcheck-label',
id: 'citetoolbar-errorcheck',
resizeme: false,
init: function {},
html: '<div id="cite-namedref-loading">'+
'<img src="//upload.wikimedia.org/wikipedia/commons/4/42/Loading.gif" />'+
'&nbsp;'+mw.usability.getMsg('cite-loading')+'</div>',
dialog: {
width:550,
open: function {
CiteTB.loadRefs;
},
buttons: {
'cite-errorcheck-submit': function {
var errorchecks = $("input[name='cite-err-test']:checked");
var errors = [];
for (var i=0; i<errorchecks.length; i++) {
errors = errors.concat(CiteTB.ErrorChecks[$(errorchecks[i]).val].run);
}
CiteTB.displayErrors(errors);
$(this).dialog( 'close' );
},
'wikieditor-toolbar-tool-link-cancel': function {
$(this).dialog( 'close' );
}
}
}
},
'cite-toolbar-namedrefs': {
titleMsg: 'cite-named-refs-title',
resizeme: false,
id: 'citetoolbar-namedrefs',
html: '<div id="cite-namedref-loading">'+
'<img src="//upload.wikimedia.org/wikipedia/commons/4/42/Loading.gif" />'+
'&nbsp;'+mw.usability.getMsg('cite-loading')+'</div>',
init: function {},
dialog: {
width: 550,
open: function {
CiteTB.loadRefs;
},
buttons: {
'cite-form-submit': function {
var refname = $("#cite-namedref-select").val;
if (refname === '') {
return;
}
$(this).dialog( 'close' );
$.wikiEditor.modules.toolbar.fn.doAction( $(this).data( 'context' ), {
type: 'encapsulate',
options: {
post: CiteTB.getNamedRef(refname, true)
}
}, $(this) );
},
'wikieditor-toolbar-tool-link-cancel': function {
$(this).dialog( 'close' );
}
}
}
}
};  
$target.wikiEditor('addDialog', defaultdialogs);
$('#citetoolbar-namedrefs').off('dialogopen');
if (!CiteTB.getOption('modal')) {
//$('#citetoolbar-namedrefs').dialog('option', 'modal', false);
//$('#citetoolbar-errorcheck').dialog('option', 'modal', false);
mw.util.addCSS(".ui-widget-overlay {"+
"display: !important;"+
"}");
}
$target.wikiEditor('addToToolbar', refsection);
};  
// Load local data - messages, cite templates, etc.
$(document).ready( function {
switch( mw.config.get('wgUserLanguage') ) {
case 'ta': // Tamil
importScript('MediaWiki:RefToolbarMessages-ta.js');
break;
default: // English
importScript('MediaWiki:RefToolbarMessages-en.js');
}
});  
// Setup the main object
CiteTB.mainRefList = [];
CiteTB.refsLoaded = false;  
// REF FUNCTIONS
// Actually assemble a ref from user input
CiteTB.getRef = function(inneronly, forinsert) {
var i;
var template = CiteTB.getOpenTemplate;
var templatename = template.templatename;
var res = '';
var refobj = {'shorttag':false};
if (!inneronly) {
var group = $('#cite-'+CiteTB.escStr(template.shortform)+'-group').val;
var refname = $('#cite-'+CiteTB.escStr(template.shortform)+'-name').val;
res += '';
}
if (forinsert) {
CiteTB.mainRefList.push(refobj);
}
return res;
};  
// Make a reference to a named ref
CiteTB.getNamedRef = function(refname, forinsert) {
if (forinsert) {
CiteTB.mainRefList.push( {'shorttag':true, 'refname':refname} );
}
return '';
};  
// Function to load the ref list