/*
 * XenForo bb_code_edit.min.js
 * Copyright 2010-2015 XenForo Ltd.
 * Released under the XenForo License Agreement: http://xenforo.com/license-agreement
 */
(function(d,j,l){XenForo.BbCodeWysiwygEditor=function(b){this.__construct(b)};XenForo.BbCodeWysiwygEditor.prototype={__construct:function(b){this.$textarea=b;this.options=b.data("options")||{};this.dialogUrl=b.data("dialog-url")?XenForo.canonicalizeUrl(b.data("dialog-url"),XenForo.ajaxBaseHref):"index.php?editor/dialog";this.autoSaveUrl=b.data("auto-save-url");this.autoCompleteUrl=b.data("ac-url")||XenForo.AutoComplete.getDefaultUrl();this.pasteImageCounter=1;var c=b.attr("id");if(c&&(c=XenForo.BbCodeWysiwygEditor_EXTEND[c]))this.options=
typeof c=="function"?c(this.options,this):d.extend(this.options,c);var c=this._adjustButtonConfig(this.getButtonConfig(),this.options.buttons||{}),a=this.getExecHandlers(),e=b.data("css-url");this.editorConfig=d.extend({direction:d("html").attr("dir")||"ltr",formattingTags:[],source:!1,iframe:!0,iframeBase:XenForo.baseUrl(),lang:"xf",buttons:c.buttons,css:e?XenForo.canonicalizeUrl(e,XenForo.ajaxBaseHref):!1,buttonsCustom:c.buttonsCustom,execCommandHandler:a,modal_link:{url:this.dialogUrl+"&dialog=link"},
modal_image:{url:this.dialogUrl+"&dialog=image"},observeImages:!1,allowJustify:!1,cleanupFontTags:!1,convertLinks:!1,modalCreateCallback:d.context(this,"modalCreateCallback"),callback:d.context(this,"editorInit"),pastePreventCallback:d.context(this,"pastePreventCallback"),pasteManipulateCallback:d.context(this,"pasteManipulateCallback"),pasteCleanUpCallback:d.context(this,"pasteCleanUpCallback"),insertHtmlCallback:d.context(this,"insertHtmlCallback")},this.options.editorOptions||{});d(l).triggerHandler("EditorInit",
{editor:this,config:this.editorConfig,$textarea:b});b.css("visibility","").show();b.redactor(this.editorConfig)},getButtonConfig:function(){var b=this,c=[["switchmode"],["removeformat"]],a=this.options.buttonConfig,e;(!a||a.basic)&&c.push(["bold","italic","underline"]);(!a||a.extended)&&c.push(["fontcolor","fontsize","fontfamily"]);(!a||a.link)&&c.push(["createlink","unlink"]);(!a||a.align)&&c.push(["alignment"]);!a||a.list?c.push(["unorderedlist","orderedlist","outdent","indent"]):a.indent&&c.push(["outdent",
"indent"]);e=[];(!a||a.smilies)&&e.push(["smilies"]);(!a||a.image)&&e.push("image");(!a||a.media)&&e.push("media");(!a||a.block)&&e.push("insert");e.length&&c.push(e);e=[];this.options.bbCodes&&d.each(this.options.bbCodes,function(b){(!a||a[b])&&e.push("custom_"+b)});e.length&&c.push(e);this.autoSaveUrl&&c.push(["draft"]);c.push(["undo","redo"]);var f=function(a,b,c){a.focus();b=d(a.analyzeSelection().selectedEls);b.find("[style]").css("font-size","");b.filter("[style]").css("font-size","");a.execCommand("fontsize",
c)},g=function(a,b,c){a.focus();b=d(a.analyzeSelection().selectedEls);b.find("[style]").css("font-family","");b.filter("[style]").css("font-family","");a.execCommand("fontname",c)},h={},k={};d.each({Arial:"arial,helvetica,sans-serif","Book Antiqua":"'book antiqua',palatino,serif","Courier New":"'courier new',courier,monospace",Georgia:"georgia,palatino,serif",Tahoma:"tahoma,arial,helvetica,sans-serif","Times New Roman":"'times new roman',times,serif","Trebuchet MS":"'trebuchet ms',geneva,sans-serif",
Verdana:"verdana,geneva,sans-serif"},function(a,b){h[a]={title:a,callback:g,style:"font-family: "+b}});d.each({1:"9px",2:"10px",3:"12px",4:"15px",5:"18px",6:"22px",7:"26px"},function(a,b){k[a]={title:a,callback:f,style:"font-size: "+b}});var i={switchmode:{title:this.getText("switch_mode_bb"),callback:d.context(this,"wysiwygToBbCode")},removeformat:{title:this.getText("remove_formatting"),exec:"removeformat"},fontsize:{title:this.getText("font_size"),func:"show",dropdown:k},fontfamily:{title:this.getText("font_family"),
func:"show",dropdown:h},smilies:{title:this.getText("smilies"),callback:d.context(this,"toggleSmilies")},createlink:{title:this.getText("link"),callback:d.context(this,"getLinkModal")},unlink:{title:this.getText("unlink"),exec:"unlink"},image:{title:this.getText("image"),callback:d.context(this,"getImageModal")},media:{title:this.getText("media"),callback:d.context(this,"getMediaModal")},draftsave:{title:this.getText("save_draft"),callback:d.proxy(function(){this.saveDraft(!0);this.api.focus()},this),
className:"icon saveDraft"},draftdelete:{title:this.getText("delete_draft"),callback:d.proxy(function(){this.saveDraft(!0,!0);this.api.focus()},this),className:"icon deleteDraft"},draft:{title:this.getText("drafts"),func:"show",dropdown:{}},undo:{title:this.getText("undo"),exec:"undo"},redo:{title:this.getText("redo"),exec:"redo"},alignment:{title:this.getText("alignment"),func:"show",dropdown:{alignleft:{title:this.getText("align_left"),exec:"JustifyLeft",className:"icon alignLeft"},aligncenter:{title:this.getText("align_center"),
exec:"JustifyCenter",className:"icon alignCenter"},alignright:{title:this.getText("align_right"),exec:"JustifyRight",className:"icon alignRight"}}},insertquote:{title:this.getText("quote"),callback:function(a){b.wrapSelectionInHtml(a,"[QUOTE]","[/QUOTE]",!0)},className:"icon quote"},insertspoiler:{title:this.getText("spoiler"),callback:d.context(this,"getSpoilerModal"),className:"icon spoiler"},insertcode:{title:this.getText("code"),callback:d.context(this,"getCodeModal"),className:"icon code"},insert:{title:this.getText("insert"),
func:"show",dropdown:{}}};i.draft.dropdown={save:i.draftsave,"delete":i.draftdelete};i.insert.dropdown={quote:i.insertquote,spoiler:i.insertspoiler,code:i.insertcode,deleted:{title:this.getText("deleted"),exec:"StrikeThrough",className:"icon strikethrough"}};this.options.bbCodes&&d.each(this.options.bbCodes,function(a,c){var e=a.toUpperCase();i["custom_"+a]={title:c.title,callback:function(a){c.hasOption=="yes"?b.wrapSelectionInHtml(a,"["+e+"=]","[/"+e+"]",!0):b.wrapSelectionInHtml(a,"["+e+"]","[/"+
e+"]",!0)}}});return{buttons:c,buttonsCustom:i}},_adjustButtonConfig:function(b,c){var a=this,e=[],d;for(d in c)c.hasOwnProperty(d)&&function(d){var f=c[d];b.buttonsCustom[d]={title:a.getText(d,f.title),callback:function(b){if(f.exec)b.execCommand(f.exec);else if(f.tag){var c=f.tag;a.wrapSelectionInHtml(b,"["+c+"]","[/"+c+"]",!0)}}};e.push(d)}(d);e.length&&b.buttons.push(e);return b},getExecHandlers:function(){return{}},editorInit:function(b){this.api=b;var c=this,a=b.$editor,e=a.closest("body"),
f=a.closest("html");d.browser.msie&&(e.click(function(a){a.stopPropagation()}),f.click(function(){b.focus();b.getSelection().collapse(1)}));a.on("cut copy",d.context(this,"editorCutCopyCallback"));d.each(["switchmode","removeformat"],function(a,c){var e=b.getBtn(c),d=e.closest(".redactor_btn_group");d.length||(d=e.parent());d.addClass("redactor_btn_right")});a.on("click","img",function(a){b.focus();if(d(this).hasClass("mceSmilie")||d(this).hasClass("mceSmilieSprite")||d(this).hasClass("attachFull")||
d(this).hasClass("attachThumb"))a.preventDefault();else{for(var a=0,e=this;e.previousSibling;)a++,e=e.previousSibling;b.setSelection(this.parentNode,a,this.parentNode,a+1);c.getImageModal(b)}});a.on("click","a",function(a){a.preventDefault()});this.initFocusWatch();this.initPlaceholder();this.initElastic();this.initDragDrop();this.initAutoComplete();this.autoSaveUrl&&setTimeout(function(){c.initAutoSave()},0);this.$textarea.closest("form").submit(function(){b.syncCode()})},editorCutCopyCallback:function(b){var c=
this.api,a=c.$editor,e=c.analyzeSelection();if(!e.isCollapsed){var f=c.getSelectedHtml(),f=f.replace(/<p/gi,'<div data-redactor="1"').replace(/<\/p>/gi,"</div>");c.browser("msie")||(f=f.replace(/<(p|div)[^>]><\/(p|div)>/gi,""));var f=f.replace(/<font/gi,'<font data-redactor="1"'),g=d('<div data-redactor-wrapper="1" />').html(f).css({position:"absolute",left:"-9999px"});f.match(/<(article|blockquote|dd|div|dl|fieldset|form|h\d|header|hr|ol|p|pre|section|table|ul)/)||(e.$commonAncestor.parents().addBack().filter("b, strong, i, em, u, s, span, strike, font").each(function(){g.append(d(this.cloneNode(!1)).append(g[0].childNodes))}),
f.match(/^\s*<li/)&&e.$commonAncestor.parents().addBack().filter("ul, ol").first().each(function(){g.append(d(this.cloneNode(!1)).append(g[0].childNodes))}));b.type=="cut"&&(c.pasteHtmlAtCaret(""),c.formatEmpty());c.saveSelection();a.append(g);b=c.getSelection();try{b.selectAllChildren(g.get(0))}catch(h){this.api.document.createRange&&b.removeAllRanges&&b.addRange?(a=this.api.document.createRange(),a.selectNode(g.get(0)),b.removeAllRanges(),b.addRange(a)):b.moveToElementText&&(b.moveToElementText(g.get(0)),
b.select())}setTimeout(function(){g.remove();c.restoreSelection()},0)}},initFocusWatch:function(){var b=this.api,c=this,a;b.$editor.on("focus click",function(){a&&(clearTimeout(a),a=null);b.$box.addClass("focused")});b.$editor.on("blur",function(){a=setTimeout(function(){b.$box.removeClass("focused")},200)});b.$editor.on("focus click keypress",function(){if(!c.editorActivated)b.$box.addClass("activated"),c.editorActivated=!0});if(b.isMobile(!0)){var e=j.innerHeight;d(j).on("resize",function(){b.$box.hasClass("focused")&&
j.innerHeight<e&&setTimeout(function(){if(d(j).scrollTop()==0){var a=b.getFocus()[0];a&&(b.$editor[0].scrollIntoView(),a.scrollIntoView?a.scrollIntoView():a.parentNode.scrollIntoView())}},50);e=j.innerHeight})}},initPlaceholder:function(){if(this.options.placeholder){var b=this.api,c=this;if(!this.$placeholder)this.$placeholder=d('<div class="placeholder" />').append(d("<span />").text(this.getText(this.options.placeholder))),b.$content.before(this.$placeholder),this.$placeholder.click(function(){b.focus()});
this.placeholderVisible=!1;b.$editor.on("focus click keydown",function(){if(c.placeholderVisible)c.$placeholder.hide(),c.placeholderVisible=!1});if(b.$editor.html().match(/^$|(^\s*<p>(\s|&nbsp;|<br\s*\/?>)*<\/p>\s*$)/i))this.$placeholder.show(),this.placeholderVisible=!0}},initElastic:function(){var b=this.api,c=b.$box.find("iframe"),a=d(j).height()-200,e=b.$el.outerHeight(),f=b.$editor[0],g=0,h,k=d.browser.msie&&d.browser.version<9;c.closest(".xenOverlay").length&&(a-=175);a=Math.max(a,e);this.minHeight=
e;this.maxHeight=a;if(b.isMobile(!0)){var i=function(){var a=b.$box.width();a&&d(f.ownerDocument.documentElement).width(a)};i();b.$editor.on("focus",i);d(j).on("orientationchange resize",function(){setTimeout(i,0)});b.$editor.addClass("noElastic");c.height(Math.max(Math.min(175,j.innerHeight/2),e))}else{h=function(){if(c){b.$editor.css("min-height","");var h=k?f.scrollHeight:Math.min(f.offsetHeight,f.scrollHeight);b.$editor.css("min-height",e-1);if(h<f.clientHeight||d.browser.msie)h+=22;h<e?h=e:h>
a&&(h=a);h!=g&&(k||(g<h&&h==a?b.$editor.css("overflow-y",""):g==a&&h<a&&b.$editor.css("overflow-y","hidden")),c.height(h),g=h)}};var m;b.$editor.on("paste change keydown focus click drop",function(){m||(m=setTimeout(function(){m=null;h()},100))});b.$editor.data("xenForoElastic",h);k||b.$editor.css("overflow-y","hidden");b.$editor.on("drop",function(){b.$editor.css("display","block");setTimeout(function(){b.$editor.css("display","")},0)});h();setTimeout(h,250);this.watchImagesElastic();d(j).focus(h)}},
triggerElastic:function(){if(this.$textarea.data("redactor")){var b=this.api.$editor.data("xenForoElastic");b&&b()}},watchImagesElastic:function(b){var b=b===!1||typeof b=="undefined"?this.api.$editor:d(b),c,a=this,e=function(){c&&clearTimeout(c);c=setTimeout(function(){a.triggerElastic()},100)};b.find("img").one("load",e);b.filter("img").one("load",e)},resetEditor:function(b,c){if(this.$textarea.data("redactor")){var a=this.api;if(!b)b=a.opts.emptyHtml;a.setCode(b,!1);a.observeFormatting();this.resetAutoSave();
this.initPlaceholder();a.$box.find(".redactor_smilies").hide();a.$box.removeClass("activated");this.editorActivated=!1;var e=a.$editor.data("xenForoElastic");e&&e();if(c){e=a.$editor;if(a.opts.iframe&&e[0])(a=e[0].ownerDocument)&&(a.defaultView||a.parentWindow).focus();d.browser.msie||e.blur()}}},initDragDrop:function(){if(!this.api.isMobile(!0)&&!this.$textarea.hasClass("NoAttachment")){var b=this.api,c=function(){g.removeClass("hover")},a=b.$box.closest("form").find(".AttachmentUploader"),e=a.length>
0,f,g=d('<div class="redactor_editor_drop" />');g.append(d("<span />").text(this.getText(e?"drop_files_here_to_upload":"uploads_are_not_available"))).appendTo(b.$box);e||g.addClass("dragDisabled");var h=function(a){a=a.originalEvent.dataTransfer;if(!a||typeof a.files=="undefined")return!1;if(a.types&&(d.inArray("Files",a.types)==-1||a.types[0]=="text/x-moz-url"))return!1;a.dropEffect="copy";return!0};d([l,b.document]).on("dragover",function(a){h(a)&&(g.addClass("hover"),clearTimeout(f),f=setTimeout(c,
200))});g.on("dragover",function(a){h(a)&&a.preventDefault()});g.on("drop",function(b){b.preventDefault();clearTimeout(f);c();if(e&&(b=b.originalEvent.dataTransfer)&&b.files&&b.files.length)for(var g=0;g<b.files.length;g++){try{var h=new FormData;h.append("upload",b.files[g]);h.append("_xfToken",XenForo._csrfToken);h.append("_xfNoRedirect","1");a.find(".HiddenInput").each(function(){var a=d(this);h.append(a.data("name"),a.data("value"))})}catch(j){break}d.ajax({url:a.data("action"),method:"POST",
dataType:"json",data:h,processData:!1,contentType:!1}).done(function(b){XenForo.hasResponseError(b)||a.trigger({type:"AttachmentUploaded",ajaxData:b})}).fail(function(a){try{var b=d.parseJSON(a.responseText);b&&XenForo.hasResponseError(b)}catch(c){}})}})}},initAutoComplete:function(){if(!this.$textarea.hasClass("NoAutoComplete")){var b=this.api.$editor,c=b[0].ownerDocument,a=this,e=function(){setTimeout(function(){a.acResults.hideResults()},200)};this.acVisible=!1;this.acResults=new XenForo.AutoCompleteResults({onInsert:d.context(this,
"insertAutoComplete")});d(c.defaultView||c.parentWindow).on("scroll",e);b.on("click blur",e);b.on("keydown",function(b){var c=!0,e=a.acResults;if(e.isVisible()){switch(b.keyCode){case 40:e.selectResult(1);break;case 38:e.selectResult(-1);break;case 27:e.hideResults();break;case 13:e.insertSelectedResult();break;default:c=!1}c&&(b.stopPropagation(),b.stopImmediatePropagation(),b.preventDefault())}});b.data("events").keydown.reverse();b.on("keyup",function(){var b=a.findCurrentAutoCompleteOption();
b?a.triggerAutoComplete(b):a.hideAutoComplete()})}},findCurrentAutoCompleteOption:function(){var b=this.api,c=b.getFocus(),b=b.getOrigin();if(!c||!b||c[0]!=b[0]||c[1]!=b[1])return!1;b=d(c[0]);c=c[0].nodeType==3?b.text().substring(0,c[1]):d(b.contents().get(c[1]-1)).text();b=c.lastIndexOf("@");if(b!=-1&&(b==0||c.substr(b-1,1).match(/(\s|[\](,]|--)/)))if(c=c.substr(b+1),!c.match(/\s/)||c.length<=10)return c=c.replace(RegExp(String.fromCharCode(160),"g")," ");return!1},insertAutoComplete:function(b){this.api.focus();
var c=this.api,a=c.getFocus(),e=d(a[0]);a[0].nodeType==3?e=e.text().substring(0,a[1]):(a[0]=e.contents().get(a[1]-1),e=d(a[0]),e=e.text());var f=e.lastIndexOf("@");if(f!=-1)c.setSelection(a[0],f,a[0],e.length),c.insertHtml("@"+XenForo.htmlspecialchars(b)+"&nbsp;"),this.lastAcLookup=b+" ";c.focus()},triggerAutoComplete:function(b){if(!(this.lastAcLookup&&this.lastAcLookup==b)&&(this.hideAutoComplete(),this.lastAcLookup=b,b.length>2&&b.substr(0,1)!="["))this.acLoadTimer=setTimeout(d.context(this,"autoCompleteLookup"),
200)},autoCompleteLookup:function(){this.acXhr&&this.acXhr.abort();this.acXhr=XenForo.ajax(this.autoCompleteUrl,{q:this.lastAcLookup},d.context(this,"showAutoCompleteResults"),{global:!1,error:!1})},showAutoCompleteResults:function(b){this.acXhr=!1;if(this.lastAcLookup==this.findCurrentAutoCompleteOption()){var c=this.api,a=c.$box.find("iframe"),e=a.offset(),f=c.getFocus()[0],f=f.nodeType==3?d(f).parent():d(f),g=f.offset(),c={top:e.top+g.top+f.height()-c.$editor.scrollTop(),left:e.left};if(XenForo.isRTL())c.right=
d("html").width()-e.left-a.outerWidth(),c.left="auto";this.acResults.showResults(this.lastAcLookup,b.results,a,c)}},hideAutoComplete:function(){this.acResults.hideResults();if(this.acLoadTimer)clearTimeout(this.acLoadTimer),this.acLoadTimer=!1},syncEditor:function(){this.$textarea&&this.$textarea.data("redactor")&&this.$textarea.data("redactor").syncCode()},initAutoSave:function(){var b=this.api,c=this;if(this.$textarea.closest("form").length){this.lastAutoSaveContent=b.getCode();var a=setInterval(function(){c.$textarea.data("redactor")?
c.saveDraft():clearInterval(a)},(this.options.autoSaveFrequency||60)*1E3)}},saveDraft:function(b,c){var a=this.api,e=this,f=this.$textarea.closest("form"),g=a.$el.prop("disabled")?this.$bbCodeTextArea.val():a.getCode();if(!c&&!b&&g==this.lastAutoSaveContent)return!1;a.syncCode();this.lastAutoSaveContent=g;var h=d.Event("BbCodeWysiwygEditorAutoSave");h.editor=this;h.content=g;h.deleteDraft=c;f.trigger(h);if(h.isDefaultPrevented())return!1;if(this.autoSaveRunning)return!1;this.autoSaveRunning=!0;XenForo.ajax(this.autoSaveUrl,
f.serialize()+(c?"&delete_draft=1":""),function(b){var c=d.Event("BbCodeWysiwygEditorAutoSaveComplete");c.ajaxData=b;f.trigger(c);if(!c.isDefaultPrevented()){c=a.$box.find(".draftNotice");c.length||(c=d('<div class="draftNotice"><span></span></div>'),a.$content.after(c));var g=c.find("span:first"),h;b.draftSaved?h=e.getText("draft_saved"):b.draftDeleted&&(h=e.getText("draft_deleted"));h&&(g.text(h),c.finish().hide().fadeIn().delay(2E3).fadeOut())}},{global:!1}).complete(function(){e.autoSaveRunning=
!1});return!0},triggerAutoSave:function(){this.saveDraft(!0)},triggerAutoSaveDelete:function(){this.saveDraft(!0,!0)},resetAutoSave:function(){if(this.$textarea.data("redactor")){var b=this.api,c=this.$textarea.closest("form");this.lastAutoSaveContent=b.$el.prop("disabled")?this.$bbCodeTextArea.val():b.getCode();c.find(".draftUpdate .draftDeleted, .draftUpdate .draftSaved").finish().fadeOut()}},insertHtmlCallback:function(b){this.watchImagesElastic(b);var c=this;setTimeout(function(){c.triggerElastic()},
300)},wrapSelectionInHtml:function(b,c,a,e){e&&(a='<ins class="selection"></ins>'+a);var d=b.getSelectedHtml(),d=d.replace(/^(<p[^>]*>)?/,"$1"+c).replace(/(<\/p>)?$/,a+"$1");b.execCommand("inserthtml",d);b.syncCode();e&&(c=b.$editor.find("ins.selection"),c.length?(b.setSelection(c[0],0,c[0],0),c.remove()):b.focus())},toggleSmilies:function(b){var c=this,a=b.$box.find(".redactor_smilies");if(a.length)a.slideToggle();else if(!c.smiliesPending)c.smiliesPending=!0,XenForo.ajax("index.php?editor/smilies",
{},function(c){XenForo.hasResponseError(c)||c.templateHtml&&new XenForo.ExtLoader(c,function(){a=d('<div class="redactor_smilies" />').html(c.templateHtml);a.hide();a.on("click",".Smilie",function(a){a.preventDefault();a=d(this);a=d.trim(a.html());b.execCommand("inserthtml",a);b.focus()});b.$box.append(a);a.xfActivate();a.slideToggle()})}).complete(function(){c.smiliesPending=!1})},modalCreateCallback:function(b,c){c.addClass("xenOverlay");var a=d('<form class="formOverlay xenForm" />').append(c.children()).appendTo(c);
a.on("submit",function(b){b.preventDefault();a.find(".button.primary").click()});a.on("click","input[type=submit]",function(a){a.stopPropagation();a.preventDefault()});d("#redactor_modal_header").addClass("heading");return c},getLinkModal:function(b){b.saveSelection();var c=b.getSelectedNode(),a;c&&(a=d(c).closest("a",b.$editor[0]));b.modalInit(this.getText("link"),{url:this.dialogUrl+"&dialog=link"},600,d.proxy(function(){var c=d("#redactor_link_url");d("#redactor_insert_link_btn").click(function(d){d.preventDefault();
setTimeout(function(){b.restoreSelection();var d=c.val(),f=b.analyzeSelection();if(d!==""){b.pushUndoStack();var k=d;d.match(/^mailto:/)||(d.match(/@[a-z0-9-]+\.[a-z0-9\.-]+$/i)?d="mailto:"+d:d.match(/^https?:|ftp:/i)||(d="http://"+d));a&&a.length?(f=a.attr("href"),a.attr("href",d),a.text()==f&&(a.text(d),b.setSelection(a[0],1,a[0],1))):f.isCollapsed?b.pasteHtmlAtCaret('<a href="'+XenForo.htmlspecialchars(d)+'">'+XenForo.htmlspecialchars(k)+"</a>"):(b.execCommand("unlink","",!1),b.execCommand("createlink",
d,!1))}else a&&a.length&&(b.pushUndoStack(),f.bookmarkSelection(),a.after(a[0].childNodes),a.remove(),f.restoreBookmark());b.syncCode();b.modalClose();b.focus()},150)});a&&a.length&&c.val(a.attr("href").replace(/^mailto:/,""));setTimeout(function(){c.focus()},100)},b))},getImageModal:function(b){b.saveSelection();var c=b.getSelectedHtml(),a;if(c.match(/^\s*<img[^>]+src="([^"]+)"[^>]*>\s*$/)&&!c.match(/mceSmilie|attachFull|attachThumb/))a=RegExp.$1,a=d("<textarea>").html(a).text();b.modalInit(this.getText("image"),
{url:this.dialogUrl+"&dialog=image"},600,d.proxy(function(){var c=d("#redactor_image_link");d("#redactor_image_btn").click(function(a){a.preventDefault();b.restoreSelection();a=c.val();a!==""&&(a.match(/^https?:|ftp:/i)||(a="http://"+a),b.pasteHtmlAtCaret('<img src="'+XenForo.htmlspecialchars(a)+'" alt="[IMG]" unselectable="on" />&nbsp;'));b.modalClose();b.observeImages();b.syncCode();b.focus()});a&&c.val(a);setTimeout(function(){c.focus()},100)},b))},getMediaModal:function(b){var c=this;b.saveSelection();
b.modalInit(this.getText("media"),{url:this.dialogUrl+"&dialog=media"},600,d.proxy(function(){d("#redactor_insert_media_btn").click(function(a){a.preventDefault();c.insertMedia(a,b)});setTimeout(function(){d("#redactor_media_link").focus()},100)},b))},insertMedia:function(b,c){XenForo.ajax("index.php?editor/media",{url:d("#redactor_media_link").val()},function(a){XenForo.hasResponseError(a)||(a.matchBbCode?(c.restoreSelection(),c.execCommand("inserthtml",a.matchBbCode),c.syncCode(),c.modalClose()):
a.noMatch&&alert(a.noMatch))})},getCodeModal:function(b){var c=this;b.saveSelection();b.modalInit(this.getText("code"),{url:this.dialogUrl+"&dialog=code"},600,d.proxy(function(){d("#redactor_insert_code_btn").click(function(a){a.preventDefault();c.insertCode(a,b)});setTimeout(function(){d("#redactor_code_code").focus()},100)},b))},insertCode:function(b,c){var a,e;switch(d("#redactor_code_type").val()){case "html":a="HTML";break;case "php":a="PHP";break;default:a="CODE"}e=d("#redactor_code_code").val();
e=e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/\t/g,"    ").replace(/  /g,"&nbsp; ").replace(/  /g,"&nbsp; ").replace(/\n/g,"</p>\n<p>");a="["+a+"]"+e+"[/"+a+"]";a.match(/\n/)&&(a=("<p>"+a+"</p>").replace(/<p><\/p>/g,"<p>"+(!d.browser.msie?"<br>":"&nbsp;")+"</p>"));c.restoreSelection();c.execCommand("inserthtml",a);c.syncCode();c.modalClose()},getSpoilerModal:function(b){var c=this;b.saveSelection();b.modalInit(this.getText("spoiler"),{url:this.dialogUrl+
"&dialog=spoiler"},600,d.proxy(function(){d("#redactor_insert_spoiler_btn").click(function(a){a.preventDefault();c.insertSpoiler(a,b)});setTimeout(function(){d("#redactor_spoiler_title").focus()},100)},b))},insertSpoiler:function(b,c){var a=d("#redactor_spoiler_title").val();a?this.wrapSelectionInHtml(c,'[SPOILER="'+XenForo.htmlspecialchars(a)+'"]',"[/SPOILER]",!0):this.wrapSelectionInHtml(c,"[SPOILER]","[/SPOILER]",!0);c.modalClose()},wysiwygToBbCode:function(b){var c=this;b.getCode().match(/^<p>(<br\s*\/?>|\s|&nbsp;)*<\/p>$/i)?
c.wysiwygToBbCodeSuccess(b,{bbCode:""}):XenForo.ajax("index.php?editor/to-bb-code",{html:b.getCode()},function(a){c.wysiwygToBbCodeSuccess(b,a)})},wysiwygToBbCodeSuccess:function(b,c){if(!(XenForo.hasResponseError(c)||typeof c.bbCode=="undefined")){var a=b.$box,e=b.$el,f=d('<div class="bbCodeEditorContainer" />'),g=d('<textarea class="textCtrl Elastic" rows="5" />'),h=this;if(!e.prop("disabled"))g.attr("name",e.attr("name").replace(/_html(]|$)/,"$1")).val(c.bbCode).appendTo(f),this.$textarea.hasClass("NoAttachment")&&
g.addClass("NoAttachment"),d("<a />").attr("href","javascript:").text(this.getText("switch_mode_rich")).click(function(){h.bbCodeToWysiwyg(b)}).appendTo(d("<div />").appendTo(f)),e.prop("disabled",!0),b.browser("mozilla")&&d(j).unbind("unload.rte").bind("unload.rte",function(){e.removeAttr("disabled")}),a.hide(),f.insertAfter(a).xfActivate(),g.focus(),this.$bbCodeTextContainer=f,this.$bbCodeTextArea=g}},bbCodeToWysiwyg:function(b){var c=this,a=this.$bbCodeTextArea.val();d.trim(a).length==0?this.bbCodeToWysiwygSuccess(b,
{html:"<p>"+(!d.browser.msie?"<br />":"")+"</p>"}):XenForo.ajax("index.php?editor/to-html",{bbCode:this.$bbCodeTextArea.val()},function(a){c.bbCodeToWysiwygSuccess(b,a)})},bbCodeToWysiwygSuccess:function(b,c){if(!(XenForo.hasResponseError(c)||typeof c.html=="undefined")){var a=b.$box,d=b.$el;d.prop("disabled")&&(d.prop("disabled",!1),a.show(),b.setCode(c.html),b.selectFirst(),b.observeFormatting(),this.$bbCodeTextContainer.remove())}},pastePreventCallback:function(b,c,a){var d=a.originalEvent;if(d.clipboardData){var f=
d.clipboardData,d=f.items,f=f.types;if(d&&f){for(var g=0;g<f.length;g++)if(f[g]=="text/html")return;f=!1;for(g=0;g<d.length;g++)if(d[g].type.match(/^image\/([a-z0-9_-]+)$/i)){var h=d[g].getAsFile(),k=(j.URL||j.webkitURL).createObjectURL(h),i=this.pasteImageCounter++;this.uploadPastedImage(c,i,RegExp.$1,h)&&(c.insertHtml('<img src="'+k+'" data-paste-id="'+i+'">'),f=!0)}f&&(b.preventDefault(),a.preventDefault(),a.stopPropagation())}}},pasteManipulateCallback:function(b,c){if(c&&c.querySelectorAll){var a=
c.querySelectorAll("img");if(a)for(var d=0;d<a.length;d++)if(a[d].setAttribute("style","-x-ignore: 1"),a[d].src.match(/^data:image\/([a-z0-9_-]+);([a-z0-9_-]+),([\W\w]+)$/i)){var f=this.pasteImageCounter++;a[d].setAttribute("data-paste-id",f);this.uploadPastedImage(b,f,RegExp.$1,RegExp.$3,RegExp.$2)||a[d].parentNode.removeChild(a[d])}}},pasteCleanUpCallback:function(b,c,a){var e=c.browser("msie")&&l.all,a=d.trim(a),f=a.match(/<[a-zA-Z0-9-]+[^>]* data-redactor="1"/),a=a.replace(/^<div[^>]* data-redactor-wrapper="1"[^>]*>([\w\W]+)<\/div>$/,
"$1");c.browser("mozilla")&&(a=a.replace(/<br>$/gi,""));a=a.replace(/<img[^>]+src="webkit-fake-url:[^"]*"[^>]*>/ig,"");a.match(/<p(\s|>)/i)&&!a.match(/^<(ul|ol|li|p|div|table|tr|th|td|pre|h\d)(\s|>)/)&&(a="<p>"+a.replace(/(<p(\s|>))/,"</p>$1"));a=a.replace(/<\/p>/gi,"</p><p>"+(e?"":"<br>")+"<span><span></span></span></p>");a=a.replace(/<p>(<br>)?<span><span><\/span><\/span><\/p>$/,"");a=a.replace(/<div/gi,"<p").replace(/<\/div>/g,"</p>");a=a.replace(/<p([^>]*)>(\s*|<br\s*\/?>|&nbsp;)<\/p>/gi,"<p$1>"+
(e?"":"<br>")+"<span><span></span></span></p>");a=a.replace(/(<[a-zA-Z0-9-]+[^>]*) data-redactor="1"/g,"$1");a=a.replace(/<span[^>]+style="[^"]*white-space:\s*pre[^"]*"[^>]*>([\w\W]+?)<\/span>/g,function(a,b){return b.replace(/\t/g,"    ").replace(/  /g,"&nbsp; ").replace(/  /g,"&nbsp; ")});a=a.replace(/(.|^)<a\s[^>]*data-user="(\d+, [^"]+)"[^>]*>([\w\W]+?)<\/a>/gi,function(a,b,c){c=c.split(", ");return!parseInt(c[0],10)?a:b+(b=="@"?"":"@")+c[1].replace(/^@/,"")});a=a.replace(/(<img\s[^>]*)src="[^"]*"(\s[^>]*)data-url="([^"]+)"/gi,
function(a,b,c,d){return b+'src="'+d+'"'+c});if(!f)var g=function(a,b,c){var d;do{d=a.replace(b,c);if(d==a)break;a=d}while(1);return d},a=g(a,/<input[^>]*>/gi,""),a=g(a,/<textarea[^>]*>/gi,""),a=g(a,/<select[^>]*>([\w\W]*?)<\/select>/gi,""),a=g(a,/<button[^>]*>([\w\W]*?)<\/button>/gi,""),a=g(a,/<article[^>]*>([\w\W]*?)<\/article>/gi,"$1"),a=g(a,/<blockquote[^>]*>([\w\W]*?)<\/blockquote>/gi,"$1"),a=g(a,/<del[^>]*>([\w\W]*?)<\/del>/gi,"$1"),a=g(a,/<ins[^>]*>([\w\W]*?)<\/ins>/gi,"$1"),a=g(a,/<sub[^>]*>([\w\W]*?)<\/sub>/gi,
"$1"),a=g(a,/<sup[^>]*>([\w\W]*?)<\/sup>/gi,"$1"),a=g(a,/<code[^>]*>([\w\W]*?)<\/code>/gi,"$1"),a=g(a,/<tr[^>]*>([\w\W]*?)<\/tr>/gi,"<p>$1</p>"),a=g(a,/<td[^>]*>([\w\W]*?)<\/td>/gi,"$1 "),a=g(a,/<th[^>]*>([\w\W]*?)<\/th>/gi,"<b>$1</b> "),a=g(a,/<tbody[^>]*>([\w\W]*?)<\/tbody>/gi,"$1 "),a=g(a,/<table[^>]*>([\w\W]*?)<\/table>/gi,"$1 "),a=a.replace(/<h1[^>]*>([\w\W]+?)<\/h1>/ig,'<p>[paste:font size="6"]<b>$1</b>[/paste:font]</p>'),a=a.replace(/<h2[^>]*>([\w\W]+?)<\/h2>/ig,'<p>[paste:font size="5"]<b>$1</b>[/paste:font]</p>'),
a=a.replace(/<h3[^>]*>([\w\W]+?)<\/h3>/ig,'<p>[paste:font size="4"]<b>$1</b>[/paste:font]</p>'),a=a.replace(/<h4[^>]*>([\w\W]+?)<\/h4>/ig,'<p>[paste:font size="3"]<b>$1</b>[/paste:font]</p>'),a=a.replace(/<h5[^>]*>([\w\W]+?)<\/h5>/ig,"<p><b>$1</b></p>"),a=a.replace(/<h6[^>]*>([\w\W]+?)<\/h6>/ig,"<p><b>$1</b></p>"),a=a.replace(/<pre[^>]*>([\w\W]+?)<\/pre>/ig,function(a,b){var c="",c=b.length?"<p>"+b.replace(/\r?\n/g,"</p><p>")+"</p>":"<p></p>";return c.replace(/<p([^>]*)>(\s*|<br\s*\/?>|&nbsp;)<\/p>/gi,
"<p$1>"+(e?"":"<br>")+"<span><span></span></span></p>")});c.$editor.data("xenForoElastic")&&setTimeout(function(){c.$editor.data("xenForoElastic")()},0);!a.match(/<(?!br\s*\/?)([a-z0-9-]+)(\s|\/|>)/i)&&a.match(/<br\s*\/?>/i)&&(a="<p>"+a.replace(/<br\s*\/?>\s*/ig,"</p><p>")+"</p>",a=a.replace(/<p><\/p>/ig,"<p>"+(e?"":"<br>")+"<span><span></span></span></p>"));f&&(a=a.replace(/<span><span><\/span><\/span>/gi,""),b.preventDefault());return a},uploadPastedImage:function(b,c,a,e,f){var g=b.$box.closest("form").find(".AttachmentUploader");
if(!g.length)return!1;if(this.$textarea.hasClass("NoAttachment"))return!1;try{var h=new FormData;if(typeof e=="string"){var k;k=f=="base64"?atob(e):unescape(e);b=[];for(f=0;f<k.length;f++)b.push(k.charCodeAt(f));e=new Blob([new Uint8Array(b)],{type:"image/"+a})}var i=new Date,j="upload_"+i.getFullYear()+"-"+(i.getMonth()+1)+"-"+i.getDate()+"_"+i.getHours()+"-"+i.getMinutes()+"-"+i.getSeconds()+"."+a;h.append("upload",e,j);h.append("filename",j);h.append("_xfToken",XenForo._csrfToken);h.append("_xfNoRedirect",
"1");g.find(".HiddenInput").each(function(){var a=d(this);h.append(a.data("name"),a.data("value"))})}catch(l){return!1}var n=this;d.ajax({url:XenForo.canonicalizeUrl(g.data("action"),XenForo.ajaxBaseHref),method:"POST",dataType:"json",data:h,processData:!1,contentType:!1}).done(function(a){if(n.$textarea.data("redactor")){var b=n.$textarea.getEditor().find("img[data-paste-id="+c+"]");XenForo.hasResponseError(a)?b.remove():(b.data("paste-id","").attr("src",a.viewUrl).attr("alt","attachFull"+a.attachment_id).addClass("attachFull"),
g.trigger({type:"AttachmentUploaded",ajaxData:a}))}}).fail(function(a){n.$textarea.getEditor().find("img[data-paste-id="+c+"]").remove();try{var b=d.parseJSON(a.responseText);b&&XenForo.hasResponseError(b)}catch(e){}});return!0},getText:function(b,c){var a=RELANG.xf||RLANG;return typeof a[b]=="string"?a[b]:c||b}};XenForo.BbCodeWysiwygEditor_EXTEND=XenForo.BbCodeWysiwygEditor_EXTEND||{};XenForo.register("textarea.BbCodeWysiwygEditor","XenForo.BbCodeWysiwygEditor")})(jQuery,this,document);
