/*
 * XenForo template_edit.min.js
 * Copyright 2010-2017 XenForo Ltd.
 * Released under the XenForo License Agreement: http://xenforo.com/license-agreement
 */
(function(d,k,n){XenForo.TemplateEditor={};XenForo.TemplateEditor=function(a){this.__construct(a)};XenForo.TemplateEditor.prototype={__construct:function(a){this.useAjaxSave=!0;this.setupEditors(a)},setupEditors:function(a){this.initialized=!1;this.$form=a;this.$styleId=d("#styleId");this.$templateId=d("#templateId");this.$titleOriginal=d("#templateTitleOriginal");this.$templateTitle=d("#templateTitle");this.$templateTextarea=d("#templateTextarea");this.$saveReloadButton=d("#saveReloadButton");this.$saveExitButton=
d("#saveExitButton");this.$changeIndicator=this.createChangeIndicator();this.$templateTab=d("#templateTab");this.$editorTabs=d("#editorTabs");this.$primaryOnly=a.find(".PrimaryTemplateOnly");this.editors={};this.templateData={"":{style_id:0,template_id:0,template:""}};this.requireRegex=RegExp('<xen:(require|include|edithint) [^>]*(css|template)="([^"]+)"[^>]*/?>',"gi");this.$titleOriginal.strval()?this.loadTemplates(this.getIncludeTitles()):this.initialize()},loadTemplates:function(a){a.length&&XenForo.ajax(this.getLoadUrl("json"),
{includeTitles:a,style_id:this.$styleId.val(),_TemplateEditorAjax:1},d.context(this,"ajaxLoadSuccess"),{type:"GET"})},ajaxLoadSuccess:function(a){if(XenForo.hasResponseError(a))return!1;this.templateData=a.templates;this.initialized||this.initialize();this.handleTitleChange();this.refreshEditors()},initialize:function(){this.initializePrimaryEditor();this.updateSaveActions();var a=function(a,c){var b=a[0],d=a.data("undoStack");d||(d=[]);d.push([a.val(),b.selectionStart,b.selectionEnd]);a.data("undoStack",
d);c&&a.data("redoStack",[])},c=function(c){var d=c[0];c.data("undoStack");var b=c.data("redoStack");if(b&&b.length)a(c,!1),b=b.pop(),c.val(b[0]),d.selectionStart=b[1],d.selectionEnd=b[2],c.data("lastSelPosition",b[2])},b=function(c){var b=c.data("lastSelPosition"),d=!1;typeof b!="undefined"&&!isNaN(b)&&c[0].selectionEnd!=b&&(a(c,!0),d=!0);setTimeout(function(){c.data("lastSelPosition",c[0].selectionEnd)},0);return d},i=this;this.$form.on("keypress",".textCtrl.code",function(){b(d(this))});this.$form.on("keydown",
".textCtrl.code",function(b){var e=d(this);e.data("undoStack")||e.data("undoStack",[[e.val(),0,0]]);b.keyCode==13&&a(e,!0);if(b.keyCode==90&&(b.metaKey||b.ctrlKey))if(b.preventDefault(),b.shiftKey)c(e);else{var b=e[0],f=e.data("undoStack"),g=e.data("redoStack");g||(g=[]);g.push([e.val(),b.selectionStart,b.selectionEnd]);e.data("redoStack",g);if(f&&f.length)f=f.pop(),e.val(f[0]),b.selectionStart=f[1],b.selectionEnd=f[2],e.data("lastSelPosition",f[2])}else if(b.keyCode==89&&(b.metaKey||b.ctrlKey))b.preventDefault(),
c(e);else if(b.keyCode==9&&!b.metaKey&&!b.ctrlKey&&!b.altKey){b.preventDefault();var f=this.selectionStart,h=this.selectionEnd,j=e.val(),g=j.substring(0,f),k=j.substring(h),m=!0;if(f!=h&&(h=j.substring(f,h),h.indexOf("\n")!=-1)){var m=!1,j=0,l=g.lastIndexOf("\n");l==-1?(h=g+h,j=g.length,g=""):(h=g.substring(l)+h,j=g.length-l,g=g.substring(0,l));b.shiftKey?(l=/(\n|^)(\t|[ ]{1,8})/g,h.match(l)&&(f-=1,j--),h=h.replace(l,"$1")):(h=h.replace(/(\n|^)/g,"$1\t"),f+=1,j++);a(e,!0);e.val(g+h+k);this.selectionStart=
f;this.selectionEnd=f+h.length-j}if(m&&!b.shiftKey)e.val(g+"\t"+k),this.selectionStart=this.selectionEnd=f+1}else if(b.keyCode==13&&!b.metaKey&&!b.ctrlKey&&!b.altKey&&!b.shiftKey){if(f=this.selectionStart,h=this.selectionEnd,j=e.val(),g=j.substring(0,f),k=j.substring(h),l=g.lastIndexOf("\n"),m=(l==-1?g:g.substring(l+1)).match(/^(\s+)/))b.preventDefault(),e.val(g+"\n"+m[1]+k),this.selectionStart=this.selectionEnd=f+m[1].length+1}else if(b.keyCode==83&&(b.ctrlKey||b.metaKey))b.preventDefault(),i.$saveReloadButton.click()});
this.$form.on("cut paste",".textCtrl.code",function(){b(d(this))||a(d(this),!0)})},initializePrimaryEditor:function(){var a=this.$templateId.strval(),c=this.$titleOriginal.strval(),b=this.createChangeIndicator();console.log("Initializing primary editor for template %s, id %s",c?c:"(untitled)",a);this.editors[c]={templateId:this.$templateId.val(),$changeIndicator:b,$styleId:d(n.createElement("input")).attr({type:"hidden",name:"styleidArray["+a+"]"}).val(this.templateData[c].style_id),$tab:this.$templateTab,
$title:this.$templateTitle.attr({templateTitle:c,name:"titleArray["+a+"]"}).keyup(d.context(this,"eTitleChange")).blur(d.context(this,"setBlurItem")),$textarea:this.$templateTextarea.attr({templateTitle:c,name:"templateArray["+a+"]"}).keyup(d.context(this,"eTemplateChange")).blur(d.context(this,"setBlurItem"))};this.editors[c].$tab.find("a").append("&nbsp;").attr("templateTitle",c).addClass(this.getInheritanceState(c)).click(d.context(this,"switchEditor")).prepend(this.editors[c].$changeIndicator).prepend(this.editors[c].$styleId);
this.initialized=!0},setBlurItem:function(a){this.blurItem=a.target},focusBlurItem:function(){this.blurItem!==void 0&&this.blurItem.focus()},refreshEditors:function(){var a=null,c=null;for(a in this.templateData)if(typeof this.templateData[a]!="function")this.editors[a]===void 0?this.editors[a]=this.createEditor(a,c):this.updateEditor(a),c=this.editors[a].$tab;for(a in this.editors)typeof this.editors[a]!="function"&&this.templateData[a]===void 0&&this.destroyEditor(a)},createEditor:function(a,c){var b=
this.templateData[a],i=this.createChangeIndicator(),k=d("<a />").html(XenForo.htmlspecialchars(a)+"&nbsp;").attr("href",b.link).attr("templateTitle",a).addClass(this.getInheritanceState(a)).prepend(i).click(d.context(this,"switchEditor")),e={},e={templateId:b.template_id,$styleId:d(n.createElement("input")).attr({type:"hidden",name:"styleidArray["+b.template_id+"]"}).val(b.style_id),$changeIndicator:i,$tab:d("<li />").append(k),$textarea:this.$templateTextarea.clone(!0).xfHide().attr({templateTitle:a,
name:"templateArray["+b.template_id+"]"}).removeAttr("id").val(b.template).keyup(d.context(this,"eTemplateChange")),$title:d(n.createElement("input")).attr({type:"hidden",name:"titleArray["+b.template_id+"]"}).val(b.title)};c?c.after(e.$tab):this.$editorTabs.append(e.$tab);this.getTextareaWrapper().append(e.$textarea).append(e.$title).append(e.$styleId);return e},updateEditor:function(a){var c=this.editors[a],b=this.templateData[a];if(c.templateId!=b.template_id){if(this.isPrimaryTemplate(a)){console.log("Primary template updated");
this.$templateId.val(b.template_id);var i=d("#TemplateDeleteButton");b.deleteLink?i.data("href",b.deleteLink).show():i.hide()}c.$tab.find("a").removeClass("master custom inherited").addClass(this.getInheritanceState(a));c.$textarea.attr("name","templateArray["+b.template_id+"]");c.$title.attr("name","titleArray["+b.template_id+"]");c.$styleId.attr("name","styleidArray["+b.template_id+"]");c.$styleId.val(b.style_id);c.templateId=b.template_id}this.handleTemplateChange(a)},destroyEditor:function(a){this.editors[a].$tab.remove();
this.editors[a].$textarea.remove();delete this.editors[a]},updateSaveActions:function(){this.useAjaxSave&&this.getSaveUrl("json")&&(this.$saveReloadButton.val(this.$saveReloadButton.data("ajaxvalue")).click(d.context(this,"saveAjax")),this.$saveExitButton.click(d.context(this,"saveExit")),this.$form.attr("action",this.getSaveUrl()))},saveAjax:function(a){var c,b;a&&a.preventDefault();this.toggleUnchangeFieldNames(this.$form.find('input[name="disable_modifications"]').is(":checked"));a=this.$form.serializeArray();
this.toggleUnchangeFieldNames(!0);b=this.getIncludeTitles();for(c=0;c<b.length;c++)XenForo.ajaxDataPush(a,"includeTitles[]",b[c]);XenForo.ajaxDataPush(a,"_TemplateEditorAjax",1);XenForo.ajax(this.getSaveUrl("json"),a,d.context(this,"ajaxSaveSuccess"));return!0},saveExit:function(){this.toggleUnchangeFieldNames(!1);return!0},toggleUnchangeFieldNames:function(a){var c,b;for(b in this.editors)if(typeof this.editors[b]!="function"){c=!1;if(this.isPrimaryTemplate(b)&&(d.trim(this.$templateTitle.strval())!=
this.$titleOriginal.strval()||this.$titleOriginal.strval()===""))c=!0;if(!this.isChanged(b)&&!c&&!d('input[name="disable_modifications"]').is(":checked"))c=this.editors[b].$textarea,a?(c.attr("name",c.attr("oName")),c.removeAttr("oName")):(c.attr("oName",c.attr("name")),c.removeAttr("name"))}},ajaxSaveSuccess:function(a,c){if(XenForo.hasResponseError(a))return!1;a.saveMessage&&XenForo.alert(a.saveMessage,"",1E3);this.focusBlurItem();var b=this.$titleOriginal.strval(),i=d.trim(this.$templateTitle.strval());
b!=i&&a.templates[i]!==void 0&&(this.editors[b].$tab.find("a").attr("templateTitle",i),this.editors[b].$title.attr("templateTitle",i),this.editors[b].$textarea.attr("templateTitle",i),this.$titleOriginal.val(i),this.editors[i]=this.editors[b],delete this.editors[b]);this.ajaxLoadSuccess(a,c)},getInheritanceState:function(a){if(this.templateData[a].style_id===void 0)return"master";switch(parseInt(this.templateData[a].style_id)){case 0:return"master";case parseInt(this.$styleId.val()):return"custom";
default:return"inherited"}},getIncludeTitles:function(){var a=[],c,b;this.$titleOriginal.strval()!=""&&a.push(this.$titleOriginal.strval());d.trim(this.$templateTitle.strval())!=""&&a.push(d.trim(this.$templateTitle.strval()));this.$templateTextarea.val().indexOf("{xen:pagenav")!=-1&&(a=this.titlePush("page_nav",a));if(c=this.$templateTextarea.val().match(this.requireRegex))for(b=0;b<c.length;b++)a=this.titlePush(c[b].replace(this.requireRegex,"$3"),a);return a},titlePush:function(a,c){c.push(a);
a.match(/\.css$/)||c.push(a+".css");return c},getTextareaWrapper:function(){if(this._$textareaWrapper===void 0)this.$templateTextarea.wrap('<div id="textareaWrapper" style="position:relative"></div>'),this._$textareaWrapper=d("#textareaWrapper").width(this.$templateTextarea.width());return this._$textareaWrapper},createChangeIndicator:function(){return d(n.createElement("span")).html("&bull;").css("visibility","hidden").addClass("changeIndicator")},setChanged:function(a,c){a.attr("changed")!=c&&(a.attr("changed",
c),a.css("visibility",c?"visible":"hidden"),a.parent().css("color",c?"darkred":"inherit"));return c},switchEditor:function(a){a=d(a.target).closest("a");a.closest("li").addClass("active").siblings().removeClass("active");d("textarea",this.getTextareaWrapper()).xfHide();this.editors[a.attr("templateTitle")].$textarea.xfShow().focus();this.$templateTextarea.is(":visible")?this.$primaryOnly.show():this.$primaryOnly.hide();return!1},eTitleChange:function(){k.clearTimeout(this.titleChangeTimeout);this.titleChangeTimeout=
k.setTimeout(d.context(function(){this.handleTitleChange()},this),500)},handleTitleChange:function(){var a=d.trim(this.$templateTitle.strval());d(".tabText",this.$templateTab).html(XenForo.htmlspecialchars(a)||this.$form.data("untitled").italics())},eTemplateChange:function(a){k.clearTimeout(this.templateChangeTimeout);var c=d(a.target).attr("templateTitle");this.templateChangeTimeout=k.setTimeout(d.context(function(){this.handleTemplateChange(c)},this),500)},isChanged:function(a){var c=this.editors[a].$textarea.strval().replace(/\r/g,
""),a=this.templateData[a].template.replace(/\r/g,"");return c!=a},isPrimaryTemplate:function(a){return a==this.$titleOriginal.strval()},handleTemplateChange:function(a){var c=this.isChanged(a);this.setChanged(this.editors[a].$changeIndicator,c);return c},getLoadUrl:function(a){return this.$form.data("loadurl")+(a?"."+a:"")},getSaveUrl:function(a){return this.$form.data("saveurl")+(a?"."+a:"")}};XenForo.register("form#templateEditor","XenForo.TemplateEditor")})(jQuery,this,document);
