/*
 * XenForo template_edit.min.js
 * Copyright 2010-2014 XenForo Ltd.
 * Released under the XenForo License Agreement: http://xenforo.com/license-agreement
 */
(function(d,j,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 d=a[0],b=a.data("undoStack");b||(b=[]);b.push([a.val(),d.selectionStart,d.selectionEnd]);a.data("undoStack",
b);c&&a.data("redoStack",[])},c=function(c){var b=c[0];c.data("undoStack");var d=c.data("redoStack");if(d&&d.length)a(c,!1),d=d.pop(),c.val(d[0]),b.selectionStart=d[1],b.selectionEnd=d[2],c.data("lastSelPosition",d[2])},b=function(c){var d=c.data("lastSelPosition"),b=!1;typeof d!="undefined"&&!isNaN(d)&&c[0].selectionEnd!=d&&(a(c,!0),b=!0);setTimeout(function(){c.data("lastSelPosition",c[0].selectionEnd)},0);return b},l=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,i=e.val(),g=i.substring(0,f),j=i.substring(h),m=!0;if(f!=h&&(h=i.substring(f,h),h.indexOf("\n")!=-1)){var m=!1,i=0,k=g.lastIndexOf("\n");k==-1?(h=g+h,i=g.length,g=""):(h=g.substring(k)+h,i=g.length-k,g=g.substring(0,k));b.shiftKey?(k=/(\n|^)(\t|[ ]{1,8})/g,h.match(k)&&(f-=1,i--),h=h.replace(k,"$1")):(h=h.replace(/(\n|^)/g,"$1\t"),f+=1,i++);a(e,!0);e.val(g+h+j);this.selectionStart=
f;this.selectionEnd=f+h.length-i}if(m&&!b.shiftKey)e.val(g+"\t"+j),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,i=e.val(),g=i.substring(0,f),j=i.substring(h),k=g.lastIndexOf("\n"),m=(k==-1?g:g.substring(k+1)).match(/^(\s+)/))b.preventDefault(),e.val(g+"\n"+m[1]+j),this.selectionStart=this.selectionEnd=f+m[1].length+1}else if(b.keyCode==83&&(b.ctrlKey||b.metaKey))b.preventDefault(),l.$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],l=this.createChangeIndicator(),j=d("<a />").html(a+"&nbsp;").attr("href",b.link).attr("templateTitle",a).addClass(this.getInheritanceState(a)).prepend(l).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:l,$tab:d("<li />").append(j),$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 l=d("#TemplateDeleteButton");b.deleteLink?l.data("href",b.deleteLink).show():l.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;for(templateTitle in this.editors)if(typeof this.editors[templateTitle]!="function"&&(c=!1,this.isPrimaryTemplate(templateTitle)&&this.$templateTitle.strval()!=
this.$titleOriginal.strval()&&(c=!0),!this.isChanged(templateTitle)&&!c&&!d('input[name="disable_modifications"]').is(":checked")))c=this.editors[templateTitle].$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(),d=this.$templateTitle.strval();b!=d&&a.templates[d]!==
void 0&&(this.editors[b].$tab.find("a").attr("templateTitle",d),this.editors[b].$title.attr("templateTitle",d),this.editors[b].$textarea.attr("templateTitle",d),this.$titleOriginal.val(d),this.editors[d]=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());this.$templateTitle.strval()!=""&&a.push(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(){j.clearTimeout(this.titleChangeTimeout);this.titleChangeTimeout=j.setTimeout(d.context(function(){this.handleTitleChange()},
this),500)},handleTitleChange:function(){var a=this.$templateTitle.strval();d(".tabText",this.$templateTab).html(a||this.$form.data("untitled").italics())},eTemplateChange:function(a){j.clearTimeout(this.templateChangeTimeout);var c=d(a.target).attr("templateTitle");this.templateChangeTimeout=j.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);
