3 */jQuery.extend({createUploadIframe:function(d,b){var a="jUploadFrame"+d;if(window.ActiveXObject){var c=document.createElement('<iframe id="'+a+'" name="'+a+'" />');if(typeof b=="boolean"){c.src="javascript:false"}else{if(typeof b=="string"){c.src=b}}}else{var c=document.createElement("iframe");c.id=a;c.name=a}c.style.position="absolute";c.style.top="-1000px";c.style.left="-1000px";document.body.appendChild(c);return c},createUploadForm:function(g,b){var e="jUploadForm"+g;var a="jUploadFile"+g;var d=$('<form action="" method="POST" name="'+e+'" id="'+e+'" enctype="multipart/form-data"></form>');var c=$("#"+b);var f=$(c).clone();$(c).attr("id",a);$(c).before(f);$(c).appendTo(d);$(d).css("position","absolute");$(d).css("top","-1200px");$(d).css("left","-1200px");$(d).appendTo("body");return d},ajaxFileUpload:function(k){k=jQuery.extend({},jQuery.ajaxSettings,k);var a=new Date().getTime();var b=jQuery.createUploadForm(a,k.fileElementId);var i=jQuery.createUploadIframe(a,k.secureuri);var h="jUploadFrame"+a;var j="jUploadForm"+a;if(k.global&&!jQuery.active++){jQuery.event.trigger("ajaxStart")}var c=false;var f={};if(k.global){jQuery.event.trigger("ajaxSend",[f,k])}var d=function(l){var p=document.getElementById(h);try{if(p.contentWindow){f.responseText=p.contentWindow.document.body?p.contentWindow.document.body.innerText:null;f.responseXML=p.contentWindow.document.XMLDocument?p.contentWindow.document.XMLDocument:p.contentWindow.document}else{if(p.contentDocument){f.responseText=p.contentDocument.document.body?p.contentDocument.document.body.textContent||document.body.innerText:null;f.responseXML=p.contentDocument.document.XMLDocument?p.contentDocument.document.XMLDocument:p.contentDocument.document}}}catch(o){jQuery.handleError(k,f,null,o)}if(f||l=="timeout"){c=true;var m;try{m=l!="timeout"?"success":"error";if(m!="error"){var n=jQuery.uploadHttpData(f,k.dataType);if(k.success){k.success(n,m)}if(k.global){jQuery.event.trigger("ajaxSuccess",[f,k])}}else{jQuery.handleError(k,f,m)}}catch(o){m="error";jQuery.handleError(k,f,m,o)}if(k.global){jQuery.event.trigger("ajaxComplete",[f,k])}if(k.global&&!--jQuery.active){jQuery.event.trigger("ajaxStop")}if(k.complete){k.complete(f,m)}jQuery(p).unbind();setTimeout(function(){try{$(p).remove();$(b).remove()}catch(q){jQuery.handleError(k,f,null,q)}},100);f=null}};if(k.timeout>0){setTimeout(function(){if(!c){d("timeout")}},k.timeout)}try{var b=$("#"+j);$(b).attr("action",k.url);$(b).attr("method","POST");$(b).attr("target",h);if(b.encoding){b.encoding="multipart/form-data"}else{b.enctype="multipart/form-data"}$(b).submit()}catch(g){jQuery.handleError(k,f,null,g)}if(window.attachEvent){document.getElementById(h).attachEvent("onload",d)}else{document.getElementById(h).addEventListener("load",d,false)}return{abort:function(){}}},uploadHttpData:function(r,type){var data=!type;data=type=="xml"||data?r.responseXML:r.responseText;if(type=="script"){jQuery.globalEval(data)}if(type=="json"){eval("data = "+data)}if(type=="html"){jQuery("<div>").html(data).evalScripts()}return data}});
5 function ajaxFileUpload(imageUrl)
7 $("#loading").ajaxStart(function(){
9 }).ajaxComplete(function(){
13 $("#upload").ajaxStart(function(){
15 }).ajaxComplete(function(){
24 fileElementId:'file-upload',
26 success: function (data, status)
28 var fileURL = $(data).find('file_url').text();
29 var error = $(data).find('error').text();
33 imageUrl.attr('value', fileURL);
37 error: function (data, status, e)
47 var Attacklab = Attacklab || {};
49 Attacklab.wmdBase = function(){
51 // A few handy aliases for readability.
52 var wmd = top.Attacklab;
53 var doc = top.document;
55 var nav = top.navigator;
64 var position = wmd.Position;
65 var command = wmd.Command;
66 var global = wmd.Global;
69 // Used to work around some browser bugs where we can't use feature testing.
70 global.isIE = /msie/.test(nav.userAgent.toLowerCase());
71 global.isIE_5or6 = /msie 6/.test(nav.userAgent.toLowerCase()) || /msie 5/.test(nav.userAgent.toLowerCase());
72 global.isIE_7plus = global.isIE && !global.isIE_5or6;
73 global.isOpera = /opera/.test(nav.userAgent.toLowerCase());
74 global.isKonqueror = /konqueror/.test(nav.userAgent.toLowerCase());
76 var toolbar_strong_label = $.i18n._('bold') + " <strong> Ctrl-B";
77 var toolbar_emphasis_label = $.i18n._('italic') + " <em> Ctrl-I";
78 var toolbar_hyperlink_label = $.i18n._('link') + " <a> Ctrl-L";
79 var toolbar_blockquote_label = $.i18n._('quote') + " <blockquote> Ctrl-.";
80 var toolbar_code_label = $.i18n._('preformatted text') + " <pre><code> Ctrl-K";
81 var toolbar_image_label = $.i18n._('image') + " <img> Ctrl-G";
82 var toolbar_numbered_label = $.i18n._('numbered list') + " <ol> Ctrl-O";
83 var toolbar_bulleted_label = $.i18n._('bulleted list') + " <ul> Ctrl-U";
84 var toolbar_heading_label = $.i18n._('heading') + " <h1>/<h2> Ctrl-H";
85 var toolbar_horizontal_label = $.i18n._('horizontal bar') + " <hr> Ctrl-R";
86 var toolbar_undo_label = $.i18n._('undo') + " Ctrl-Z";
87 var toolbar_redo_label = $.i18n._('redo') + " Ctrl-Y";
89 // -------------------------------------------------------------------
90 // YOUR CHANGES GO HERE
92 // I've tried to localize the things you are likely to change to
94 // -------------------------------------------------------------------
96 // The text that appears on the upper part of the dialog box when
98 var imageDialogText = "<p style='margin-top: 0px'>" + $.i18n._('enter image url') + '</p>';
99 var linkDialogText = "<p style='margin-top: 0px'>" + $.i18n._('enter url') + '</p>';
100 var uploadImageHTML ="<div>" + $.i18n._('upload image') + "</div>" +
101 "<input type=\"file\" name=\"file-upload\" id=\"file-upload\" size=\"26\" "+
102 "onchange=\"return ajaxFileUpload($('#image-url'));\"/><br>" +
103 "<img id=\"loading\" src=\"" + mediaUrl("media/images/indicator.gif") + "\" style=\"display:none;\"/>";
105 // The default text that appears in the dialog input box when entering
107 var imageDefaultText = "http://";
108 var linkDefaultText = "http://";
110 // The location of your button images relative to the base directory.
111 var imageDirectory = "images/";
113 // Some intervals in ms. These can be adjusted to reduce the control's load.
114 var previewPollInterval = 500;
115 var pastePollInterval = 100;
117 // The link and title for the help button
118 var helpLink = "http://wmd-editor.com/";
119 var helpHoverTitle = "WMD website";
120 var helpTarget = "_blank";
122 // -------------------------------------------------------------------
123 // END OF YOUR CHANGES
124 // -------------------------------------------------------------------
126 // A collection of the important regions on the page.
127 // Cached so we don't have to keep traversing the DOM.
128 wmd.PanelCollection = function(){
129 this.buttonBar = doc.getElementById("wmd-button-bar");
130 this.preview = doc.getElementById("previewer");
131 this.output = doc.getElementById("wmd-output");
132 this.input = doc.getElementById("editor");
135 // This PanelCollection object can't be filled until after the page
137 wmd.panels = undefined;
139 // Internet explorer has problems with CSS sprite buttons that use HTML
140 // lists. When you click on the background image "button", IE will
141 // select the non-existent link text and discard the selection in the
142 // textarea. The solution to this is to cache the textarea selection
143 // on the button's mousedown event and set a flag. In the part of the
144 // code where we need to grab the selection, we check for the flag
145 // and, if it's set, use the cached area instead of querying the
148 // This ONLY affects Internet Explorer (tested on versions 6, 7
149 // and 8) and ONLY on button clicks. Keyboard shortcuts work
150 // normally since the focus never leaves the textarea.
151 wmd.ieCachedRange = null; // cached textarea selection
152 wmd.ieRetardedClick = false; // flag
154 // Returns true if the DOM element is visible, false if it's hidden.
155 // Checks if display is anything other than none.
156 util.isVisible = function (elem) {
158 if (window.getComputedStyle) {
160 return window.getComputedStyle(elem, null).getPropertyValue("display") !== "none";
162 else if (elem.currentStyle) {
164 return elem.currentStyle.display !== "none";
169 // Adds a listener callback to a DOM element which is fired on a specified
171 util.addEvent = function(elem, event, listener){
172 if (elem.attachEvent) {
173 // IE only. The "on" is mandatory.
174 elem.attachEvent("on" + event, listener);
178 elem.addEventListener(event, listener, false);
183 // Removes a listener callback from a DOM element which is fired on a specified
185 util.removeEvent = function(elem, event, listener){
186 if (elem.detachEvent) {
187 // IE only. The "on" is mandatory.
188 elem.detachEvent("on" + event, listener);
192 elem.removeEventListener(event, listener, false);
196 // Converts \r\n and \r to \n.
197 util.fixEolChars = function(text){
198 text = text.replace(/\r\n/g, "\n");
199 text = text.replace(/\r/g, "\n");
203 // Extends a regular expression. Returns a new RegExp
204 // using pre + regex + post as the expression.
205 // Used in a few functions where we have a base
206 // expression and we want to pre- or append some
207 // conditions to it (e.g. adding "$" to the end).
208 // The flags are unchanged.
210 // regex is a RegExp, pre and post are strings.
211 util.extendRegExp = function(regex, pre, post){
213 if (pre === null || pre === undefined)
217 if(post === null || post === undefined)
222 var pattern = regex.toString();
225 // Replace the flags with empty space and store them.
226 pattern = pattern.replace(/\/([gim]*)$/, "");
229 // Remove the slash delimiters on the regular expression.
230 pattern = pattern.replace(/(^\/|\/$)/g, "");
231 pattern = pre + pattern + post;
233 return new re(pattern, flags);
237 // Sets the image for a button passed to the WMD editor.
238 // Returns a new element with the image attached.
239 // Adds several style properties to the image.
240 util.createImage = function(img){
242 var imgPath = imageDirectory + img;
244 var elem = doc.createElement("img");
245 elem.className = "wmd-button";
252 // This simulates a modal dialog box and asks for the URL when you
253 // click the hyperlink or image buttons.
255 // text: The html for the input box.
256 // defaultInputText: The default value that appears in the input box.
257 // makeLinkMarkdown: The function which is executed when the prompt is dismissed, either via OK or Cancel
258 util.prompt = function(text, defaultInputText, makeLinkMarkdown){
260 // These variables need to be declared at this level since they are used
261 // in multiple functions.
262 var dialog; // The dialog box.
263 var background; // The background beind the dialog box.
264 var input; // The text box where you enter the hyperlink.
266 // The dialog box type(0: Link, 1: Image)
267 if(arguments.length == 4){
271 if (defaultInputText === undefined) {
272 defaultInputText = "";
275 // Used as a keydown event handler. Esc dismisses the prompt.
276 // Key code 27 is ESC.
277 var checkEscape = function(key){
278 var code = (key.charCode || key.keyCode);
284 // Dismisses the hyperlink input box.
285 // isCancel is true if we don't care about the input text.
286 // isCancel is false if we are going to keep the text.
287 var close = function(isCancel){
288 util.removeEvent(doc.body, "keydown", checkEscape);
289 var text = input.value;
295 // Fixes common pasting errors.
296 text = text.replace('http://http://', 'http://');
297 text = text.replace('http://https://', 'https://');
298 text = text.replace('http://ftp://', 'ftp://');
300 if (text.indexOf('http://') === -1 && text.indexOf('ftp://') === -1) {
301 text = 'http://' + text;
305 dialog.parentNode.removeChild(dialog);
306 background.parentNode.removeChild(background);
307 makeLinkMarkdown(text);
311 // Creates the background behind the hyperlink text entry box.
312 // Most of this has been moved to CSS but the div creation and
313 // browser-specific hacks remain here.
314 var createBackground = function(){
316 background = doc.createElement("div");
317 background.className = "wmd-prompt-background";
318 style = background.style;
319 style.position = "absolute";
322 style.zIndex = "1000";
324 // Some versions of Konqueror don't support transparent colors
325 // so we make the whole window transparent.
327 // Is this necessary on modern konqueror browsers?
328 if (global.isKonqueror){
329 style.backgroundColor = "transparent";
331 else if (global.isIE){
332 style.filter = "alpha(opacity=50)";
335 style.opacity = "0.5";
338 var pageSize = position.getPageSize();
339 style.height = pageSize[1] + "px";
342 style.left = doc.documentElement.scrollLeft;
343 style.width = doc.documentElement.clientWidth;
347 style.width = "100%";
350 doc.body.appendChild(background);
353 // Create the text input box form/window.
354 var createDialog = function(){
356 // The main dialog box.
357 dialog = doc.createElement("div");
358 dialog.className = "wmd-prompt-dialog";
359 dialog.style.padding = "10px;";
360 dialog.style.position = "fixed";
361 dialog.style.width = "400px";
362 dialog.style.zIndex = "1001";
365 var question = doc.createElement("div");
366 question.innerHTML = text;
367 question.style.padding = "5px";
368 dialog.appendChild(question);
370 // The web form container for the text box and buttons.
371 var form = doc.createElement("form");
372 form.onsubmit = function(){ return close(false); };
376 style.cssFloat = "left";
377 style.width = "100%";
378 style.textAlign = "center";
379 style.position = "relative";
380 dialog.appendChild(form);
382 // The input text box
383 input = doc.createElement("input");
385 input.id = "image-url";
388 input.value = defaultInputText;
390 style.display = "block";
392 style.marginLeft = style.marginRight = "auto";
393 form.appendChild(input);
395 // The upload file input
397 var upload = doc.createElement("div");
398 upload.innerHTML = uploadImageHTML;
399 upload.style.padding = "5px";
400 form.appendChild(upload);
404 var okButton = doc.createElement("input");
405 okButton.type = "button";
406 okButton.onclick = function(){ return close(false); };
407 okButton.value = "OK";
408 style = okButton.style;
409 style.margin = "10px";
410 style.display = "inline";
415 var cancelButton = doc.createElement("input");
416 cancelButton.type = "button";
417 cancelButton.onclick = function(){ return close(true); };
418 cancelButton.value = "Cancel";
419 style = cancelButton.style;
420 style.margin = "10px";
421 style.display = "inline";
424 // The order of these buttons is different on macs.
425 if (/mac/.test(nav.platform.toLowerCase())) {
426 form.appendChild(cancelButton);
427 form.appendChild(okButton);
430 form.appendChild(okButton);
431 form.appendChild(cancelButton);
434 util.addEvent(doc.body, "keydown", checkEscape);
435 dialog.style.top = "50%";
436 dialog.style.left = "50%";
437 dialog.style.display = "block";
438 if(global.isIE_5or6){
439 dialog.style.position = "absolute";
440 dialog.style.top = doc.documentElement.scrollTop + 200 + "px";
441 dialog.style.left = "50%";
443 doc.body.appendChild(dialog);
445 // This has to be done AFTER adding the dialog to the form if you
446 // want it to be centered.
447 dialog.style.marginTop = -(position.getHeight(dialog) / 2) + "px";
448 dialog.style.marginLeft = -(position.getWidth(dialog) / 2) + "px";
454 // Why is this in a zero-length timeout?
455 // Is it working around a browser bug?
456 top.setTimeout(function(){
460 var defTextLen = defaultInputText.length;
461 if (input.selectionStart !== undefined) {
462 input.selectionStart = 0;
463 input.selectionEnd = defTextLen;
465 else if (input.createTextRange) {
466 var range = input.createTextRange();
467 range.collapse(false);
468 range.moveStart("character", -defTextLen);
469 range.moveEnd("character", defTextLen);
479 // The assignment in the while loop makes jslint cranky.
480 // I'll change it to a better loop later.
481 position.getTop = function(elem, isInner){
482 var result = elem.offsetTop;
484 while (elem.offsetParent) {
485 elem = elem.offsetParent;
486 result += elem.offsetTop;
492 position.getHeight = function (elem) {
493 return elem.offsetHeight || elem.scrollHeight;
496 position.getWidth = function (elem) {
497 return elem.offsetWidth || elem.scrollWidth;
500 position.getPageSize = function(){
502 var scrollWidth, scrollHeight;
503 var innerWidth, innerHeight;
505 // It's not very clear which blocks work with which browsers.
506 if(self.innerHeight && self.scrollMaxY){
507 scrollWidth = doc.body.scrollWidth;
508 scrollHeight = self.innerHeight + self.scrollMaxY;
510 else if(doc.body.scrollHeight > doc.body.offsetHeight){
511 scrollWidth = doc.body.scrollWidth;
512 scrollHeight = doc.body.scrollHeight;
515 scrollWidth = doc.body.offsetWidth;
516 scrollHeight = doc.body.offsetHeight;
519 if(self.innerHeight){
521 innerWidth = self.innerWidth;
522 innerHeight = self.innerHeight;
524 else if(doc.documentElement && doc.documentElement.clientHeight){
525 // Some versions of IE (IE 6 w/ a DOCTYPE declaration)
526 innerWidth = doc.documentElement.clientWidth;
527 innerHeight = doc.documentElement.clientHeight;
530 // Other versions of IE
531 innerWidth = doc.body.clientWidth;
532 innerHeight = doc.body.clientHeight;
535 var maxWidth = Math.max(scrollWidth, innerWidth);
536 var maxHeight = Math.max(scrollHeight, innerHeight);
537 return [maxWidth, maxHeight, innerWidth, innerHeight];
540 // Watches the input textarea, polling at an interval and runs
541 // a callback function if anything has changed.
542 wmd.inputPoller = function(callback, interval){
544 var pollerObj = this;
545 var inputArea = wmd.panels.input;
547 // Stored start, end and text. Used to see if there are changes to the input.
552 var killHandle; // Used to cancel monitoring on destruction.
553 // Checks to see if anything has changed in the textarea.
554 // If so, it runs the callback.
555 this.tick = function(){
557 if (!util.isVisible(inputArea)) {
561 // Update the selection start and end, text.
562 if (inputArea.selectionStart || inputArea.selectionStart === 0) {
563 var start = inputArea.selectionStart;
564 var end = inputArea.selectionEnd;
565 if (start != lastStart || end != lastEnd) {
569 if (markdown != inputArea.value) {
570 markdown = inputArea.value;
579 var doTickCallback = function(){
581 if (!util.isVisible(inputArea)) {
585 // If anything has changed, call the function.
586 if (pollerObj.tick()) {
591 // Set how often we poll the textarea for changes.
592 var assignInterval = function(){
593 // previewPollInterval is set at the top of the namespace.
594 killHandle = top.setInterval(doTickCallback, interval);
597 this.destroy = function(){
598 top.clearInterval(killHandle);
604 // Handles pushing and popping TextareaStates for undo/redo commands.
605 // I should rename the stack variables to list.
606 wmd.undoManager = function(callback){
609 var undoStack = []; // A stack of undo states
610 var stackPtr = 0; // The index of the current state
612 var lastState; // The last state
614 var timer; // The setTimeout handle for cancelling the timer
617 // Set the mode for later logic steps.
618 var setMode = function(newMode, noSave){
620 if (mode != newMode) {
627 if (!global.isIE || mode != "moving") {
628 timer = top.setTimeout(refreshState, 1);
631 inputStateObj = null;
635 var refreshState = function(){
636 inputStateObj = new wmd.TextareaState();
641 this.setCommandMode = function(){
644 timer = top.setTimeout(refreshState, 0);
647 this.canUndo = function(){
651 this.canRedo = function(){
652 if (undoStack[stackPtr + 1]) {
658 // Removes the last state and restores it.
659 this.undo = function(){
661 if (undoObj.canUndo()) {
663 // What about setting state -1 to null or checking for undefined?
668 undoStack[stackPtr] = new wmd.TextareaState();
669 undoStack[--stackPtr].restore();
678 wmd.panels.input.focus();
683 this.redo = function(){
685 if (undoObj.canRedo()) {
687 undoStack[++stackPtr].restore();
695 wmd.panels.input.focus();
699 // Push the input area state to the stack.
700 var saveState = function(){
702 var currState = inputStateObj || new wmd.TextareaState();
707 if (mode == "moving") {
709 lastState = currState;
714 if (undoStack[stackPtr - 1].text != lastState.text) {
715 undoStack[stackPtr++] = lastState;
719 undoStack[stackPtr++] = currState;
720 undoStack[stackPtr + 1] = null;
726 var handleCtrlYZ = function(event){
730 if (event.ctrlKey || event.metaKey) {
732 // IE and Opera do not support charCode.
733 var keyCode = event.charCode || event.keyCode;
734 var keyCodeChar = String.fromCharCode(keyCode);
736 switch (keyCodeChar) {
744 if (!event.shiftKey) {
756 if (event.preventDefault) {
757 event.preventDefault();
760 top.event.returnValue = false;
766 // Set the mode depending on what is going on in the input area.
767 var handleModeChange = function(event){
769 if (!event.ctrlKey && !event.metaKey) {
771 var keyCode = event.keyCode;
773 if ((keyCode >= 33 && keyCode <= 40) || (keyCode >= 63232 && keyCode <= 63235)) {
774 // 33 - 40: page up/dn and arrow keys
775 // 63232 - 63235: page up/dn and arrow keys on safari
778 else if (keyCode == 8 || keyCode == 46 || keyCode == 127) {
784 else if (keyCode == 13) {
788 else if (keyCode == 27) {
792 else if ((keyCode < 16 || keyCode > 20) && keyCode != 91) {
793 // 16-20 are shift, etc.
794 // 91: left window key
795 // I think this might be a little messed up since there are
796 // a lot of nonprinting keys above 20.
802 var setEventHandlers = function(){
804 util.addEvent(wmd.panels.input, "keypress", function(event){
807 if ((event.ctrlKey || event.metaKey) && (event.keyCode == 89 || event.keyCode == 90)) {
808 event.preventDefault();
812 var handlePaste = function(){
813 if (global.isIE || (inputStateObj && inputStateObj.text != wmd.panels.input.value)) {
814 if (timer === undefined) {
822 // pastePollInterval is specified at the beginning of this namespace.
823 poller = new wmd.inputPoller(handlePaste, pastePollInterval);
825 util.addEvent(wmd.panels.input, "keydown", handleCtrlYZ);
826 util.addEvent(wmd.panels.input, "keydown", handleModeChange);
828 util.addEvent(wmd.panels.input, "mousedown", function(){
831 wmd.panels.input.onpaste = handlePaste;
832 wmd.panels.input.ondrop = handlePaste;
835 var init = function(){
841 this.destroy = function(){
850 // I think my understanding of how the buttons and callbacks are stored in the array is incomplete.
851 wmd.editor = function(previewRefreshCallback){
853 if (!previewRefreshCallback) {
854 previewRefreshCallback = function(){};
857 var inputBox = wmd.panels.input;
859 var offsetHeight = 0;
866 var div; // This name is pretty ambiguous. I should rename this.
868 // Used to cancel recurring events from setInterval.
871 var undoMgr; // The undo manager
873 // Perform the button's action.
874 var doClick = function(button){
881 undoMgr.setCommandMode();
884 var state = new wmd.TextareaState();
890 var chunks = state.getChunks();
892 // Some commands launch a "modal" prompt dialog. Javascript
893 // can't really make a modal dialog box and the WMD code
894 // will continue to execute while the dialog is displayed.
895 // This prevents the dialog pattern I'm used to and means
896 // I can't do something like this:
898 // var link = CreateLinkDialog();
899 // makeMarkdownLink(link);
901 // Instead of this straightforward method of handling a
902 // dialog I have to pass any code which would execute
903 // after the dialog is dismissed (e.g. link creation)
904 // in a function parameter.
906 // Yes this is awkward and I think it sucks, but there's
907 // no real workaround. Only the image and link code
908 // create dialogs and require the function pointers.
909 var fixupInputArea = function(){
914 state.setChunks(chunks);
918 previewRefreshCallback();
921 var noCleanup = button.textOp(chunks, fixupInputArea);
929 if (button.execute) {
930 button.execute(editObj);
934 var setUndoRedoButtonStates = function(){
936 setupButton(document.getElementById("wmd-undo-button"), undoMgr.canUndo());
937 setupButton(document.getElementById("wmd-redo-button"), undoMgr.canRedo());
941 var setupButton = function(button, isEnabled) {
943 var normalYShift = "0px";
944 var disabledYShift = "-20px";
945 var highlightYShift = "-40px";
948 button.style.backgroundPosition = button.XShift + " " + normalYShift;
949 button.onmouseover = function(){
950 this.style.backgroundPosition = this.XShift + " " + highlightYShift;
953 button.onmouseout = function(){
954 this.style.backgroundPosition = this.XShift + " " + normalYShift;
957 // IE tries to select the background image "button" text (it's
958 // implemented in a list item) so we have to cache the selection
961 button.onmousedown = function() {
962 wmd.ieRetardedClick = true;
963 wmd.ieCachedRange = document.selection.createRange();
969 button.onclick = function() {
970 if (this.onmouseout) {
979 button.style.backgroundPosition = button.XShift + " " + disabledYShift;
980 button.onmouseover = button.onmouseout = button.onclick = function(){};
984 var makeSpritedButtonRow = function(){
985 var buttonBar = document.getElementById("wmd-button-bar");
986 var normalYShift = "0px";
987 var disabledYShift = "-20px";
988 var highlightYShift = "-40px";
990 var buttonRow = document.createElement("ul");
991 buttonRow.id = "wmd-button-row";
992 buttonRow = buttonBar.appendChild(buttonRow);
995 var boldButton = document.createElement("li");
996 boldButton.className = "wmd-button";
997 boldButton.id = "wmd-bold-button";
998 boldButton.title = toolbar_strong_label;
999 boldButton.XShift = "0px";
1000 boldButton.textOp = command.doBold;
1001 setupButton(boldButton, true);
1002 buttonRow.appendChild(boldButton);
1004 var italicButton = document.createElement("li");
1005 italicButton.className = "wmd-button";
1006 italicButton.id = "wmd-italic-button";
1007 italicButton.title = toolbar_emphasis_label;
1008 italicButton.XShift = "-20px";
1009 italicButton.textOp = command.doItalic;
1010 setupButton(italicButton, true);
1011 buttonRow.appendChild(italicButton);
1013 var spacer1 = document.createElement("li");
1014 spacer1.className = "wmd-spacer";
1015 spacer1.id = "wmd-spacer1";
1016 buttonRow.appendChild(spacer1);
1018 var linkButton = document.createElement("li");
1019 linkButton.className = "wmd-button";
1020 linkButton.id = "wmd-link-button";
1021 linkButton.title = toolbar_hyperlink_label;
1022 linkButton.XShift = "-40px";
1023 linkButton.textOp = function(chunk, postProcessing){
1024 return command.doLinkOrImage(chunk, postProcessing, false);
1026 setupButton(linkButton, true);
1027 buttonRow.appendChild(linkButton);
1029 var quoteButton = document.createElement("li");
1030 quoteButton.className = "wmd-button";
1031 quoteButton.id = "wmd-quote-button";
1032 quoteButton.title = toolbar_blockquote_label;
1033 quoteButton.XShift = "-60px";
1034 quoteButton.textOp = command.doBlockquote;
1035 setupButton(quoteButton, true);
1036 buttonRow.appendChild(quoteButton);
1038 var codeButton = document.createElement("li");
1039 codeButton.className = "wmd-button";
1040 codeButton.id = "wmd-code-button";
1041 codeButton.title = toolbar_code_label;
1042 codeButton.XShift = "-80px";
1043 codeButton.textOp = command.doCode;
1044 setupButton(codeButton, true);
1045 buttonRow.appendChild(codeButton);
1047 var imageButton = document.createElement("li");
1048 imageButton.className = "wmd-button";
1049 imageButton.id = "wmd-image-button";
1050 imageButton.title = toolbar_image_label;
1051 imageButton.XShift = "-100px";
1052 imageButton.textOp = function(chunk, postProcessing){
1053 return command.doLinkOrImage(chunk, postProcessing, true);
1055 setupButton(imageButton, true);
1056 buttonRow.appendChild(imageButton);
1058 var spacer2 = document.createElement("li");
1059 spacer2.className = "wmd-spacer";
1060 spacer2.id = "wmd-spacer2";
1061 buttonRow.appendChild(spacer2);
1063 var olistButton = document.createElement("li");
1064 olistButton.className = "wmd-button";
1065 olistButton.id = "wmd-olist-button";
1066 olistButton.title = toolbar_numbered_label;
1067 olistButton.XShift = "-120px";
1068 olistButton.textOp = function(chunk, postProcessing){
1069 command.doList(chunk, postProcessing, true);
1071 setupButton(olistButton, true);
1072 buttonRow.appendChild(olistButton);
1074 var ulistButton = document.createElement("li");
1075 ulistButton.className = "wmd-button";
1076 ulistButton.id = "wmd-ulist-button";
1077 ulistButton.title = toolbar_bulleted_label;
1078 ulistButton.XShift = "-140px";
1079 ulistButton.textOp = function(chunk, postProcessing){
1080 command.doList(chunk, postProcessing, false);
1082 setupButton(ulistButton, true);
1083 buttonRow.appendChild(ulistButton);
1085 var headingButton = document.createElement("li");
1086 headingButton.className = "wmd-button";
1087 headingButton.id = "wmd-heading-button";
1088 headingButton.title = toolbar_heading_label;
1089 headingButton.XShift = "-160px";
1090 headingButton.textOp = command.doHeading;
1091 setupButton(headingButton, true);
1092 buttonRow.appendChild(headingButton);
1094 var hrButton = document.createElement("li");
1095 hrButton.className = "wmd-button";
1096 hrButton.id = "wmd-hr-button";
1097 hrButton.title = toolbar_horizontal_label;
1098 hrButton.XShift = "-180px";
1099 hrButton.textOp = command.doHorizontalRule;
1100 setupButton(hrButton, true);
1101 buttonRow.appendChild(hrButton);
1103 var spacer3 = document.createElement("li");
1104 spacer3.className = "wmd-spacer";
1105 spacer3.id = "wmd-spacer3";
1106 buttonRow.appendChild(spacer3);
1108 var undoButton = document.createElement("li");
1109 undoButton.className = "wmd-button";
1110 undoButton.id = "wmd-undo-button";
1111 undoButton.title = toolbar_undo_label;
1112 undoButton.XShift = "-200px";
1113 undoButton.execute = function(manager){
1116 setupButton(undoButton, true);
1117 buttonRow.appendChild(undoButton);
1119 var redoButton = document.createElement("li");
1120 redoButton.className = "wmd-button";
1121 redoButton.id = "wmd-redo-button";
1122 redoButton.title = toolbar_redo_label;
1123 if (/win/.test(nav.platform.toLowerCase())) {
1124 redoButton.title = toolbar_redo_label;
1127 // mac and other non-Windows platforms
1128 redoButton.title = $.i18n._('redo') + " - Ctrl+Shift+Z";
1130 redoButton.XShift = "-220px";
1131 redoButton.execute = function(manager){
1134 setupButton(redoButton, true);
1135 buttonRow.appendChild(redoButton);
1137 var helpButton = document.createElement("li");
1138 helpButton.className = "wmd-button";
1139 helpButton.id = "wmd-help-button";
1140 helpButton.XShift = "-240px";
1141 helpButton.isHelp = true;
1143 var helpAnchor = document.createElement("a");
1144 helpAnchor.href = helpLink;
1145 helpAnchor.target = helpTarget
1146 helpAnchor.title = helpHoverTitle;
1147 helpButton.appendChild(helpAnchor);
1149 setupButton(helpButton, true);
1150 buttonRow.appendChild(helpButton);
1152 setUndoRedoButtonStates();
1155 var setupEditor = function(){
1157 if (/\?noundo/.test(doc.location.href)) {
1158 wmd.nativeUndo = true;
1161 if (!wmd.nativeUndo) {
1162 undoMgr = new wmd.undoManager(function(){
1163 previewRefreshCallback();
1164 setUndoRedoButtonStates();
1168 makeSpritedButtonRow();
1171 var keyEvent = "keydown";
1172 if (global.isOpera) {
1173 keyEvent = "keypress";
1176 util.addEvent(inputBox, keyEvent, function(key){
1178 // Check to see if we have a button key and, if so execute the callback.
1179 if (key.ctrlKey || key.metaKey) {
1181 var keyCode = key.charCode || key.keyCode;
1182 var keyCodeStr = String.fromCharCode(keyCode).toLowerCase();
1184 // Bugfix for messed up DEL and .
1185 if (keyCode === 46) {
1188 if (keyCode === 190) {
1192 switch(keyCodeStr) {
1194 doClick(document.getElementById("wmd-bold-button"));
1197 doClick(document.getElementById("wmd-italic-button"));
1200 doClick(document.getElementById("wmd-link-button"));
1203 doClick(document.getElementById("wmd-quote-button"));
1206 doClick(document.getElementById("wmd-code-button"));
1209 doClick(document.getElementById("wmd-image-button"));
1212 doClick(document.getElementById("wmd-olist-button"));
1215 doClick(document.getElementById("wmd-ulist-button"));
1218 doClick(document.getElementById("wmd-heading-button"));
1221 doClick(document.getElementById("wmd-hr-button"));
1224 doClick(document.getElementById("wmd-redo-button"));
1228 doClick(document.getElementById("wmd-redo-button"));
1231 doClick(document.getElementById("wmd-undo-button"));
1239 if (key.preventDefault) {
1240 key.preventDefault();
1244 top.event.returnValue = false;
1249 // Auto-indent on shift-enter
1250 util.addEvent(inputBox, "keyup", function(key){
1251 if (key.shiftKey && !key.ctrlKey && !key.metaKey) {
1252 var keyCode = key.charCode || key.keyCode;
1253 // Character 13 is Enter
1254 if (keyCode === 13) {
1256 fakeButton.textOp = command.doAutoindent;
1257 doClick(fakeButton);
1262 if (inputBox.form) {
1263 var submitCallback = inputBox.form.onsubmit;
1264 inputBox.form.onsubmit = function(){
1266 if (submitCallback) {
1267 return submitCallback.apply(this, arguments);
1273 // Convert the contents of the input textarea to HTML in the output/preview panels.
1274 var convertToHtml = function(){
1277 var markdownConverter = new wmd.showdown.converter();
1279 var text = inputBox.value;
1281 var callback = function(){
1282 inputBox.value = text;
1285 if (!/markdown/.test(wmd.wmd_env.output.toLowerCase())) {
1286 if (markdownConverter) {
1287 inputBox.value = markdownConverter.makeHtml(text);
1288 top.setTimeout(callback, 0);
1295 this.undo = function(){
1301 this.redo = function(){
1307 // This is pretty useless. The setupEditor function contents
1308 // should just be copied here.
1309 var init = function(){
1313 this.destroy = function(){
1317 if (div.parentNode) {
1318 div.parentNode.removeChild(div);
1321 inputBox.style.marginTop = "";
1323 top.clearInterval(creationHandle);
1329 // The input textarea state/contents.
1330 // This is used to implement undo/redo by the undo manager.
1331 wmd.TextareaState = function(){
1334 var stateObj = this;
1335 var inputArea = wmd.panels.input;
1337 this.init = function() {
1339 if (!util.isVisible(inputArea)) {
1343 this.setInputAreaSelectionStartEnd();
1344 this.scrollTop = inputArea.scrollTop;
1345 if (!this.text && inputArea.selectionStart || inputArea.selectionStart === 0) {
1346 this.text = inputArea.value;
1351 // Sets the selected text in the input box after we've performed an
1353 this.setInputAreaSelection = function(){
1355 if (!util.isVisible(inputArea)) {
1359 if (inputArea.selectionStart !== undefined && !global.isOpera) {
1362 inputArea.selectionStart = stateObj.start;
1363 inputArea.selectionEnd = stateObj.end;
1364 inputArea.scrollTop = stateObj.scrollTop;
1366 else if (doc.selection) {
1368 if (doc.activeElement && doc.activeElement !== inputArea) {
1373 var range = inputArea.createTextRange();
1374 range.moveStart("character", -inputArea.value.length);
1375 range.moveEnd("character", -inputArea.value.length);
1376 range.moveEnd("character", stateObj.end);
1377 range.moveStart("character", stateObj.start);
1382 this.setInputAreaSelectionStartEnd = function(){
1384 if (inputArea.selectionStart || inputArea.selectionStart === 0) {
1386 stateObj.start = inputArea.selectionStart;
1387 stateObj.end = inputArea.selectionEnd;
1389 else if (doc.selection) {
1391 stateObj.text = util.fixEolChars(inputArea.value);
1393 // IE loses the selection in the textarea when buttons are
1394 // clicked. On IE we cache the selection and set a flag
1395 // which we check for here.
1397 if(wmd.ieRetardedClick && wmd.ieCachedRange) {
1398 range = wmd.ieCachedRange;
1399 wmd.ieRetardedClick = false;
1402 range = doc.selection.createRange();
1405 var fixedRange = util.fixEolChars(range.text);
1406 var marker = "\x07";
1407 var markedRange = marker + fixedRange + marker;
1408 range.text = markedRange;
1409 var inputText = util.fixEolChars(inputArea.value);
1411 range.moveStart("character", -markedRange.length);
1412 range.text = fixedRange;
1414 stateObj.start = inputText.indexOf(marker);
1415 stateObj.end = inputText.lastIndexOf(marker) - marker.length;
1417 var len = stateObj.text.length - util.fixEolChars(inputArea.value).length;
1420 range.moveStart("character", -fixedRange.length);
1425 range.text = fixedRange;
1428 this.setInputAreaSelection();
1432 // Restore this state into the input area.
1433 this.restore = function(){
1435 if (stateObj.text !== undefined && stateObj.text != inputArea.value) {
1436 inputArea.value = stateObj.text;
1438 this.setInputAreaSelection();
1439 inputArea.scrollTop = stateObj.scrollTop;
1442 // Gets a collection of HTML chunks from the inptut textarea.
1443 this.getChunks = function(){
1445 var chunk = new wmd.Chunks();
1447 chunk.before = util.fixEolChars(stateObj.text.substring(0, stateObj.start));
1448 chunk.startTag = "";
1449 chunk.selection = util.fixEolChars(stateObj.text.substring(stateObj.start, stateObj.end));
1451 chunk.after = util.fixEolChars(stateObj.text.substring(stateObj.end));
1452 chunk.scrollTop = stateObj.scrollTop;
1457 // Sets the TextareaState properties given a chunk of markdown.
1458 this.setChunks = function(chunk){
1460 chunk.before = chunk.before + chunk.startTag;
1461 chunk.after = chunk.endTag + chunk.after;
1463 if (global.isOpera) {
1464 chunk.before = chunk.before.replace(/\n/g, "\r\n");
1465 chunk.selection = chunk.selection.replace(/\n/g, "\r\n");
1466 chunk.after = chunk.after.replace(/\n/g, "\r\n");
1469 this.start = chunk.before.length;
1470 this.end = chunk.before.length + chunk.selection.length;
1471 this.text = chunk.before + chunk.selection + chunk.after;
1472 this.scrollTop = chunk.scrollTop;
1478 // before: contains all the text in the input box BEFORE the selection.
1479 // after: contains all the text in the input box AFTER the selection.
1480 wmd.Chunks = function(){
1483 // startRegex: a regular expression to find the start tag
1484 // endRegex: a regular expresssion to find the end tag
1485 wmd.Chunks.prototype.findTags = function(startRegex, endRegex){
1487 var chunkObj = this;
1492 regex = util.extendRegExp(startRegex, "", "$");
1494 this.before = this.before.replace(regex,
1496 chunkObj.startTag = chunkObj.startTag + match;
1500 regex = util.extendRegExp(startRegex, "^", "");
1502 this.selection = this.selection.replace(regex,
1504 chunkObj.startTag = chunkObj.startTag + match;
1511 regex = util.extendRegExp(endRegex, "", "$");
1513 this.selection = this.selection.replace(regex,
1515 chunkObj.endTag = match + chunkObj.endTag;
1519 regex = util.extendRegExp(endRegex, "^", "");
1521 this.after = this.after.replace(regex,
1523 chunkObj.endTag = match + chunkObj.endTag;
1529 // If remove is false, the whitespace is transferred
1530 // to the before/after regions.
1532 // If remove is true, the whitespace disappears.
1533 wmd.Chunks.prototype.trimWhitespace = function(remove){
1535 this.selection = this.selection.replace(/^(\s*)/, "");
1538 this.before += re.$1;
1541 this.selection = this.selection.replace(/(\s*)$/, "");
1544 this.after = re.$1 + this.after;
1549 wmd.Chunks.prototype.skipLines = function(nLinesBefore, nLinesAfter, findExtraNewlines){
1551 if (nLinesBefore === undefined) {
1555 if (nLinesAfter === undefined) {
1563 var replacementText;
1565 this.selection = this.selection.replace(/(^\n*)/, "");
1566 this.startTag = this.startTag + re.$1;
1567 this.selection = this.selection.replace(/(\n*$)/, "");
1568 this.endTag = this.endTag + re.$1;
1569 this.startTag = this.startTag.replace(/(^\n*)/, "");
1570 this.before = this.before + re.$1;
1571 this.endTag = this.endTag.replace(/(\n*$)/, "");
1572 this.after = this.after + re.$1;
1576 regexText = replacementText = "";
1578 while (nLinesBefore--) {
1579 regexText += "\\n?";
1580 replacementText += "\n";
1583 if (findExtraNewlines) {
1586 this.before = this.before.replace(new re(regexText + "$", ""), replacementText);
1591 regexText = replacementText = "";
1593 while (nLinesAfter--) {
1594 regexText += "\\n?";
1595 replacementText += "\n";
1597 if (findExtraNewlines) {
1601 this.after = this.after.replace(new re(regexText, ""), replacementText);
1605 // The markdown symbols - 4 spaces = code, > = blockquote, etc.
1606 command.prefixes = "(?:\\s{4,}|\\s*>|\\s*-\\s+|\\s*\\d+\\.|=|\\+|-|_|\\*|#|\\s*\\[[^\n]]+\\]:)";
1608 // Remove markdown symbols from the chunk selection.
1609 command.unwrap = function(chunk){
1610 var txt = new re("([^\\n])\\n(?!(\\n|" + command.prefixes + "))", "g");
1611 chunk.selection = chunk.selection.replace(txt, "$1 $2");
1614 command.wrap = function(chunk, len){
1615 command.unwrap(chunk);
1616 var regex = new re("(.{1," + len + "})( +|$\\n?)", "gm");
1618 chunk.selection = chunk.selection.replace(regex, function(line, marked){
1619 if (new re("^" + command.prefixes, "").test(line)) {
1622 return marked + "\n";
1625 chunk.selection = chunk.selection.replace(/\s+$/, "");
1628 command.doBold = function(chunk, postProcessing){
1629 return command.doBorI(chunk, postProcessing, 2, "strong text");
1632 command.doItalic = function(chunk, postProcessing){
1633 return command.doBorI(chunk, postProcessing, 1, "emphasized text");
1636 // chunk: The selected region that will be enclosed with */**
1637 // nStars: 1 for italics, 2 for bold
1638 // insertText: If you just click the button without highlighting text, this gets inserted
1639 command.doBorI = function(chunk, postProcessing, nStars, insertText){
1641 // Get rid of whitespace and fixup newlines.
1642 chunk.trimWhitespace();
1643 chunk.selection = chunk.selection.replace(/\n{2,}/g, "\n");
1645 // Look for stars before and after. Is the chunk already marked up?
1646 chunk.before.search(/(\**$)/);
1647 var starsBefore = re.$1;
1649 chunk.after.search(/(^\**)/);
1650 var starsAfter = re.$1;
1652 var prevStars = Math.min(starsBefore.length, starsAfter.length);
1654 // Remove stars if we have to since the button acts as a toggle.
1655 if ((prevStars >= nStars) && (prevStars != 2 || nStars != 1)) {
1656 chunk.before = chunk.before.replace(re("[*]{" + nStars + "}$", ""), "");
1657 chunk.after = chunk.after.replace(re("^[*]{" + nStars + "}", ""), "");
1659 else if (!chunk.selection && starsAfter) {
1660 // It's not really clear why this code is necessary. It just moves
1661 // some arbitrary stuff around.
1662 chunk.after = chunk.after.replace(/^([*_]*)/, "");
1663 chunk.before = chunk.before.replace(/(\s?)$/, "");
1664 var whitespace = re.$1;
1665 chunk.before = chunk.before + starsAfter + whitespace;
1669 // In most cases, if you don't have any selected text and click the button
1670 // you'll get a selected, marked up region with the default text inserted.
1671 if (!chunk.selection && !starsAfter) {
1672 chunk.selection = insertText;
1675 // Add the true markup.
1676 var markup = nStars <= 1 ? "*" : "**"; // shouldn't the test be = ?
1677 chunk.before = chunk.before + markup;
1678 chunk.after = markup + chunk.after;
1684 command.stripLinkDefs = function(text, defsToAdd){
1686 text = text.replace(/^[ ]{0,3}\[(\d+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+|$)/gm,
1687 function(totalMatch, id, link, newlines, title){
1688 defsToAdd[id] = totalMatch.replace(/\s*$/, "");
1690 // Strip the title and return that separately.
1691 defsToAdd[id] = totalMatch.replace(/["(](.+?)[")]$/, "");
1692 return newlines + title;
1700 command.addLinkDef = function(chunk, linkDef){
1702 var refNumber = 0; // The current reference number
1703 var defsToAdd = {}; //
1704 // Start with a clean slate by removing all previous link definitions.
1705 chunk.before = command.stripLinkDefs(chunk.before, defsToAdd);
1706 chunk.selection = command.stripLinkDefs(chunk.selection, defsToAdd);
1707 chunk.after = command.stripLinkDefs(chunk.after, defsToAdd);
1710 var regex = /(\[(?:\[[^\]]*\]|[^\[\]])*\][ ]?(?:\n[ ]*)?\[)(\d+)(\])/g;
1712 var addDefNumber = function(def){
1714 def = def.replace(/^[ ]{0,3}\[(\d+)\]:/, " [" + refNumber + "]:");
1718 var getLink = function(wholeMatch, link, id, end){
1720 if (defsToAdd[id]) {
1721 addDefNumber(defsToAdd[id]);
1722 return link + refNumber + end;
1728 chunk.before = chunk.before.replace(regex, getLink);
1731 addDefNumber(linkDef);
1734 chunk.selection = chunk.selection.replace(regex, getLink);
1737 var refOut = refNumber;
1739 chunk.after = chunk.after.replace(regex, getLink);
1742 chunk.after = chunk.after.replace(/\n*$/, "");
1745 chunk.selection = chunk.selection.replace(/\n*$/, "");
1748 chunk.after += "\n\n" + defs;
1753 command.doLinkOrImage = function(chunk, postProcessing, isImage){
1755 chunk.trimWhitespace();
1756 chunk.findTags(/\s*!?\[/, /\][ ]?(?:\n[ ]*)?(\[.*?\])?/);
1758 if (chunk.endTag.length > 1) {
1760 chunk.startTag = chunk.startTag.replace(/!?\[/, "");
1762 command.addLinkDef(chunk, null);
1767 if (/\n\n/.test(chunk.selection)) {
1768 command.addLinkDef(chunk, null);
1772 // The function to be executed when you enter a link and press OK or Cancel.
1773 // Marks up the link and adds the ref.
1774 var makeLinkMarkdown = function(link){
1776 if (link !== null) {
1778 chunk.startTag = chunk.endTag = "";
1779 var linkDef = " [999]: " + link;
1781 var num = command.addLinkDef(chunk, linkDef);
1782 chunk.startTag = isImage ? "![" : "[";
1783 chunk.endTag = "][" + num + "]";
1785 if (!chunk.selection) {
1787 chunk.selection = "alt text";
1790 chunk.selection = "link text";
1798 // add forth param to identify image window
1799 util.prompt(imageDialogText, imageDefaultText, makeLinkMarkdown, 1);
1802 util.prompt(linkDialogText, linkDefaultText, makeLinkMarkdown);
1808 util.makeAPI = function(){
1810 wmd.wmd.editor = wmd.editor;
1811 wmd.wmd.previewManager = wmd.previewManager;
1814 util.startEditor = function(){
1816 if (wmd.wmd_env.autostart === false) {
1821 var edit; // The editor (buttons + input + outputs) - the main object.
1822 var previewMgr; // The preview manager.
1824 // Fired after the page has fully loaded.
1825 var loadListener = function(){
1827 wmd.panels = new wmd.PanelCollection();
1829 previewMgr = new wmd.previewManager();
1830 var previewRefreshCallback = previewMgr.refresh;
1832 edit = new wmd.editor(previewRefreshCallback);
1834 previewMgr.refresh(true);
1838 util.addEvent(top, "load", loadListener);
1841 wmd.previewManager = function(){
1843 var managerObj = this;
1850 var maxDelay = 3000;
1851 var startType = "delayed"; // The other legal value is "manual"
1853 // Adds event listeners to elements and creates the input poller.
1854 var setupEvents = function(inputElem, listener){
1856 util.addEvent(inputElem, "input", listener);
1857 inputElem.onpaste = listener;
1858 inputElem.ondrop = listener;
1860 util.addEvent(inputElem, "keypress", listener);
1861 util.addEvent(inputElem, "keydown", listener);
1862 // previewPollInterval is set at the top of this file.
1863 poller = new wmd.inputPoller(listener, previewPollInterval);
1866 var getDocScrollTop = function(){
1870 if (top.innerHeight) {
1871 result = top.pageYOffset;
1874 if (doc.documentElement && doc.documentElement.scrollTop) {
1875 result = doc.documentElement.scrollTop;
1879 result = doc.body.scrollTop;
1885 var makePreviewHtml = function(){
1887 // If there are no registered preview and output panels
1888 // there is nothing to do.
1889 if (!wmd.panels.preview && !wmd.panels.output) {
1893 var text = wmd.panels.input.value;
1894 if (text && text == oldInputText) {
1895 return; // Input text hasn't changed.
1898 oldInputText = text;
1901 var prevTime = new Date().getTime();
1903 if (!converter && wmd.showdown) {
1904 converter = new wmd.showdown.converter();
1908 text = converter.makeHtml(text);
1911 // Calculate the processing time of the HTML creation.
1912 // It's used as the delay time in the event listener.
1913 var currTime = new Date().getTime();
1914 elapsedTime = currTime - prevTime;
1916 pushPreviewHtml(text);
1920 // setTimeout is already used. Used as an event listener.
1921 var applyTimeout = function(){
1924 top.clearTimeout(timeout);
1925 timeout = undefined;
1928 if (startType !== "manual") {
1932 if (startType === "delayed") {
1933 delay = elapsedTime;
1936 if (delay > maxDelay) {
1939 timeout = top.setTimeout(makePreviewHtml, delay);
1943 var getScaleFactor = function(panel){
1944 if (panel.scrollHeight <= panel.clientHeight) {
1947 return panel.scrollTop / (panel.scrollHeight - panel.clientHeight);
1950 var setPanelScrollTops = function(){
1952 if (wmd.panels.preview) {
1953 wmd.panels.preview.scrollTop = (wmd.panels.preview.scrollHeight - wmd.panels.preview.clientHeight) * getScaleFactor(wmd.panels.preview);
1956 if (wmd.panels.output) {
1957 wmd.panels.output.scrollTop = (wmd.panels.output.scrollHeight - wmd.panels.output.clientHeight) * getScaleFactor(wmd.panels.output);
1961 this.refresh = function(requiresRefresh){
1963 if (requiresRefresh) {
1972 this.processingTime = function(){
1977 this.output = function(){
1981 // The mode can be "manual" or "delayed"
1982 this.setUpdateMode = function(mode){
1984 managerObj.refresh();
1987 var isFirstTimeFilled = true;
1989 var pushPreviewHtml = function(text){
1991 var emptyTop = position.getTop(wmd.panels.input) - getDocScrollTop();
1993 // Send the encoded HTML to the output textarea/div.
1994 if (wmd.panels.output) {
1995 // The value property is only defined if the output is a textarea.
1996 if (wmd.panels.output.value !== undefined) {
1997 wmd.panels.output.value = text;
1998 wmd.panels.output.readOnly = true;
2000 // Otherwise we are just replacing the text in a div.
2001 // Send the HTML wrapped in <pre><code>
2003 var newText = text.replace(/&/g, "&");
2004 newText = newText.replace(/</g, "<");
2005 wmd.panels.output.innerHTML = "<pre><code>" + newText + "</code></pre>";
2009 if (wmd.panels.preview) {
2010 wmd.panels.preview.innerHTML = text;
2013 setPanelScrollTops();
2015 if (isFirstTimeFilled) {
2016 isFirstTimeFilled = false;
2020 var fullTop = position.getTop(wmd.panels.input) - getDocScrollTop();
2023 top.setTimeout(function(){
2024 top.scrollBy(0, fullTop - emptyTop);
2028 top.scrollBy(0, fullTop - emptyTop);
2032 var init = function(){
2034 setupEvents(wmd.panels.input, applyTimeout);
2037 if (wmd.panels.preview) {
2038 wmd.panels.preview.scrollTop = 0;
2040 if (wmd.panels.output) {
2041 wmd.panels.output.scrollTop = 0;
2045 this.destroy = function(){
2054 // When making a list, hitting shift-enter will put your cursor on the next line
2055 // at the current indent level.
2056 command.doAutoindent = function(chunk, postProcessing){
2058 chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]*\n$/, "\n\n");
2059 chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}>[ \t]*\n$/, "\n\n");
2060 chunk.before = chunk.before.replace(/(\n|^)[ \t]+\n$/, "\n\n");
2062 if(/(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]+.*\n$/.test(chunk.before)){
2064 command.doList(chunk);
2067 if(/(\n|^)[ ]{0,3}>[ \t]+.*\n$/.test(chunk.before)){
2068 if(command.doBlockquote){
2069 command.doBlockquote(chunk);
2072 if(/(\n|^)(\t|[ ]{4,}).*\n$/.test(chunk.before)){
2074 command.doCode(chunk);
2079 command.doBlockquote = function(chunk, postProcessing){
2081 chunk.selection = chunk.selection.replace(/^(\n*)([^\r]+?)(\n*)$/,
2082 function(totalMatch, newlinesBefore, text, newlinesAfter){
2083 chunk.before += newlinesBefore;
2084 chunk.after = newlinesAfter + chunk.after;
2088 chunk.before = chunk.before.replace(/(>[ \t]*)$/,
2089 function(totalMatch, blankLine){
2090 chunk.selection = blankLine + chunk.selection;
2094 chunk.selection = chunk.selection.replace(/^(\s|>)+$/ ,"");
2095 chunk.selection = chunk.selection || "Blockquote";
2098 chunk.before = chunk.before.replace(/\n?$/,"\n");
2101 chunk.after = chunk.after.replace(/^\n?/,"\n");
2104 chunk.before = chunk.before.replace(/(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*$)/,
2105 function(totalMatch){
2106 chunk.startTag = totalMatch;
2110 chunk.after = chunk.after.replace(/^(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*)/,
2111 function(totalMatch){
2112 chunk.endTag = totalMatch;
2116 var replaceBlanksInTags = function(useBracket){
2118 var replacement = useBracket ? "> " : "";
2121 chunk.startTag = chunk.startTag.replace(/\n((>|\s)*)\n$/,
2122 function(totalMatch, markdown){
2123 return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n";
2127 chunk.endTag = chunk.endTag.replace(/^\n((>|\s)*)\n/,
2128 function(totalMatch, markdown){
2129 return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n";
2134 if(/^(?![ ]{0,3}>)/m.test(chunk.selection)){
2135 command.wrap(chunk, wmd.wmd_env.lineLength - 2);
2136 chunk.selection = chunk.selection.replace(/^/gm, "> ");
2137 replaceBlanksInTags(true);
2141 chunk.selection = chunk.selection.replace(/^[ ]{0,3}> ?/gm, "");
2142 command.unwrap(chunk);
2143 replaceBlanksInTags(false);
2145 if(!/^(\n|^)[ ]{0,3}>/.test(chunk.selection) && chunk.startTag){
2146 chunk.startTag = chunk.startTag.replace(/\n{0,2}$/, "\n\n");
2149 if(!/(\n|^)[ ]{0,3}>.*$/.test(chunk.selection) && chunk.endTag){
2150 chunk.endTag=chunk.endTag.replace(/^\n{0,2}/, "\n\n");
2154 if(!/\n/.test(chunk.selection)){
2155 chunk.selection = chunk.selection.replace(/^(> *)/,
2156 function(wholeMatch, blanks){
2157 chunk.startTag += blanks;
2163 command.doCode = function(chunk, postProcessing){
2165 var hasTextBefore = /\S[ ]*$/.test(chunk.before);
2166 var hasTextAfter = /^[ ]*\S/.test(chunk.after);
2168 // Use 'four space' markdown if the selection is on its own
2169 // line or is multiline.
2170 if((!hasTextAfter && !hasTextBefore) || /\n/.test(chunk.selection)){
2172 chunk.before = chunk.before.replace(/[ ]{4}$/,
2173 function(totalMatch){
2174 chunk.selection = totalMatch + chunk.selection;
2179 var nLinesForward = 1;
2181 if(/\n(\t|[ ]{4,}).*\n$/.test(chunk.before)){
2184 if(/^\n(\t|[ ]{4,})/.test(chunk.after)){
2188 chunk.skipLines(nLinesBack, nLinesForward);
2190 if(!chunk.selection){
2191 chunk.startTag = " ";
2192 chunk.selection = "enter code here";
2195 if(/^[ ]{0,3}\S/m.test(chunk.selection)){
2196 chunk.selection = chunk.selection.replace(/^/gm, " ");
2199 chunk.selection = chunk.selection.replace(/^[ ]{4}/gm, "");
2204 // Use backticks (`) to delimit the code block.
2206 chunk.trimWhitespace();
2207 chunk.findTags(/`/, /`/);
2209 if(!chunk.startTag && !chunk.endTag){
2210 chunk.startTag = chunk.endTag="`";
2211 if(!chunk.selection){
2212 chunk.selection = "enter code here";
2215 else if(chunk.endTag && !chunk.startTag){
2216 chunk.before += chunk.endTag;
2220 chunk.startTag = chunk.endTag="";
2225 command.doList = function(chunk, postProcessing, isNumberedList){
2227 // These are identical except at the very beginning and end.
2228 // Should probably use the regex extension function to make this clearer.
2229 var previousItemsRegex = /(\n|^)(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*$/;
2230 var nextItemsRegex = /^\n*(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*/;
2232 // The default bullet is a dash but others are possible.
2233 // This has nothing to do with the particular HTML bullet,
2234 // it's just a markdown bullet.
2237 // The number in a numbered list.
2240 // Get the item prefix - e.g. " 1. " for a numbered list, " - " for a bulleted list.
2241 var getItemPrefix = function(){
2244 prefix = " " + num + ". ";
2248 prefix = " " + bullet + " ";
2253 // Fixes the prefixes of the other list items.
2254 var getPrefixedItem = function(itemText){
2256 // The numbering flag is unset when called by autoindent.
2257 if(isNumberedList === undefined){
2258 isNumberedList = /^\s*\d/.test(itemText);
2261 // Renumber/bullet the list element.
2262 itemText = itemText.replace(/^[ ]{0,3}([*+-]|\d+[.])\s/gm,
2264 return getItemPrefix();
2270 chunk.findTags(/(\n|^)*[ ]{0,3}([*+-]|\d+[.])\s+/, null);
2272 if(chunk.before && !/\n$/.test(chunk.before) && !/^\n/.test(chunk.startTag)){
2273 chunk.before += chunk.startTag;
2274 chunk.startTag = "";
2279 var hasDigits = /\d+[.]/.test(chunk.startTag);
2280 chunk.startTag = "";
2281 chunk.selection = chunk.selection.replace(/\n[ ]{4}/g, "\n");
2282 command.unwrap(chunk);
2286 // Have to renumber the bullet points if this is a numbered list.
2287 chunk.after = chunk.after.replace(nextItemsRegex, getPrefixedItem);
2289 if(isNumberedList == hasDigits){
2296 chunk.before = chunk.before.replace(previousItemsRegex,
2298 if(/^\s*([*+-])/.test(itemText)){
2301 nLinesUp = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0;
2302 return getPrefixedItem(itemText);
2305 if(!chunk.selection){
2306 chunk.selection = "List item";
2309 var prefix = getItemPrefix();
2313 chunk.after = chunk.after.replace(nextItemsRegex,
2315 nLinesDown = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0;
2316 return getPrefixedItem(itemText);
2319 chunk.trimWhitespace(true);
2320 chunk.skipLines(nLinesUp, nLinesDown, true);
2321 chunk.startTag = prefix;
2322 var spaces = prefix.replace(/./g, " ");
2323 command.wrap(chunk, wmd.wmd_env.lineLength - spaces.length);
2324 chunk.selection = chunk.selection.replace(/\n/g, "\n" + spaces);
2328 command.doHeading = function(chunk, postProcessing){
2330 // Remove leading/trailing whitespace and reduce internal spaces to single spaces.
2331 chunk.selection = chunk.selection.replace(/\s+/g, " ");
2332 chunk.selection = chunk.selection.replace(/(^\s+|\s+$)/g, "");
2334 // If we clicked the button with no selected text, we just
2335 // make a level 2 hash header around some default text.
2336 if(!chunk.selection){
2337 chunk.startTag = "## ";
2338 chunk.selection = "Heading";
2339 chunk.endTag = " ##";
2343 var headerLevel = 0; // The existing header level of the selected text.
2345 // Remove any existing hash heading markdown and save the header level.
2346 chunk.findTags(/#+[ ]*/, /[ ]*#+/);
2347 if(/#+/.test(chunk.startTag)){
2348 headerLevel = re.lastMatch.length;
2350 chunk.startTag = chunk.endTag = "";
2352 // Try to get the current header level by looking for - and = in the line
2353 // below the selection.
2354 chunk.findTags(null, /\s?(-+|=+)/);
2355 if(/=+/.test(chunk.endTag)){
2358 if(/-+/.test(chunk.endTag)){
2362 // Skip to the next line so we can create the header markdown.
2363 chunk.startTag = chunk.endTag = "";
2364 chunk.skipLines(1, 1);
2366 // We make a level 2 header if there is no current header.
2367 // If there is a header level, we substract one from the header level.
2368 // If it's already a level 1 header, it's removed.
2369 var headerLevelToCreate = headerLevel == 0 ? 2 : headerLevel - 1;
2371 if(headerLevelToCreate > 0){
2373 // The button only creates level 1 and 2 underline headers.
2374 // Why not have it iterate over hash header levels? Wouldn't that be easier and cleaner?
2375 var headerChar = headerLevelToCreate >= 2 ? "-" : "=";
2376 var len = chunk.selection.length;
2377 if(len > wmd.wmd_env.lineLength){
2378 len = wmd.wmd_env.lineLength;
2380 chunk.endTag = "\n";
2382 chunk.endTag += headerChar;
2387 command.doHorizontalRule = function(chunk, postProcessing){
2388 chunk.startTag = "----------\n";
2389 chunk.selection = "";
2390 chunk.skipLines(2, 1, true);
2395 Attacklab.wmd_env = {};
2396 Attacklab.account_options = {};
2397 Attacklab.wmd_defaults = {version:1, output:"Markdown", lineLength:40, delayLoad:false};
2401 Attacklab.wmd = function()
2403 Attacklab.loadEnv = function()
2405 var mergeEnv = function(env)
2414 Attacklab.wmd_env[key] = env[key];
2418 mergeEnv(Attacklab.wmd_defaults);
2419 mergeEnv(Attacklab.account_options);
2420 mergeEnv(top["wmd_options"]);
2421 Attacklab.full = true;
2423 var defaultButtons = "bold italic link blockquote code image ol ul heading hr";
2424 Attacklab.wmd_env.buttons = Attacklab.wmd_env.buttons || defaultButtons;
2426 Attacklab.loadEnv();
2431 Attacklab.wmdBase();
2432 Attacklab.Util.startEditor();