summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorByron <byroncorrales@gmail.com>2011-10-17 21:52:27 -0600
committerByron <byroncorrales@gmail.com>2011-10-17 21:52:27 -0600
commitabfb34100092130963042b7fee833fff76e5326b (patch)
treee76ea7b8d06dd96bcd586c150540a124d75177a4
parenteda3047d53a6ec5e74bd5b56230cd15349d1ff4d (diff)
parent8e1d714137088b4b032d35d6e6a25657bfc7cdfc (diff)
downloadaskbot-abfb34100092130963042b7fee833fff76e5326b.tar.gz
askbot-abfb34100092130963042b7fee833fff76e5326b.tar.bz2
askbot-abfb34100092130963042b7fee833fff76e5326b.zip
Merge branch 'new-template' of https://github.com/ASKBOT/askbot-devel into askbot/new-template
-rw-r--r--askbot/skins/common/media/js/live_search.js11
-rw-r--r--askbot/skins/default/media/js/editor.js75
-rw-r--r--askbot/skins/default/media/js/i18n.js469
-rw-r--r--askbot/skins/default/media/js/less.min.js16
-rw-r--r--askbot/skins/default/media/js/live_search.js545
-rw-r--r--askbot/skins/default/media/js/post.js1665
-rw-r--r--askbot/skins/default/media/js/user.js185
-rw-r--r--askbot/skins/default/media/js/utils.js405
-rw-r--r--askbot/skins/default/templates/macros/macros.html23
-rw-r--r--askbot/skins/default/templates/question.html7
-rw-r--r--askbot/skins/default/templates/question/answer_author_info.html6
-rw-r--r--askbot/skins/default/templates/question/answer_card.html73
-rw-r--r--askbot/skins/default/templates/question/answer_comments.html10
-rw-r--r--askbot/skins/default/templates/question/answer_vote_buttons.html40
-rw-r--r--askbot/skins/default/templates/question/content.html26
-rw-r--r--askbot/skins/default/templates/question/new_answer_form.html57
-rw-r--r--askbot/skins/default/templates/question/new_answer_input.html37
-rw-r--r--askbot/skins/default/templates/question/question_author_info.html6
-rw-r--r--askbot/skins/default/templates/question/question_card.html37
-rw-r--r--askbot/skins/default/templates/question/question_comments.html10
-rw-r--r--askbot/skins/default/templates/question/question_tags.html7
21 files changed, 179 insertions, 3531 deletions
diff --git a/askbot/skins/common/media/js/live_search.js b/askbot/skins/common/media/js/live_search.js
index 1a46e338..18ad8b78 100644
--- a/askbot/skins/common/media/js/live_search.js
+++ b/askbot/skins/common/media/js/live_search.js
@@ -97,11 +97,10 @@ var liveSearch = function(){
var render_title = function(result){
return '<h2>' +
- '<a title="' + result['summary'] + '" ' +
- 'href="' +
+ '<a href="' +
askbot['urls']['question_url_template']
.replace('{{QuestionID}}', result['id']) +
- '">' +
+ '" onmouseover="load_question_body(this,' + result['id'] + ')">' +
result['title'] +
'</a>' +
'</h2>';
@@ -286,7 +285,7 @@ var liveSearch = function(){
};
var set_question_count = function(count_html){
- $('#question-count').html(count_html);
+ $('#questionCount').html(count_html);
};
var get_old_tags = function(container){
@@ -299,7 +298,7 @@ var liveSearch = function(){
};
var render_search_tags = function(tags){
- var search_tags = $('#search-tags');
+ var search_tags = $('#searchTags');
search_tags.children().remove();
var tags_html = '';
$.each(tags, function(idx, tag_name){
@@ -382,7 +381,7 @@ var liveSearch = function(){
};
var activate_search_tags = function(){
- var search_tags = $('#search-tags .tag-left');
+ var search_tags = $('#searchTags .tag-left');
$.each(search_tags, function(idx, element){
var tag = new Tag();
tag.decorate($(element));
diff --git a/askbot/skins/default/media/js/editor.js b/askbot/skins/default/media/js/editor.js
deleted file mode 100644
index f5b1e2af..00000000
--- a/askbot/skins/default/media/js/editor.js
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- jQuery TextAreaResizer plugin
- Created on 17th January 2008 by Ryan O'Dell
- Version 1.0.4
-*/(function($){var textarea,staticOffset;var iLastMousePos=0;var iMin=32;var grip;$.fn.TextAreaResizer=function(){return this.each(function(){textarea=$(this).addClass('processed'),staticOffset=null;$(this).wrap('<div class="resizable-textarea"><span></span></div>').parent().append($('<div class="grippie"></div>').bind("mousedown",{el:this},startDrag));var grippie=$('div.grippie',$(this).parent())[0];grippie.style.marginRight=(grippie.offsetWidth-$(this)[0].offsetWidth)+'px'})};function startDrag(e){textarea=$(e.data.el);textarea.blur();iLastMousePos=mousePosition(e).y;staticOffset=textarea.height()-iLastMousePos;textarea.css('opacity',0.25);$(document).mousemove(performDrag).mouseup(endDrag);return false}function performDrag(e){var iThisMousePos=mousePosition(e).y;var iMousePos=staticOffset+iThisMousePos;if(iLastMousePos>=(iThisMousePos)){iMousePos-=5}iLastMousePos=iThisMousePos;iMousePos=Math.max(iMin,iMousePos);textarea.height(iMousePos+'px');if(iMousePos<iMin){endDrag(e)}return false}function endDrag(e){$(document).unbind('mousemove',performDrag).unbind('mouseup',endDrag);textarea.css('opacity',1);textarea.focus();textarea=null;staticOffset=null;iLastMousePos=0}function mousePosition(e){return{x:e.clientX+document.documentElement.scrollLeft,y:e.clientY+document.documentElement.scrollTop}}})(jQuery);
-/*
- * TypeWatch 2.0 - Original by Denny Ferrassoli / Refactored by Charles Christolini
- * Copyright(c) 2007 Denny Ferrassoli - DennyDotNet.com
- * Coprright(c) 2008 Charles Christolini - BinaryPie.com
- * Dual licensed under the MIT and GPL licenses:
- * http://www.opensource.org/licenses/mit-license.php
- * http://www.gnu.org/licenses/gpl.html
-*/(function(jQuery){jQuery.fn.typeWatch=function(o){var options=jQuery.extend({wait:750,callback:function(){},highlight:true,captureLength:2},o);function checkElement(timer,override){var elTxt=jQuery(timer.el).val();if((elTxt.length>options.captureLength&&elTxt.toUpperCase()!=timer.text)||(override&&elTxt.length>options.captureLength)){timer.text=elTxt.toUpperCase();timer.cb(elTxt)}};function watchElement(elem){if(elem.type.toUpperCase()=="TEXT"||elem.nodeName.toUpperCase()=="TEXTAREA"){var timer={timer:null,text:jQuery(elem).val().toUpperCase(),cb:options.callback,el:elem,wait:options.wait};if(options.highlight){jQuery(elem).focus(function(){this.select()})}var startWatch=function(evt){var timerWait=timer.wait;var overrideBool=false;if(evt.keyCode==13&&this.type.toUpperCase()=="TEXT"){timerWait=1;overrideBool=true}var timerCallbackFx=function(){checkElement(timer,overrideBool)};clearTimeout(timer.timer);timer.timer=setTimeout(timerCallbackFx,timerWait)};jQuery(elem).keydown(startWatch)}};return this.each(function(index){watchElement(this)})}})(jQuery);
-/*
-Ajax upload
-*/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}});
-/**
- * Upload call. Used only once in the wmd file upload
- * this is "tightly coupled" with the wmd file uploader
- * @param {Object} jquery object imageUrl - where the
- * uploaded url must be inserted on successful upload
- * @param {Function} handler that is run upon change
- * of the file upload field
- */
-function ajaxFileUpload(imageUrl, startUploadHandler)
-{
- $("#loading").ajaxStart(function(){
- $(this).show();
- }).ajaxComplete(function(){
- $(this).hide();
- });
-
- $("#upload").ajaxStart(function(){
- $(this).hide();
- }).ajaxComplete(function(){
- $(this).show();
- });
-
- $.ajaxFileUpload
- (
- {
- url: askbot['urls']['upload'],
- secureuri:false,
- fileElementId:'file-upload',
- dataType: 'xml',
- success: function (data, status)
- {
- var fileURL = $(data).find('file_url').text();
- var error = $(data).find('error').text();
- if(error != ''){
- alert(error);
- if (startUploadHandler){
- /* re-install this as the upload extension
- * will remove the handler to prevent double uploading */
- $('#file-upload').change(startUploadHandler);
- }
- }else{
- imageUrl.attr('value', fileURL);
- }
-
- },
- error: function (data, status, e)
- {
- alert(e);
- if (startUploadHandler){
- /* re-install this as the upload extension
- * will remove the handler to prevent double uploading */
- $('#file-upload').change(startUploadHandler);
- }
- }
- }
- )
-
- return false;
-}
diff --git a/askbot/skins/default/media/js/i18n.js b/askbot/skins/default/media/js/i18n.js
deleted file mode 100644
index 192d335b..00000000
--- a/askbot/skins/default/media/js/i18n.js
+++ /dev/null
@@ -1,469 +0,0 @@
-//var i18nLang;
-var i18nZh = {
- 'insufficient privilege':'用户权限不在操作范围',
- 'cannot pick own answer as best':'不能设置自己的回答为最佳答案',
- 'anonymous users cannot select favorite questions':'匿名用户不能收藏问题,请先',
- 'please login':'注册或者登录',
- 'daily vote cap exhausted':'对不起,您已用完今日所有的投票。',
- 'please confirm offensive':"确定要归类该帖为广告、人身攻击、恶意言论吗?",
- 'anonymous users cannot flag offensive posts':'匿名用户不能操作,请先',
- 'cannot flag message as offensive twice':'不能重复操作。',
- 'flag offensive cap exhausted':'对不起,您已用完今日所有的5次‘水帖’操作。',
- 'confirm delete':"确定要删除/撤销删除该帖吗?",
- 'anonymous users cannot delete/undelete':"匿名用户不能删除或撤销删除帖子",
- 'post recovered':"操作成功!该帖子已被恢复。",
- 'post deleted':"操作成功!该帖子已删除。",
- 'add comment':'添加评论',
- 'delete this comment':'删除此评论',
- 'add a comment':"添加评论",
- 'comments':"评论",
- 'confirm delete comment':"真要删除此评论吗?",
- '{0} characters left': '还可写{0}字符',
- 'click to close':'点击消息框关闭',
- 'loading...':'读取中...',
- 'tags cannot be empty':'标签不能为空。',
- 'content cannot be empty':'内容不能为空。',
- 'content minchars': '请输入至少 {0} 字符。',
- 'please enter title':'请输入标题。',
- 'title minchars':"请输入至少 {0} 字符。",
- 'delete':'删除',
- 'undelete':'取消',
- 'bold':'粗体',
- 'italic':'斜体',
- 'link':'超链接',
- 'quote':'引用',
- 'preformatted text':'代码',
- 'image':'图片',
- 'numbered list':'数字编号列表',
- 'bulleted list':'项目符号列表',
- 'heading':'标题',
- 'horizontal bar':'水平线',
- 'undo':'撤销',
- 'redo':'重做',
- 'enter image url':'<b>输入图片地址</b></p><p>示例:<br />http://www.example.com/image.jpg \"我的截图\"',
- 'enter url':'<b>输入Web地址</b></p><p>示例:<br />http://www.cnprog.com/ \"我的网站\"</p>"',
- 'upload image':'或者上传本地图片:'
-};
-
-var i18nZhtw = {
- 'insufficient privilege':'權限不足',
- 'cannot pick own answer as best':'不能蔽掃自珍',
- 'anonymous users cannot select favorite questions':'匿名用戶不能收藏問題',
- 'please login':'請先登錄',
- 'daily vote cap exhausted':'對不起,您已用完今日所有的投票。',
- 'please confirm offensive':"確定要歸類該帖為廣告、人身攻擊、惡意言論嗎?",
- 'anonymous users cannot flag offensive posts':'匿名用戶不能操作',
- 'cannot flag message as offensive twice':'不能重複操作。',
- 'flag offensive cap exhausted':'對不起,您已用完今日所有的5次『水帖』操作。',
- 'confirm delete':"確定刪除",
- 'anonymous users cannot delete/undelete':"匿名用戶不能刪除或恢復帖子",
- 'post recovered':"操作成功!該帖子已被恢複。",
- 'post deleted':"操作成功!該帖子已刪除。",
- 'add comment':'添加評論',
- 'delete this comment':'刪除此評論',
- 'add a comment':"添加評論",
- 'comments':"評論",
- 'confirm delete comment':"刪除評論確認",
- '{0} characters left': '還可寫{0}字',
- 'click to close':'點擊消息框關閉',
- 'loading...':'讀取中...',
- 'tags cannot be empty':'標籤不能為空白',
- 'content cannot be empty':'內容不能為空白',
- 'content minchars': '請輸入至少 {0} 字符。',
- 'please enter title':'請輸入標題。',
- 'title minchars':"請輸入至少 {0} 字符。",
- 'delete':'刪除',
- 'undelete':'取消',
- 'bold':'粗體',
- 'italic':'斜體',
- 'link':'超連接',
- 'quote':'引用',
- 'preformatted text':'代碼',
- 'image':'圖片',
- 'numbered list':'數字編號列表',
- 'bulleted list':'項目符號列表',
- 'heading':'標題',
- 'horizontal bar':'水平線',
- 'undo':'撤銷',
- 'redo':'重做',
- 'enter image url':'<b>輸入圖片地址</b></p><p>示例:<br />http://www.example.com/image.jpg \"我的截圖\"',
- 'enter url':'<b>輸入Web地址</b></p><p>示例:<br />http://www.cnprog.com/ \"我的網站\"</p>"',
- 'upload image':'或者上傳本地圖片:'
-};
-
-
-var i18nEn = {
- "anonymous users cannot vote": "sorry, anonymous users cannot vote ",
- 'tags cannot be empty':'please enter at least one tag',
- 'anonymous users cannot select favorite questions':'sorry, anonymous users cannot select favorite questions ',
- 'upload image':'Upload image:',
- 'enter image url':'enter URL of the image, e.g. http://www.example.com/image.jpg or upload an image file',
- 'enter url':'enter Web address, e.g. http://www.example.com \"page title\"',
- 'upload file attachment':'Please choose and upload a file:',
- 'daily vote cap exhausted':'sorry, you\'ve used up todays vote cap',
- 'cannot pick own answer as best':'sorry, you cannot accept your own answer',
- 'please confirm offensive':'are you sure this post is offensive, contains spam, advertising, malicious remarks, etc.?',
- 'flag offensive cap exhausted':'sorry, you\'ve used up todays cap of flagging offensive messages ',
- 'confirm delete':'are you sure you want to delete this?',
- 'anonymous users cannot delete/undelete':'sorry, anonymous users cannot delete or undelete posts',
- 'post recovered':'your post is now restored!',
- 'post deleted':'your post has been deleted',
- 'confirm delete comment':'do you really want to delete this comment?',
- 'content minchars': 'please enter more than {0} characters',
- 'title minchars':"please enter at least {0} characters",
- 'characters':'characters left',
- 'cannot flag message as offensive twice':'cannot flag message as offensive twice ',
- 'edit':'edit',
- 'click to edit this comment':'click to edit this comment',
- 'confirm abandon comment':'Are you sure you do not want to post this comment?',
- 'save comment': 'save comment',
- 'enter more characters': 'please enter at least {0} more characters',
- 'Follow': 'Follow',
- '<b>Following</b><b class="unfollow">Unfollow</b>': '<b>Following</b><b class="unfollow">Unfollow</b>',
-};
-
-var i18nFi = {
- "anonymous users cannot vote": "kirjaudu sisään, jotta voit käyttää tätä ominaisuutta ",
- 'tags cannot be empty':'anna vähintään yksi tagi',
- 'anonymous users cannot select favorite questions':'kirjaudu sisään, jotta voit käyttää tätä ominaisuutta',
- 'upload image':'Lähetä kuva:',
- 'enter image url':'Anna kuvan URL-osoite, esim. http://www.example.com/image.jpg \"kuvan otsikko\"',
- 'enter url':'Anna URL-osoite, esim. http://www.example.com \"sivun otsikko\"',
- 'daily vote cap exhausted':'olet käyttänyt tämän päivän osalta äänesi',
- 'cannot pick own answer as best':'et voi hyväksyä omaa vastaustasi parhaaksi',
- 'please confirm offensive':'oletko varma, että tämä on roskaposti, loukkaava tai muuta hyväksymätöntä?',
- 'flag offensive cap exhausted':'olet käyttänyt tämän päivän merkkausmäärät ',
- 'confirm delete':'oletko varma, että haluat poistaa tämän?',
- 'anonymous users cannot delete/undelete':'kirjaudu sisään, jotta voit käyttää tätä ominaisuutta',
- 'post recovered':'postauksesi on palautettu!',
- 'post deleted':'postauksesi on poistettu',
- 'confirm delete comment':'oletko varma, että haluat poistaa tämän kommentin?',
- 'content minchars': 'syötä vähintään {0} merkkiä',
- 'title minchars':"syötä vähintään {0} merkkiä",
- '{0} characters left': '{0} merkkiä jäljellä',
- 'cannot flag message as offensive twice':'ei voi merkata kahta kertaa '
-};
-
-var i18nTr = {
- "anonymous users cannot vote":"üye girişi yapmadan oy kullanamazsınız",
- 'insufficient privilege':'buna yetkiniz yoktur',
- 'cannot pick own answer as best':'en cevap olarak kendi cevabınızı seçemezsiniz',
- 'anonymous users cannot select favorite questions':'üye girişi yapmadan favori seçemezsiniz',
- 'please login':'lütfen üye girişi yapınız',
- 'daily vote cap exhausted':'bugünlük oy verme kotanız doldu',
- 'please confirm offensive':"şikayetinizi onaylayın",
- 'anonymous users cannot flag offensive posts':'üye girişi yapmadan şikayet gönderemezsiniz',
- 'cannot flag message as offensive twice':'şikayet mesajı olarak iki kez işaretlemelisiniz',
- 'flag offensive cap exhausted':'şikayet kotası aşıldı',
- 'confirm delete':"Bunu silmek istediğinizden emin misiniz?",
- 'anonymous users cannot delete/undelete':"üye girişi yapmadan yazı silemez yada geri alamazsınız",
- 'post recovered':"yazı geri alındı",
- 'post deleted':"yazı silindi",
- 'add comment':'yorum ekle',
- 'delete this comment':'bu yorumu sil',
- 'add a comment':"yorum ekle",
- 'comments':"yorumlar",
- 'confirm delete comment':"yorumu silmek istediğinizden emin misiniz?",
- '{0} characters left': 'yazılabilir {0} karakter eksik',
- 'click to close':'kapatmak için tıklayın',
- 'loading...':'yükleniyor...',
- 'tags cannot be empty':'etiketler boş olamaz',
- 'content cannot be empty':'içerik boş olamaz',
- 'content minchars': 'Lütfen en az (0) karakter girin',
- 'please enter title':'lütfen bir başlık yazın',
- 'title minchars':"Lütfen en az (0) karakter girin",
- 'delete':'sil',
- 'undelete':'geri al',
- 'bold': 'kalın',
- 'italic':'italik',
- 'link':'link',
- 'quote':'alıntı',
- 'preformatted text':'hazır metin',
- 'image':'resimler',
- 'numbered list':'numaralı liste',
- 'bulleted list':'işaretli liste',
- 'heading':'Başlık',
- 'horizontal bar':'yatay bar',
- 'undo':'geri',
- 'redo':'yeniden',
- 'enter image url':'örnek resmin URLsini girin: <br />http://www.example.com/image.jpg \"resim başlığı\"',
- 'enter url':'web adresini girin: <br />http://www.cnprog.com/ \"başlık bağlantısı\"</p>"',
- 'upload image':'resim yükle:'
-};
-
-var i18nEs = {
- "anonymous users cannot vote":"usuarios anónimos no pueden votar",
- 'insufficient privilege':'privilegio insuficiente',
- 'cannot pick own answer as best':'no puede escoger su propia respuesta como la mejor',
- 'anonymous users cannot select favorite questions':'usuarios anonimos no pueden seleccionar',
- 'please login':'por favor inicie sesión',
- 'daily vote cap exhausted':'cuota de votos diarios excedida',
- 'please confirm offensive':"por favor confirme ofensiva",
- 'anonymous users cannot flag offensive posts':'usuarios anónimos no pueden marcar publicaciones como ofensivas',
- 'cannot flag message as offensive twice':'no puede marcar mensaje como ofensivo dos veces',
- 'flag offensive cap exhausted':'cuota para marcar ofensivas ha sido excedida',
- 'confirm delete':"¿Está seguro que desea borrar esto?",
- 'anonymous users cannot delete/undelete':"usuarios anónimos no pueden borrar o recuperar publicaciones",
- 'post recovered':"publicación recuperada",
- 'post deleted':"publicación borrada。",
- 'add comment':'agregar comentario',
- 'delete this comment':'borrar este comentario',
- 'add a comment':"agregar comentarios",
- 'comments':"comentarios",
- 'confirm delete comment':"¿Realmente desea borrar este comentario?",
- '{0} characters left': '{0} caracteres faltantes',
- 'click to close':'haga click para cerrar',
- 'loading...':'cargando...',
- 'tags cannot be empty':'las etiquetas no pueden estar vacías',
- 'content cannot be empty':'el contenido no puede estar vacío',
- 'content minchars': 'por favor introduzca mas de {0} caracteres',
- 'please enter title':'por favor ingrese un título',
- 'title minchars':"por favor introduzca al menos {0} caracteres",
- 'delete':'borrar',
- 'undelete': 'recuperar',
- 'bold': 'negrita',
- 'italic':'cursiva',
- 'link':'enlace',
- 'quote':'citar',
- 'preformatted text':'texto preformateado',
- 'image':'imagen',
- 'numbered list':'lista numerada',
- 'bulleted list':'lista no numerada',
- 'heading':'标题',
- 'horizontal bar':'barra horizontal',
- 'undo':'deshacer',
- 'redo':'rehacer',
- 'enter image url':'introduzca la URL de la imagen, por ejemplo:<br />http://www.example.com/image.jpg \"titulo de imagen\"',
- 'enter url':'introduzca direcciones web, ejemplo:<br />http://www.cnprog.com/ \"titulo del enlace\"</p>"',
- 'upload image':'cargar imagen:'
-};
-
-var i18nDe = {
- "anonymous users cannot vote":"Gastbenutzer können nicht abstimmen ",
- 'add a comment': 'Kommentar hinzufügen',
- 'add comment': 'OK',
- 'anonymous users cannot delete/undelete': 'Gastbenutzer können Beiträge nicht löschen oder wiederherstellen',
- 'anonymous users cannot flag offensive posts': 'Gastbenutzer können Beiträge nicht melden',
- 'anonymous users cannot select favorite questions': 'Gastbenutzer können keine Fragen als Favoriten markieren',
- 'bold': 'Fett',
- 'bulleted list': 'Liste',
- '{0} characters left': '{0} characters left',
- 'cannot flag message as offensive twice': 'Beiträge können nicht doppelt gemeldet werden',
- 'cannot pick own answer as best': 'Eigene Antworten können nicht als die korrekte akzeptiert werden',
- 'click to close': 'Schließen mit Klick',
- 'comments': 'Kommentare',
- 'confirm delete': 'Löschen bestätigen',
- 'confirm delete comment': 'Löschen des Kommentars bestätigen',
- 'content cannot be empty': 'Inhalt darf nicht leer sein',
- 'content minchars': 'Bitte mindestens {0} Zeichen eingeben',
- 'daily vote cap exhausted': 'Tägliches Abstimmungslimit erreicht',
- 'delete': 'löschen',
- 'delete this comment': 'Diesen Kommentar löschen',
- 'enter image url': 'Bild-URL eingeben, zum Beispiel <br />http://www.ihredomain.de/bildname.jpg',
- 'enter url': 'URL eingeben, zum Beispiel <br />http://www.askbot.org/ </p>',
- 'flag offensive cap exhausted': 'Tägliches Limit zum Melden von Beiträgen erreicht',
- 'heading': 'Titel',
- 'horizontal bar': 'horizontaler Balken',
- 'image': 'Bild',
- 'insufficient privilege': 'nicht genügend Rechte',
- 'italic': 'Kursiv',
- 'link': 'Link',
- 'loading...': 'Lade...',
- 'numbered list': 'Nummerierte Liste',
- 'please confirm offensive': 'Bitte beleidigenden/regelwidrigen Beitrag bestätigen',
- 'please enter title': 'Bitte Titel eingeben',
- 'please login': 'Bitte einloggen',
- 'post deleted': 'Beitrag gelöscht',
- 'post recovered': 'Beitrag wiederhergestellt',
- 'preformatted text': 'Vorformatierter Text',
- 'quote': 'Zitat',
- 'redo': 'Wiederholen',
- 'tags cannot be empty': 'Tags dürfen nicht leer sein',
- 'title minchars': 'Bitte mindestens {0} Zeichen eingeben',
- 'undelete': 'wiederherstellen',
- 'undo': 'Rückgängig',
- 'upload image': 'Bild hochladen'
-};
-
-
-var i18nRu = {
- "anonymous users cannot vote": "Извините, но для того чтобы голосовать, ",
- 'add a comment': 'добавить комментарий',
- 'add comment': 'добавить комментарий',
- 'save comment': 'сохранить комментарий',
- 'anonymous users cannot delete/undelete': 'неавторизированные пользователи не могут восстанавливать и удалять сообщения ',
- 'anonymous users cannot flag offensive posts': 'Извините, но для того чтобы пожаловаться на сообщение, ',
- 'anonymous users cannot select favorite questions': 'Извините, но для того чтобы добавть вопрос в закладки, ',
- 'Are you sure you want to remove your {provider} login?': 'Вы действительно хотите удалить логин через {provider}?',
- 'bold': 'жирный',
- 'bulleted list': 'маркированный список',
- 'cancel': 'cancel',
- '{0} characters left': 'осталось место для {0} символов',
- 'cannot flag message as offensive twice': 'нельзя отметить сообщение как спам два раза',
- 'cannot pick own answer as best': 'Извините, выбрать собственный ответ в качестве лучшего не разрешается',
- 'Change password': 'Изменить пароль',
- 'Change your {provider} password': 'Измените Ваш пароль для {provider}',
- 'click to close': 'нажмите, что бы закрыть',
- 'Create a password for {provider}': 'Создать пароль для {provider}',
- 'Create password': 'Создать пароль',
- 'Create a password-protected account': 'Создать аккаунт, защищенный паролем',
- 'comments': 'комментарии',
- 'confirm abandon comment': '',
- 'Connect your {provider_name} account to {site}': 'Соедините {site} с Вашим аккаунтом от {provider_name}',
- 'confirm delete': 'Удалить?',
- 'confirm delete comment': 'Удалить комментарий?',
- 'content cannot be empty': 'пожалуйста, добавьте содержание',
- 'content minchars': 'содержание должно быть более {0} символов',
- 'daily vote cap exhausted': 'исчерпан доступный на сегодня лимит голосований',
- 'delete': 'удалить',
- 'save tags': 'запомнить теги',
- 'delete this comment': 'удалить этот комментарий',
- 'Delete this notification?': 'Удалить это извещение?',
- 'Delete these notifications?': 'Удалить эти извещения?',
- 'enter image url': 'введите url изображения, например:<br /> http://www.domain.ru/kartinka.gif',
- 'enter url': 'введите url, например:<br />http://www.domain.ru/ </p>',
- 'flag offensive cap exhausted': 'исчерпан доступный на сегодня лимит сообщений о спаме',
- 'file name': 'название файла',
- 'heading': 'заголовок',
- 'horizontal bar': 'горизонтальная полоса',
- 'image': 'изображение',
- 'image description': 'описание изображения',
- 'insufficient privilege': 'недостаточно прав',
- 'italic': 'курсив',
- 'link': 'ссылка',
- 'link text': 'текст ссылки',
- 'loading...': 'загрузка...',
- 'passwords do not match': 'пароли не совпадают',
- 'numbered list': 'пронумерованный список',
- 'Please add one or more login methods.': 'Пожалуйста, добавьте хотя бы один постоянный метод для авторизации.',
- 'please confirm offensive': 'Вы уверены что это сообщение неуместно?',
- 'please enter title': 'пожалуйста, введите заголовок',
- 'Please enter your {token_name}, then proceed': 'Чтобы продолжить, пожалуйста введите {token_name}',
- 'Please select at least one item': 'Пожалуйста, отметьте хотя бы одно извещение',
- 'enter more characters': 'недостаточно символов, пожалуйста, добавьте ещё {0}',
- 'please login': 'введите логин',
- 'post deleted': 'сообщение удалено',
- 'post recovered': 'восстановить сообщение',
- 'preformatted text': 'форматирование текста',
- 'quote': 'цитата',
- 'redo': 'повторить',
- 'see questions tagged \'{tag}\'': 'смотрите вопросы, помеченные \'{tag}\'',
- 'Show/change current login methods': 'Просмотреть, изменить существующие методы авторизации.',
- 'tags cannot be empty': 'введите теги',
- 'title minchars': 'заголовок должен быть более {0} символов',
- 'undelete': 'восстановить',
- 'click to edit this comment': 'нажмите здесь, чтобы отредактировать этот комментарий',
- 'edit': 'редактировать',
- 'undo': 'отменить',
- 'upload image': 'загрузить изображение',
- 'upload file attachment': 'загрузить файл',
- 'You don\'t have a method to log in right now, please add one or more by clicking any of the icons below.': 'У Вас сейчас нет постоянного метода авторизации, пожалуйста выберите хотя бы один, нажав на любую из предложеных ниже кнопок.'
-};
-
-var i18nFr = {
- "anonymous users cannot vote":"les utilisateurs anonyment ne peuvent pas voter ",
- 'add a comment': 'Ajouter un commentaire',
- 'add comment': 'OK',
- 'anonymous users cannot delete/undelete': 'Les utilisateurs anonymes ne peuvent pas supprimer/restaurer',
- 'anonymous users cannot flag offensive posts': 'Les utilisateurs anonymes ne peuvent pas signaler les messages à contenu abusif',
- 'anonymous users cannot select favorite questions': 'Les utilisateurs anonymes ne peuvent pas sélectionner leurs questions favorites',
- 'bold': 'gras',
- 'bulleted list': 'liste',
- '{0} characters left': '{0} characters left',
- 'cannot flag message as offensive twice': 'Vous ne pouvez pas signaler deux fois un message à contenu abusif',
- 'cannot pick own answer as best': 'Vous ne pouvez pas désigner une de vos propres réponses comme étant la meilleure réponse',
- 'click to close': 'cliquez pour fermer',
- 'comments': 'commentaires',
- 'confirm delete': 'Confirmer la suppression',
- 'confirm delete comment': 'Confirmer la suppression du commentaire',
- 'content cannot be empty': 'Le contenu ne doit pas être vide',
- 'content minchars': 'Veuillez saisir au moins {0} caractères',
- 'daily vote cap exhausted': 'Votre quota journalier de votes est atteint',
- 'delete': 'supprimer',
- 'delete this comment': 'supprimer ce commentaire',
- 'enter image url': 'Veuillez saisir une URL menant à une image, par exemple <br />http://www.votre-domaine.com/nom-image.jpg',
- 'enter url': 'Entrez une URL, par exemple <br />http://www.askbot.org/ </p>',
- 'flag offensive cap exhausted': 'Votre quota journalier de signalements de contenus abusifs a été atteint',
- 'heading': 'Titre',
- 'horizontal bar': 'Barre horizontale',
- 'image': 'Image',
- 'insufficient privilege': 'Privilèges insuffisants',
- 'italic': 'italique',
- 'link': 'lien',
- 'loading...': 'Chargement en cours...',
- 'numbered list': 'liste numérotée',
- 'please confirm offensive': 'Veuillez confirmer que le contenu est abusif',
- 'please enter title': 'Veuillez saisir un titre',
- 'please login': 'Veuillez vous authentifier',
- 'post deleted': 'Message supprimé',
- 'post recovered': 'Message restauré',
- 'preformatted text': 'Texte préformaté',
- 'quote': 'Citer',
- 'redo': 'Rétablir',
- 'tags cannot be empty': 'Les mots-clés ne doivent pas être vides',
- 'title minchars': 'Veuillez saisir au moins {0} caractères',
- 'undelete': 'Restaurer',
- 'undo': 'Annuler',
- 'upload image': 'Charger une image'
-};
-
-var i18nIt = {
- "anonymous users cannot vote":"Gli utenti anonimi non possono votare ",
- 'add a comment': 'Aggiungi un commento',
- 'add comment': 'OK',
- 'anonymous users cannot delete/undelete': 'Gli utenti anonimi non possono cancellare/annullare la cancellazione',
- 'anonymous users cannot flag offensive posts': 'Gli utenti anonimi non possono flaggare come offensivo questo post',
- 'anonymous users cannot select favorite questions': 'Gli utenti anonimi non possono aggiungere domande ai preferiti',
- 'bold': 'grassetto',
- 'bulleted list': 'Lista',
- 'cannot flag message as offensive twice': 'non è possibile flaggare come offensivo più di una volta ',
- 'cannot pick own answer as best': 'non è possibile assegnare come miglior risposta ad una propria domanda una propria risposta',
- '{0} characters left': '{0} caratteri rimanenti',
- 'click to close': 'clicca per chiudere',
- 'comments': 'commenti',
- 'confirm delete': 'conferma la cancellazione',
- 'confirm delete comment': 'Vuoi davvero cancellare il commento?',
- 'content cannot be empty': 'il contenuto non può essere vuoto',
- 'content minchars': 'per favore inserisci più di {0} caratteri',
- 'daily vote cap exhausted': 'Spiacente, hai raggiunto il limite odierno massimo di voti',
- 'delete': 'elimina',
- 'delete this comment': 'Elimina questo commento',
- 'enter image url': 'inserisci l\'URL dell\'immagine, es. http://www.example.com/immagine.jpg \"titolo immagine\"',
- 'enter url': 'inserisci l\'indirizzo web, e.g. <br />http://www.askbot.org/ </p>',
- 'flag offensive cap exhausted': 'spiacente, hai raggiunto il limite odierno massimo di flag offensivi ',
- 'heading': 'Titolo',
- 'horizontal bar': 'barra orizzontale',
- 'image': 'Immagine',
- 'insufficient privilege': 'privilegi non sufficienti',
- 'italic': 'corsivo',
- 'link': 'Link',
- 'loading...': 'Caricamento...',
- 'numbered list': 'Lista numerata',
- 'please confirm offensive': 'sei certo che questo post sia offensivo, contenga spam, pubblicità, osservazioni poco idonee, ecc.?',
- 'please enter title': 'Per favore inserisci il titolo',
- 'please login': 'Per favore effettua il login',
- 'post deleted': 'Post eliminato',
- 'post recovered': 'Post recuperato',
- 'preformatted text': 'Testo preformattato',
- 'quote': 'cita',
- 'redo': 'Esegui nuovamente',
- 'tags cannot be empty': 'Il campo Tags non può essere vuoto',
- 'title minchars': 'per favore inserisci almeno {0} caratteri',
- 'undelete': 'elimina',
- 'undo': 'annulla',
- 'upload image': 'carica immagine'
-};
-
-var i18n = {
- 'en':i18nEn,
- 'zh-cn':i18nZh,
- 'es':i18nEs,
- 'tr':i18nTr,
- 'de':i18nDe,
- 'ru':i18nRu,
- 'fr':i18nFr,
- 'it':i18nIt,
- 'zh-tw':i18nZhtw
-};
-
-var i18n_dict = i18n[i18nLang];
diff --git a/askbot/skins/default/media/js/less.min.js b/askbot/skins/default/media/js/less.min.js
deleted file mode 100644
index 6e4d5cff..00000000
--- a/askbot/skins/default/media/js/less.min.js
+++ /dev/null
@@ -1,16 +0,0 @@
-//
-// LESS - Leaner CSS v1.1.3
-// http://lesscss.org
-//
-// Copyright (c) 2009-2011, Alexis Sellier
-// Licensed under the Apache 2.0 License.
-//
-//
-// LESS - Leaner CSS v1.1.3
-// http://lesscss.org
-//
-// Copyright (c) 2009-2011, Alexis Sellier
-// Licensed under the Apache 2.0 License.
-//
-(function(a,b){function v(a,b){var c="less-error-message:"+p(b),e=["<ul>",'<li><label>[-1]</label><pre class="ctx">{0}</pre></li>',"<li><label>[0]</label><pre>{current}</pre></li>",'<li><label>[1]</label><pre class="ctx">{2}</pre></li>',"</ul>"].join("\n"),f=document.createElement("div"),g,h;f.id=c,f.className="less-error-message",h="<h3>"+(a.message||"There is an error in your .less file")+"</h3>"+'<p><a href="'+b+'">'+b+"</a> ",a.extract&&(h+="on line "+a.line+", column "+(a.column+1)+":</p>"+e.replace(/\[(-?\d)\]/g,function(b,c){return parseInt(a.line)+parseInt(c)||""}).replace(/\{(\d)\}/g,function(b,c){return a.extract[parseInt(c)]||""}).replace(/\{current\}/,a.extract[1].slice(0,a.column)+'<span class="error">'+a.extract[1].slice(a.column)+"</span>")),f.innerHTML=h,q([".less-error-message ul, .less-error-message li {","list-style-type: none;","margin-right: 15px;","padding: 4px 0;","margin: 0;","}",".less-error-message label {","font-size: 12px;","margin-right: 15px;","padding: 4px 0;","color: #cc7777;","}",".less-error-message pre {","color: #ee4444;","padding: 4px 0;","margin: 0;","display: inline-block;","}",".less-error-message pre.ctx {","color: #dd4444;","}",".less-error-message h3 {","font-size: 20px;","font-weight: bold;","padding: 15px 0 5px 0;","margin: 0;","}",".less-error-message a {","color: #10a","}",".less-error-message .error {","color: red;","font-weight: bold;","padding-bottom: 2px;","border-bottom: 1px dashed red;","}"].join("\n"),{title:"error-message"}),f.style.cssText=["font-family: Arial, sans-serif","border: 1px solid #e00","background-color: #eee","border-radius: 5px","-webkit-border-radius: 5px","-moz-border-radius: 5px","color: #e00","padding: 15px","margin-bottom: 15px"].join(";"),d.env=="development"&&(g=setInterval(function(){document.body&&(document.getElementById(c)?document.body.replaceChild(f,document.getElementById(c)):document.body.insertBefore(f,document.body.firstChild),clearInterval(g))},10))}function u(a){d.env=="development"&&typeof console!="undefined"&&console.log("less: "+a)}function t(a){return a&&a.parentNode.removeChild(a)}function s(){if(a.XMLHttpRequest)return new XMLHttpRequest;try{return new ActiveXObject("MSXML2.XMLHTTP.3.0")}catch(b){u("browser doesn't support AJAX.");return null}}function r(a,b,c,e){function i(b,c,d){b.status>=200&&b.status<300?c(b.responseText,b.getResponseHeader("Last-Modified")):typeof d=="function"&&d(b.status,a)}var f=s(),h=g?!1:d.async;typeof f.overrideMimeType=="function"&&f.overrideMimeType("text/css"),f.open("GET",a,h),f.setRequestHeader("Accept",b||"text/x-less, text/css; q=0.9, */*; q=0.5"),f.send(null),g?f.status===0?c(f.responseText):e(f.status,a):h?f.onreadystatechange=function(){f.readyState==4&&i(f,c,e)}:i(f,c,e)}function q(a,b,c){var d,e=b.href?b.href.replace(/\?.*$/,""):"",f="less:"+(b.title||p(e));(d=document.getElementById(f))===null&&(d=document.createElement("style"),d.type="text/css",d.media=b.media||"screen",d.id=f,document.getElementsByTagName("head")[0].appendChild(d));if(d.styleSheet)try{d.styleSheet.cssText=a}catch(g){throw new Error("Couldn't reassign styleSheet.cssText.")}else(function(a){d.childNodes.length>0?d.firstChild.nodeValue!==a.nodeValue&&d.replaceChild(a,d.firstChild):d.appendChild(a)})(document.createTextNode(a));c&&h&&(u("saving "+e+" to cache."),h.setItem(e,a),h.setItem(e+":timestamp",c))}function p(a){return a.replace(/^[a-z]+:\/\/?[^\/]+/,"").replace(/^\//,"").replace(/\?.*$/,"").replace(/\.[^\.\/]+$/,"").replace(/[^\.\w-]+/g,"-").replace(/\./g,":")}function o(b,c,e,f){var g=a.location.href.replace(/[#?].*$/,""),i=b.href.replace(/\?.*$/,""),j=h&&h.getItem(i),k=h&&h.getItem(i+":timestamp"),l={css:j,timestamp:k};/^(https?|file):/.test(i)||(i.charAt(0)=="/"?i=a.location.protocol+"//"+a.location.host+i:i=g.slice(0,g.lastIndexOf("/")+1)+i),r(b.href,b.type,function(a,g){if(!e&&l&&g&&(new Date(g)).valueOf()===(new Date(l.timestamp)).valueOf())q(l.css,b),c(null,b,{local:!0,remaining:f});else try{(new d.Parser({optimization:d.optimization,paths:[i.replace(/[\w\.-]+$/,"")],mime:b.type})).parse(a,function(a,d){if(a)return v(a,i);try{c(d,b,{local:!1,lastModified:g,remaining:f}),t(document.getElementById("less-error-message:"+p(i)))}catch(a){v(a,i)}})}catch(h){v(h,i)}},function(a,b){throw new Error("Couldn't load "+b+" ("+a+")")})}function n(a,b){for(var c=0;c<d.sheets.length;c++)o(d.sheets[c],a,b,d.sheets.length-(c+1))}function m(){var a=document.getElementsByTagName("style");for(var b=0;b<a.length;b++)a[b].type.match(k)&&(new d.Parser).parse(a[b].innerHTML||"",function(c,d){a[b].type="text/css",a[b].innerHTML=d.toCSS()})}function c(b){return a.less[b.split("/")[1]]}Array.isArray||(Array.isArray=function(a){return Object.prototype.toString.call(a)==="[object Array]"||a instanceof Array}),Array.prototype.forEach||(Array.prototype.forEach=function(a,b){var c=this.length>>>0;for(var d=0;d<c;d++)d in this&&a.call(b,this[d],d,this)}),Array.prototype.map||(Array.prototype.map=function(a){var b=this.length>>>0,c=Array(b),d=arguments[1];for(var e=0;e<b;e++)e in this&&(c[e]=a.call(d,this[e],e,this));return c}),Array.prototype.filter||(Array.prototype.filter=function(a){var b=[],c=arguments[1];for(var d=0;d<this.length;d++)a.call(c,this[d])&&b.push(this[d]);return b}),Array.prototype.reduce||(Array.prototype.reduce=function(a){var b=this.length>>>0,c=0;if(b===0&&arguments.length===1)throw new TypeError;if(arguments.length>=2)var d=arguments[1];else for(;;){if(c in this){d=this[c++];break}if(++c>=b)throw new TypeError}for(;c<b;c++)c in this&&(d=a.call(null,d,this[c],c,this));return d}),Array.prototype.indexOf||(Array.prototype.indexOf=function(a){var b=this.length,c=arguments[1]||0;if(!b)return-1;if(c>=b)return-1;c<0&&(c+=b);for(;c<b;c++){if(!Object.prototype.hasOwnProperty.call(this,c))continue;if(a===this[c])return c}return-1}),Object.keys||(Object.keys=function(a){var b=[];for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&b.push(c);return b}),String.prototype.trim||(String.prototype.trim=function(){return String(this).replace(/^\s\s*/,"").replace(/\s\s*$/,"")});var d,e;typeof a=="undefined"?(d=exports,e=c("less/tree")):(typeof a.less=="undefined"&&(a.less={}),d=a.less,e=a.less.tree={}),d.Parser=function(a){function t(a){return typeof a=="string"?b.charAt(c)===a:a.test(j[f])?!0:!1}function s(a){var d,e,g,h,i,m,n,o;if(a instanceof Function)return a.call(l.parsers);if(typeof a=="string")d=b.charAt(c)===a?a:null,g=1,r();else{r();if(d=a.exec(j[f]))g=d[0].length;else return null}if(d){o=c+=g,m=c+j[f].length-g;while(c<m){h=b.charCodeAt(c);if(h!==32&&h!==10&&h!==9)break;c++}j[f]=j[f].slice(g+(c-o)),k=c,j[f].length===0&&f<j.length-1&&f++;return typeof d=="string"?d:d.length===1?d[0]:d}}function r(){c>k&&(j[f]=j[f].slice(c-k),k=c)}function q(){j[f]=g,c=h,k=c}function p(){g=j[f],h=c,k=c}var b,c,f,g,h,i,j,k,l,m=this,n=function(){},o=this.imports={paths:a&&a.paths||[],queue:[],files:{},mime:a&&a.mime,push:function(b,c){var e=this;this.queue.push(b),d.Parser.importer(b,this.paths,function(a){e.queue.splice(e.queue.indexOf(b),1),e.files[b]=a,c(a),e.queue.length===0&&n()},a)}};this.env=a=a||{},this.optimization="optimization"in this.env?this.env.optimization:1,this.env.filename=this.env.filename||null;return l={imports:o,parse:function(d,g){var h,l,m,o,p,q,r=[],t,u=null;c=f=k=i=0,j=[],b=d.replace(/\r\n/g,"\n"),j=function(c){var d=0,e=/[^"'`\{\}\/\(\)]+/g,f=/\/\*(?:[^*]|\*+[^\/*])*\*+\/|\/\/.*/g,g=0,h,i=c[0],j,k;for(var l=0,m,n;l<b.length;l++){e.lastIndex=l,(h=e.exec(b))&&h.index===l&&(l+=h[0].length,i.push(h[0])),m=b.charAt(l),f.lastIndex=l,!k&&!j&&m==="/"&&(n=b.charAt(l+1),(n==="/"||n==="*")&&(h=f.exec(b))&&h.index===l&&(l+=h[0].length,i.push(h[0]),m=b.charAt(l)));if(m==="{"&&!k&&!j)g++,i.push(m);else if(m==="}"&&!k&&!j)g--,i.push(m),c[++d]=i=[];else if(m==="("&&!k&&!j)i.push(m),j=!0;else if(m===")"&&!k&&j)i.push(m),j=!1;else{if(m==='"'||m==="'"||m==="`")k?k=k===m?!1:k:k=m;i.push(m)}}if(g>0)throw{type:"Syntax",message:"Missing closing `}`",filename:a.filename};return c.map(function(a){return a.join("")})}([[]]),h=new e.Ruleset([],s(this.parsers.primary)),h.root=!0,h.toCSS=function(c){var d,f,g;return function(g,h){function n(a){return a?(b.slice(0,a).match(/\n/g)||"").length:null}var i=[];g=g||{},typeof h=="object"&&!Array.isArray(h)&&(h=Object.keys(h).map(function(a){var b=h[a];b instanceof e.Value||(b instanceof e.Expression||(b=new e.Expression([b])),b=new e.Value([b]));return new e.Rule("@"+a,b,!1,0)}),i=[new e.Ruleset(null,h)]);try{var j=c.call(this,{frames:i}).toCSS([],{compress:g.compress||!1})}catch(k){f=b.split("\n"),d=n(k.index);for(var l=k.index,m=-1;l>=0&&b.charAt(l)!=="\n";l--)m++;throw{type:k.type,message:k.message,filename:a.filename,index:k.index,line:typeof d=="number"?d+1:null,callLine:k.call&&n(k.call)+1,callExtract:f[n(k.call)],stack:k.stack,column:m,extract:[f[d-1],f[d],f[d+1]]}}return g.compress?j.replace(/(\s)+/g,"$1"):j}}(h.eval);if(c<b.length-1){c=i,q=b.split("\n"),p=(b.slice(0,c).match(/\n/g)||"").length+1;for(var v=c,w=-1;v>=0&&b.charAt(v)!=="\n";v--)w++;u={name:"ParseError",message:"Syntax Error on line "+p,index:c,filename:a.filename,line:p,column:w,extract:[q[p-2],q[p-1],q[p]]}}this.imports.queue.length>0?n=function(){g(u,h)}:g(u,h)},parsers:{primary:function(){var a,b=[];while((a=s(this.mixin.definition)||s(this.rule)||s(this.ruleset)||s(this.mixin.call)||s(this.comment)||s(this.directive))||s(/^[\s\n]+/))a&&b.push(a);return b},comment:function(){var a;if(b.charAt(c)==="/"){if(b.charAt(c+1)==="/")return new e.Comment(s(/^\/\/.*/),!0);if(a=s(/^\/\*(?:[^*]|\*+[^\/*])*\*+\/\n?/))return new e.Comment(a)}},entities:{quoted:function(){var a,d=c,f;b.charAt(d)==="~"&&(d++,f=!0);if(b.charAt(d)==='"'||b.charAt(d)==="'"){f&&s("~");if(a=s(/^"((?:[^"\\\r\n]|\\.)*)"|'((?:[^'\\\r\n]|\\.)*)'/))return new e.Quoted(a[0],a[1]||a[2],f)}},keyword:function(){var a;if(a=s(/^[A-Za-z-]+/))return new e.Keyword(a)},call:function(){var a,b,d=c;if(!!(a=/^([\w-]+|%)\(/.exec(j[f]))){a=a[1].toLowerCase();if(a==="url")return null;c+=a.length;if(a==="alpha")return s(this.alpha);s("("),b=s(this.entities.arguments);if(!s(")"))return;if(a)return new e.Call(a,b,d)}},arguments:function(){var a=[],b;while(b=s(this.expression)){a.push(b);if(!s(","))break}return a},literal:function(){return s(this.entities.dimension)||s(this.entities.color)||s(this.entities.quoted)},url:function(){var a;if(b.charAt(c)==="u"&&!!s(/^url\(/)){a=s(this.entities.quoted)||s(this.entities.variable)||s(this.entities.dataURI)||s(/^[-\w%@$\/.&=:;#+?~]+/)||"";if(!s(")"))throw new Error("missing closing ) for url()");return new e.URL(a.value||a.data||a instanceof e.Variable?a:new e.Anonymous(a),o.paths)}},dataURI:function(){var a;if(s(/^data:/)){a={},a.mime=s(/^[^\/]+\/[^,;)]+/)||"",a.charset=s(/^;\s*charset=[^,;)]+/)||"",a.base64=s(/^;\s*base64/)||"",a.data=s(/^,\s*[^)]+/);if(a.data)return a}},variable:function(){var a,d=c;if(b.charAt(c)==="@"&&(a=s(/^@@?[\w-]+/)))return new e.Variable(a,d)},color:function(){var a;if(b.charAt(c)==="#"&&(a=s(/^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})/)))return new e.Color(a[1])},dimension:function(){var a,d=b.charCodeAt(c);if(!(d>57||d<45||d===47))if(a=s(/^(-?\d*\.?\d+)(px|%|em|pc|ex|in|deg|s|ms|pt|cm|mm|rad|grad|turn)?/))return new e.Dimension(a[1],a[2])},javascript:function(){var a,d=c,f;b.charAt(d)==="~"&&(d++,f=!0);if(b.charAt(d)==="`"){f&&s("~");if(a=s(/^`([^`]*)`/))return new e.JavaScript(a[1],c,f)}}},variable:function(){var a;if(b.charAt(c)==="@"&&(a=s(/^(@[\w-]+)\s*:/)))return a[1]},shorthand:function(){var a,b;if(!!t(/^[@\w.%-]+\/[@\w.-]+/)&&(a=s(this.entity))&&s("/")&&(b=s(this.entity)))return new e.Shorthand(a,b)},mixin:{call:function(){var a=[],d,f,g,h=c,i=b.charAt(c);if(i==="."||i==="#"){while(d=s(/^[#.](?:[\w-]|\\(?:[a-fA-F0-9]{1,6} ?|[^a-fA-F0-9]))+/))a.push(new e.Element(f,d)),f=s(">");s("(")&&(g=s(this.entities.arguments))&&s(")");if(a.length>0&&(s(";")||t("}")))return new e.mixin.Call(a,g,h)}},definition:function(){var a,d=[],f,g,h,i;if(!(b.charAt(c)!=="."&&b.charAt(c)!=="#"||t(/^[^{]*(;|})/)))if(f=s(/^([#.](?:[\w-]|\\(?:[a-fA-F0-9]{1,6} ?|[^a-fA-F0-9]))+)\s*\(/)){a=f[1];while(h=s(this.entities.variable)||s(this.entities.literal)||s(this.entities.keyword)){if(h instanceof e.Variable)if(s(":"))if(i=s(this.expression))d.push({name:h.name,value:i});else throw new Error("Expected value");else d.push({name:h.name});else d.push({value:h});if(!s(","))break}if(!s(")"))throw new Error("Expected )");g=s(this.block);if(g)return new e.mixin.Definition(a,d,g)}}},entity:function(){return s(this.entities.literal)||s(this.entities.variable)||s(this.entities.url)||s(this.entities.call)||s(this.entities.keyword)||s(this.entities.javascript)||s(this.comment)},end:function(){return s(";")||t("}")},alpha:function(){var a;if(!!s(/^\(opacity=/i))if(a=s(/^\d+/)||s(this.entities.variable)){if(!s(")"))throw new Error("missing closing ) for alpha()");return new e.Alpha(a)}},element:function(){var a,b,c;c=s(this.combinator),a=s(/^(?:[.#]?|:*)(?:[\w-]|\\(?:[a-fA-F0-9]{1,6} ?|[^a-fA-F0-9]))+/)||s("*")||s(this.attribute)||s(/^\([^)@]+\)/);if(a)return new e.Element(c,a)},combinator:function(){var a,d=b.charAt(c);if(d===">"||d==="&"||d==="+"||d==="~"){c++;while(b.charAt(c)===" ")c++;return new e.Combinator(d)}if(d===":"&&b.charAt(c+1)===":"){c+=2;while(b.charAt(c)===" ")c++;return new e.Combinator("::")}return b.charAt(c-1)===" "?new e.Combinator(" "):new e.Combinator(null)},selector:function(){var a,d,f=[],g,h;while(d=s(this.element)){g=b.charAt(c),f.push(d);if(g==="{"||g==="}"||g===";"||g===",")break}if(f.length>0)return new e.Selector(f)},tag:function(){return s(/^[a-zA-Z][a-zA-Z-]*[0-9]?/)||s("*")},attribute:function(){var a="",b,c,d;if(!!s("[")){if(b=s(/^[a-zA-Z-]+/)||s(this.entities.quoted))(d=s(/^[|~*$^]?=/))&&(c=s(this.entities.quoted)||s(/^[\w-]+/))?a=[b,d,c.toCSS?c.toCSS():c].join(""):a=b;if(!s("]"))return;if(a)return"["+a+"]"}},block:function(){var a;if(s("{")&&(a=s(this.primary))&&s("}"))return a},ruleset:function(){var a=[],b,d,g;p();if(g=/^([.#: \w-]+)[\s\n]*\{/.exec(j[f]))c+=g[0].length-1,a=[new e.Selector([new e.Element(null,g[1])])];else while(b=s(this.selector)){a.push(b),s(this.comment);if(!s(","))break;s(this.comment)}if(a.length>0&&(d=s(this.block)))return new e.Ruleset(a,d);i=c,q()},rule:function(){var a,d,g=b.charAt(c),k,l;p();if(g!=="."&&g!=="#"&&g!=="&")if(a=s(this.variable)||s(this.property)){a.charAt(0)!="@"&&(l=/^([^@+\/'"*`(;{}-]*);/.exec(j[f]))?(c+=l[0].length-1,d=new e.Anonymous(l[1])):a==="font"?d=s(this.font):d=s(this.value),k=s(this.important);if(d&&s(this.end))return new e.Rule(a,d,k,h);i=c,q()}},"import":function(){var a;if(s(/^@import\s+/)&&(a=s(this.entities.quoted)||s(this.entities.url))&&s(";"))return new e.Import(a,o)},directive:function(){var a,d,f,g;if(b.charAt(c)==="@"){if(d=s(this["import"]))return d;if(a=s(/^@media|@page|@-[-a-z]+/)){g=(s(/^[^{]+/)||"").trim();if(f=s(this.block))return new e.Directive(a+" "+g,f)}else if(a=s(/^@[-a-z]+/))if(a==="@font-face"){if(f=s(this.block))return new e.Directive(a,f)}else if((d=s(this.entity))&&s(";"))return new e.Directive(a,d)}},font:function(){var a=[],b=[],c,d,f,g;while(g=s(this.shorthand)||s(this.entity))b.push(g);a.push(new e.Expression(b));if(s(","))while(g=s(this.expression)){a.push(g);if(!s(","))break}return new e.Value(a)},value:function(){var a,b=[],c;while(a=s(this.expression)){b.push(a);if(!s(","))break}if(b.length>0)return new e.Value(b)},important:function(){if(b.charAt(c)==="!")return s(/^! *important/)},sub:function(){var a;if(s("(")&&(a=s(this.expression))&&s(")"))return a},multiplication:function(){var a,b,c,d;if(a=s(this.operand)){while((c=s("/")||s("*"))&&(b=s(this.operand)))d=new e.Operation(c,[d||a,b]);return d||a}},addition:function(){var a,d,f,g;if(a=s(this.multiplication)){while((f=s(/^[-+]\s+/)||b.charAt(c-1)!=" "&&(s("+")||s("-")))&&(d=s(this.multiplication)))g=new e.Operation(f,[g||a,d]);return g||a}},operand:function(){var a,d=b.charAt(c+1);b.charAt(c)==="-"&&(d==="@"||d==="(")&&(a=s("-"));var f=s(this.sub)||s(this.entities.dimension)||s(this.entities.color)||s(this.entities.variable)||s(this.entities.call);return a?new e.Operation("*",[new e.Dimension(-1),f]):f},expression:function(){var a,b,c=[],d;while(a=s(this.addition)||s(this.entity))c.push(a);if(c.length>0)return new e.Expression(c)},property:function(){var a;if(a=s(/^(\*?-?[-a-z_0-9]+)\s*:/))return a[1]}}}},typeof a!="undefined"&&(d.Parser.importer=function(a,b,c,d){a.charAt(0)!=="/"&&b.length>0&&(a=b[0]+a),o({href:a,title:a,type:d.mime},c,!0)}),function(a){function d(a){return Math.min(1,Math.max(0,a))}function c(b){if(b instanceof a.Dimension)return parseFloat(b.unit=="%"?b.value/100:b.value);if(typeof b=="number")return b;throw{error:"RuntimeError",message:"color functions take numbers as parameters"}}function b(b){return a.functions.hsla(b.h,b.s,b.l,b.a)}a.functions={rgb:function(a,b,c){return this.rgba(a,b,c,1)},rgba:function(b,d,e,f){var g=[b,d,e].map(function(a){return c(a)}),f=c(f);return new a.Color(g,f)},hsl:function(a,b,c){return this.hsla(a,b,c,1)},hsla:function(a,b,d,e){function h(a){a=a<0?a+1:a>1?a-1:a;return a*6<1?g+(f-g)*a*6:a*2<1?f:a*3<2?g+(f-g)*(2/3-a)*6:g}a=c(a)%360/360,b=c(b),d=c(d),e=c(e);var f=d<=.5?d*(b+1):d+b-d*b,g=d*2-f;return this.rgba(h(a+1/3)*255,h(a)*255,h(a-1/3)*255,e)},hue:function(b){return new a.Dimension(Math.round(b.toHSL().h))},saturation:function(b){return new a.Dimension(Math.round(b.toHSL().s*100),"%")},lightness:function(b){return new a.Dimension(Math.round(b.toHSL().l*100),"%")},alpha:function(b){return new a.Dimension(b.toHSL().a)},saturate:function(a,c){var e=a.toHSL();e.s+=c.value/100,e.s=d(e.s);return b(e)},desaturate:function(a,c){var e=a.toHSL();e.s-=c.value/100,e.s=d(e.s);return b(e)},lighten:function(a,c){var e=a.toHSL();e.l+=c.value/100,e.l=d(e.l);return b(e)},darken:function(a,c){var e=a.toHSL();e.l-=c.value/100,e.l=d(e.l);return b(e)},fadein:function(a,c){var e=a.toHSL();e.a+=c.value/100,e.a=d(e.a);return b(e)},fadeout:function(a,c){var e=a.toHSL();e.a-=c.value/100,e.a=d(e.a);return b(e)},spin:function(a,c){var d=a.toHSL(),e=(d.h+c.value)%360;d.h=e<0?360+e:e;return b(d)},mix:function(b,c,d){var e=d.value/100,f=e*2-1,g=b.toHSL().a-c.toHSL().a,h=((f*g==-1?f:(f+g)/(1+f*g))+1)/2,i=1-h,j=[b.rgb[0]*h+c.rgb[0]*i,b.rgb[1]*h+c.rgb[1]*i,b.rgb[2]*h+c.rgb[2]*i],k=b.alpha*e+c.alpha*(1-e);return new a.Color(j,k)},greyscale:function(b){return this.desaturate(b,new a.Dimension(100))},e:function(b){return new a.Anonymous(b instanceof a.JavaScript?b.evaluated:b)},escape:function(b){return new a.Anonymous(encodeURI(b.value).replace(/=/g,"%3D").replace(/:/g,"%3A").replace(/#/g,"%23").replace(/;/g,"%3B").replace(/\(/g,"%28").replace(/\)/g,"%29"))},"%":function(b){var c=Array.prototype.slice.call(arguments,1),d=b.value;for(var e=0;e<c.length;e++)d=d.replace(/%[sda]/i,function(a){var b=a.match(/s/i)?c[e].value:c[e].toCSS();return a.match(/[A-Z]$/)?encodeURIComponent(b):b});d=d.replace(/%%/g,"%");return new a.Quoted('"'+d+'"',d)},round:function(b){if(b instanceof a.Dimension)return new a.Dimension(Math.round(c(b)),b.unit);if(typeof b=="number")return Math.round(b);throw{error:"RuntimeError",message:"math functions take numbers as parameters"}}}}(c("less/tree")),function(a){a.Alpha=function(a){this.value=a},a.Alpha.prototype={toCSS:function(){return"alpha(opacity="+(this.value.toCSS?this.value.toCSS():this.value)+")"},eval:function(a){this.value.eval&&(this.value=this.value.eval(a));return this}}}(c("less/tree")),function(a){a.Anonymous=function(a){this.value=a.value||a},a.Anonymous.prototype={toCSS:function(){return this.value},eval:function(){return this}}}(c("less/tree")),function(a){a.Call=function(a,b,c){this.name=a,this.args=b,this.index=c},a.Call.prototype={eval:function(b){var c=this.args.map(function(a){return a.eval(b)});if(!(this.name in a.functions))return new a.Anonymous(this.name+"("+c.map(function(a){return a.toCSS()}).join(", ")+")");try{return a.functions[this.name].apply(a.functions,c)}catch(d){throw{message:"error evaluating function `"+this.name+"`",index:this.index}}},toCSS:function(a){return this.eval(a).toCSS()}}}(c("less/tree")),function(a){a.Color=function(a,b){Array.isArray(a)?this.rgb=a:a.length==6?this.rgb=a.match(/.{2}/g).map(function(a){return parseInt(a,16)}):a.length==8?(this.alpha=parseInt(a.substring(0,2),16)/255,this.rgb=a.substr(2).match(/.{2}/g).map(function(a){return parseInt(a,16)})):this.rgb=a.split("").map(function(a){return parseInt(a+a,16)}),this.alpha=typeof b=="number"?b:1},a.Color.prototype={eval:function(){return this},toCSS:function(){return this.alpha<1?"rgba("+this.rgb.map(function(a){return Math.round(a)}).concat(this.alpha).join(", ")+")":"#"+this.rgb.map(function(a){a=Math.round(a),a=(a>255?255:a<0?0:a).toString(16);return a.length===1?"0"+a:a}).join("")},operate:function(b,c){var d=[];c instanceof a.Color||(c=c.toColor());for(var e=0;e<3;e++)d[e]=a.operate(b,this.rgb[e],c.rgb[e]);return new a.Color(d,this.alpha+c.alpha)},toHSL:function(){var a=this.rgb[0]/255,b=this.rgb[1]/255,c=this.rgb[2]/255,d=this.alpha,e=Math.max(a,b,c),f=Math.min(a,b,c),g,h,i=(e+f)/2,j=e-f;if(e===f)g=h=0;else{h=i>.5?j/(2-e-f):j/(e+f);switch(e){case a:g=(b-c)/j+(b<c?6:0);break;case b:g=(c-a)/j+2;break;case c:g=(a-b)/j+4}g/=6}return{h:g*360,s:h,l:i,a:d}}}}(c("less/tree")),function(a){a.Comment=function(a,b){this.value=a,this.silent=!!b},a.Comment.prototype={toCSS:function(a){return a.compress?"":this.value},eval:function(){return this}}}(c("less/tree")),function(a){a.Dimension=function(a,b){this.value=parseFloat(a),this.unit=b||null},a.Dimension.prototype={eval:function(){return this},toColor:function(){return new a.Color([this.value,this.value,this.value])},toCSS:function(){var a=this.value+this.unit;return a},operate:function(b,c){return new a.Dimension(a.operate(b,this.value,c.value),this.unit||c.unit)}}}(c("less/tree")),function(a){a.Directive=function(b,c){this.name=b,Array.isArray(c)?this.ruleset=new a.Ruleset([],c):this.value=c},a.Directive.prototype={toCSS:function(a,b){if(this.ruleset){this.ruleset.root=!0;return this.name+(b.compress?"{":" {\n ")+this.ruleset.toCSS(a,b).trim().replace(/\n/g,"\n ")+(b.compress?"}":"\n}\n")}return this.name+" "+this.value.toCSS()+";\n"},eval:function(a){a.frames.unshift(this),this.ruleset=this.ruleset&&this.ruleset.eval(a),a.frames.shift();return this},variable:function(b){return a.Ruleset.prototype.variable.call(this.ruleset,b)},find:function(){return a.Ruleset.prototype.find.apply(this.ruleset,arguments)},rulesets:function(){return a.Ruleset.prototype.rulesets.apply(this.ruleset)}}}(c("less/tree")),function(a){a.Element=function(b,c){this.combinator=b instanceof a.Combinator?b:new a.Combinator(b),this.value=c.trim()},a.Element.prototype.toCSS=function(a){return this.combinator.toCSS(a||{})+this.value},a.Combinator=function(a){a===" "?this.value=" ":this.value=a?a.trim():""},a.Combinator.prototype.toCSS=function(a){return{"":""," ":" ","&":"",":":" :","::":"::","+":a.compress?"+":" + ","~":a.compress?"~":" ~ ",">":a.compress?">":" > "}[this.value]}}(c("less/tree")),function(a){a.Expression=function(a){this.value=a},a.Expression.prototype={eval:function(b){return this.value.length>1?new a.Expression(this.value.map(function(a){return a.eval(b)})):this.value.length===1?this.value[0].eval(b):this},toCSS:function(a){return this.value.map(function(b){return b.toCSS(a)}).join(" ")}}}(c("less/tree")),function(a){a.Import=function(b,c){var d=this;this._path=b,b instanceof a.Quoted?this.path=/\.(le?|c)ss$/.test(b.value)?b.value:b.value+".less":this.path=b.value.value||b.value,this.css=/css$/.test(this.path),this.css||c.push(this.path,function(a){if(!a)throw new Error("Error parsing "+d.path);d.root=a})},a.Import.prototype={toCSS:function(){return this.css?"@import "+this._path.toCSS()+";\n":""},eval:function(b){var c;if(this.css)return this;c=new a.Ruleset(null,this.root.rules.slice(0));for(var d=0;d<c.rules.length;d++)c.rules[d]instanceof a.Import&&Array.prototype.splice.apply(c.rules,[d,1].concat(c.rules[d].eval(b)));return c.rules}}}(c("less/tree")),function(a){a.JavaScript=function(a,b,c){this.escaped=c,this.expression=a,this.index=b},a.JavaScript.prototype={eval:function(b){var c,d=this,e={},f=this.expression.replace(/@\{([\w-]+)\}/g,function(c,e){return a.jsify((new a.Variable("@"+e,d.index)).eval(b))});try{f=new Function("return ("+f+")")}catch(g){throw{message:"JavaScript evaluation error: `"+f+"`",index:this.index}}for(var h in b.frames[0].variables())e[h.slice(1)]={value:b.frames[0].variables()[h].value,toJS:function(){return this.value.eval(b).toCSS()}};try{c=f.call(e)}catch(g){throw{message:"JavaScript evaluation error: '"+g.name+": "+g.message+"'",index:this.index}}return typeof c=="string"?new a.Quoted('"'+c+'"',c,this.escaped,this.index):Array.isArray(c)?new a.Anonymous(c.join(", ")):new a.Anonymous(c)}}}(c("less/tree")),function(a){a.Keyword=function(a){this.value=a},a.Keyword.prototype={eval:function(){return this},toCSS:function(){return this.value}}}(c("less/tree")),function(a){a.mixin={},a.mixin.Call=function(b,c,d){this.selector=new a.Selector(b),this.arguments=c,this.index=d},a.mixin.Call.prototype={eval:function(a){var b,c,d=[],e=!1;for(var f=0;f<a.frames.length;f++)if((b=a.frames[f].find(this.selector)).length>0){c=this.arguments&&this.arguments.map(function(b){return b.eval(a)});for(var g=0;g<b.length;g++)if(b[g].match(c,a))try{Array.prototype.push.apply(d,b[g].eval(a,this.arguments).rules),e=!0}catch(h){throw{message:h.message,index:h.index,stack:h.stack,call:this.index}}if(e)return d;throw{message:"No matching definition was found for `"+this.selector.toCSS().trim()+"("+this.arguments.map(function(a){return a.toCSS()}).join(", ")+")`",index:this.index}}throw{message:this.selector.toCSS().trim()+" is undefined",index:this.index}}},a.mixin.Definition=function(b,c,d){this.name=b,this.selectors=[new a.Selector([new a.Element(null,b)])],this.params=c,this.arity=c.length,this.rules=d,this._lookups={},this.required=c.reduce(function(a,b){return!b.name||b.name&&!b.value?a+1:a},0),this.parent=a.Ruleset.prototype,this.frames=[]},a.mixin.Definition.prototype={toCSS:function(){return""},variable:function(a){return this.parent.variable.call(this,a)},variables:function(){return this.parent.variables.call(this)},find:function(){return this.parent.find.apply(this,arguments)},rulesets:function(){return this.parent.rulesets.apply(this)},eval:function(b,c){var d=new a.Ruleset(null,[]),e,f=[];for(var g=0,h;g<this.params.length;g++)if(this.params[g].name)if(h=c&&c[g]||this.params[g].value)d.rules.unshift(new a.Rule(this.params[g].name,h.eval(b)));else throw{message:"wrong number of arguments for "+this.name+" ("+c.length+" for "+this.arity+")"};for(var g=0;g<Math.max(this.params.length,c&&c.length);g++)f.push(c[g]||this.params[g].value);d.rules.unshift(new a.Rule("@arguments",(new a.Expression(f)).eval(b)));return(new a.Ruleset(null,this.rules.slice(0))).eval({frames:[this,d].concat(this.frames,b.frames)})},match:function(a,b){var c=a&&a.length||0,d;if(c<this.required)return!1;if(this.required>0&&c>this.params.length)return!1;d=Math.min(c,this.arity);for(var e=0;e<d;e++)if(!this.params[e].name&&a[e].eval(b).toCSS()!=this.params[e].value.eval(b).toCSS())return!1;return!0}}}(c("less/tree")),function(a){a.Operation=function(a,b){this.op=a.trim(),this.operands=b},a.Operation.prototype.eval=function(b){var c=this.operands[0].eval(b),d=this.operands[1].eval(b),e;if(c instanceof a.Dimension&&d instanceof a.Color)if(this.op==="*"||this.op==="+")e=d,d=c,c=e;else throw{name:"OperationError",message:"Can't substract or divide a color from a number"};return c.operate(this.op,d)},a.operate=function(a,b,c){switch(a){case"+":return b+c;case"-":return b-c;case"*":return b*c;case"/":return b/c}}}(c("less/tree")),function(a){a.Quoted=function(a,b,c,d){this.escaped=c,this.value=b||"",this.quote=a.charAt(0),this.index=d},a.Quoted.prototype={toCSS:function(){return this.escaped?this.value:this.quote+this.value+this.quote},eval:function(b){var c=this,d=this.value.replace(/`([^`]+)`/g,function(d,e){return(new a.JavaScript(e,c.index,!0)).eval(b).value}).replace(/@\{([\w-]+)\}/g,function(d,e){var f=(new a.Variable("@"+e,c.index)).eval(b);return f.value||f.toCSS()});return new a.Quoted(this.quote+d+this.quote,d,this.escaped,this.index)}}}(c("less/tree")),function(a){a.Rule=function(b,c,d,e){this.name=b,this.value=c instanceof a.Value?c:new a.Value([c]),this.important=d?" "+d.trim():"",this.index=e,b.charAt(0)==="@"?this.variable=!0:this.variable=!1},a.Rule.prototype.toCSS=function(a){return this.variable?"":this.name+(a.compress?":":": ")+this.value.toCSS(a)+this.important+";"},a.Rule.prototype.eval=function(b){return new a.Rule(this.name,this.value.eval(b),this.important,this.index)},a.Shorthand=function(a,b){this.a=a,this.b=b},a.Shorthand.prototype={toCSS:function(a){return this.a.toCSS(a)+"/"+this.b.toCSS(a)},eval:function(){return this}}}(c("less/tree")),function(a){a.Ruleset=function(a,b){this.selectors=a,this.rules=b,this._lookups={}},a.Ruleset.prototype={eval:function(b){var c=new a.Ruleset(this.selectors,this.rules.slice(0));c.root=this.root,b.frames.unshift(c);if(c.root)for(var d=0;d<c.rules.length;d++)c.rules[d]instanceof a.Import&&Array.prototype.splice.apply(c.rules,[d,1].concat(c.rules[d].eval(b)));for(var d=0;d<c.rules.length;d++)c.rules[d]instanceof a.mixin.Definition&&(c.rules[d].frames=b.frames.slice(0));for(var d=0;d<c.rules.length;d++)c.rules[d]instanceof a.mixin.Call&&Array.prototype.splice.apply(c.rules,[d,1].concat(c.rules[d].eval(b)));for(var d=0,e;d<c.rules.length;d++)e=c.rules[d],e instanceof a.mixin.Definition||(c.rules[d]=e.eval?e.eval(b):e);b.frames.shift();return c},match:function(a){return!a||a.length===0},variables:function(){return this._variables?this._variables:this._variables=this.rules.reduce(function(b,c){c instanceof a.Rule&&c.variable===!0&&(b[c.name]=c);return b},{})},variable:function(a){return this.variables()[a]},rulesets:function(){return this._rulesets?this._rulesets:this._rulesets=this.rules.filter(function(b){return b instanceof a.Ruleset||b instanceof a.mixin.Definition})},find:function(b,c){c=c||this;var d=[],e,f,g=b.toCSS();if(g in this._lookups)return this._lookups[g];this.rulesets().forEach(function(e){if(e!==c)for(var g=0;g<e.selectors.length;g++)if(f=b.match(e.selectors[g])){b.elements.length>1?Array.prototype.push.apply(d,e.find(new a.Selector(b.elements.slice(1)),c)):d.push(e);break}});return this._lookups[g]=d},toCSS:function(b,c){var d=[],e=[],f=[],g=[],h,i;if(!this.root)if(b.length===0)g=this.selectors.map(function(a){return[a]});else for(var j=0;j<this.selectors.length;j++)for(var k=0;k<b.length;k++)g.push(b[k].concat([this.selectors[j]]));for(var l=0;l<this.rules.length;l++)i=this.rules[l],i.rules||i instanceof a.Directive?f.push(i.toCSS(g,c)):i instanceof a.Comment?i.silent||(this.root?f.push(i.toCSS(c)):e.push(i.toCSS(c))):i.toCSS&&!i.variable?e.push(i.toCSS(c)):i.value&&!i.variable&&e.push(i.value.toString());f=f.join(""),this.root?d.push(e.join(c.compress?"":"\n")):e.length>0&&(h=g.map(function(a){return a.map(function(a){return a.toCSS(c)}).join("").trim()}).join(c.compress?",":g.length>3?",\n":", "),d.push(h,(c.compress?"{":" {\n ")+e.join(c.compress?"":"\n ")+(c.compress?"}":"\n}\n"))),d.push(f);return d.join("")+(c.compress?"\n":"")}}}(c("less/tree")),function(a){a.Selector=function(a){this.elements=a,this.elements[0].combinator.value===""&&(this.elements[0].combinator.value=" ")},a.Selector.prototype.match=function(a){return this.elements[0].value===a.elements[0].value?!0:!1},a.Selector.prototype.toCSS=function(a){if(this._css)return this._css;return this._css=this.elements.map(function(b){return typeof b=="string"?" "+b.trim():b.toCSS(a)}).join("")}}(c("less/tree")),function(b){b.URL=function(b,c){b.data?this.attrs=b:(!/^(?:https?:\/|file:\/|data:\/)?\//.test(b.value)&&c.length>0&&typeof a!="undefined"&&(b.value=c[0]+(b.value.charAt(0)==="/"?b.value.slice(1):b.value)),this.value=b,this.paths=c)},b.URL.prototype={toCSS:function(){return"url("+(this.attrs?"data:"+this.attrs.mime+this.attrs.charset+this.attrs.base64+this.attrs.data:this.value.toCSS())+")"},eval:function(a){return this.attrs?this:new b.URL(this.value.eval(a),this.paths)}}}(c("less/tree")),function(a){a.Value=function(a){this.value=a,this.is="value"},a.Value.prototype={eval:function(b){return this.value.length===1?this.value[0].eval(b):new a.Value(this.value.map(function(a){return a.eval(b)}))},toCSS:function(a){return this.value.map(function(b){return b.toCSS(a)}).join(a.compress?",":", ")}}}(c("less/tree")),function(a){a.Variable=function(a,b){this.name=a,this
-.index=b},a.Variable.prototype={eval:function(b){var c,d,e=this.name;e.indexOf("@@")==0&&(e="@"+(new a.Variable(e.slice(1))).eval(b).value);if(c=a.find(b.frames,function(a){if(d=a.variable(e))return d.value.eval(b)}))return c;throw{message:"variable "+e+" is undefined",index:this.index}}}}(c("less/tree")),c("less/tree").find=function(a,b){for(var c=0,d;c<a.length;c++)if(d=b.call(a,a[c]))return d;return null},c("less/tree").jsify=function(a){return Array.isArray(a.value)&&a.value.length>1?"["+a.value.map(function(a){return a.toCSS(!1)}).join(", ")+"]":a.toCSS(!1)};var g=location.protocol==="file:"||location.protocol==="chrome:"||location.protocol==="chrome-extension:"||location.protocol==="resource:";d.env=d.env||(location.hostname=="127.0.0.1"||location.hostname=="0.0.0.0"||location.hostname=="localhost"||location.port.length>0||g?"development":"production"),d.async=!1,d.poll=d.poll||(g?1e3:1500),d.watch=function(){return this.watchMode=!0},d.unwatch=function(){return this.watchMode=!1},d.env==="development"?(d.optimization=0,/!watch/.test(location.hash)&&d.watch(),d.watchTimer=setInterval(function(){d.watchMode&&n(function(a,b,c){a&&q(a.toCSS(),b,c.lastModified)})},d.poll)):d.optimization=3;var h;try{h=typeof a.localStorage=="undefined"?null:a.localStorage}catch(i){h=null}var j=document.getElementsByTagName("link"),k=/^text\/(x-)?less$/;d.sheets=[];for(var l=0;l<j.length;l++)(j[l].rel==="stylesheet/less"||j[l].rel.match(/stylesheet/)&&j[l].type.match(k))&&d.sheets.push(j[l]);d.refresh=function(a){var b,c;b=c=new Date,n(function(a,d,e){e.local?u("loading "+d.href+" from cache."):(u("parsed "+d.href+" successfully."),q(a.toCSS(),d,e.lastModified)),u("css for "+d.href+" generated in "+(new Date-c)+"ms"),e.remaining===0&&u("css generated in "+(new Date-b)+"ms"),c=new Date},a),m()},d.refreshStyles=m,d.refresh(d.env==="development")})(window) \ No newline at end of file
diff --git a/askbot/skins/default/media/js/live_search.js b/askbot/skins/default/media/js/live_search.js
deleted file mode 100644
index d66f5006..00000000
--- a/askbot/skins/default/media/js/live_search.js
+++ /dev/null
@@ -1,545 +0,0 @@
-var prevSortMethod = sortMethod;
-var liveSearch = function(){
- var query = undefined;
- var prev_text = undefined;
- var running = false;
- var q_list_sel = 'question-list';//id of question listing div
- var search_url = undefined;
- var restart_query = function(){};
- var process_query = function(){};
- var render_result = function(){};
-
- var refresh_x_button = function(){
- if ($.trim(query.val()).length > 0){
- if (query.attr('class') === 'searchInput'){
- query.attr('class', 'searchInputCancelable');
- x_button = $('<input class="cancelSearchBtn" type="button" name="reset_query"/>');
- //x_button.click(reset_query);
- x_button.val('X');
- x_button.click(
- function(){
- query.val('');
- if (sortMethod === 'relevance-desc'){
- sortMethod = prevSortMethod;
- }
- refresh_x_button();
- reset_query(sortMethod);
- }
- );
- query.after(x_button);
- }
- } else {
- $('input[name=reset_query]').remove();
- query.attr('class', 'searchInput');
- }
- };
-
- var reset_sort_method = function(){
- if (sortMethod === 'relevance-desc'){
- sortMethod = prevSortMethod;
- if (sortMethod === 'relevance-desc'){
- sortMethod = 'activity-desc';
- }
- } else {
- sortMethod = 'activity-desc';
- prevSortMethod = 'activity-desc';
- }
- };
-
- var eval_query = function(){
- cur_text = $.trim(query.val());
- if (cur_text !== prev_text && running === false){
- if (cur_text.length >= minSearchWordLength){
- process_query();
- running = true;
- } else if (cur_text.length === 0){
- restart_query();
- }
- }
- };
-
- var ask_page_search_listen = function(){
- running = false;
- var ask_page_eval_handle;
- query.keyup(function(e){
- if (running === false){
- clearTimeout(ask_page_eval_handle);
- ask_page_eval_handle = setTimeout(eval_query, 400);
- }
- });
- };
-
- var main_page_search_listen = function(){
- running = false;
- refresh_x_button();
- var main_page_eval_handle;
- query.keyup(function(e){
- refresh_x_button();
- if (running === false){
- clearTimeout(main_page_eval_handle);
- main_page_eval_handle = setTimeout(eval_query, 400);
- }
- });
- };
-
- var render_counter = function(count, word, counter_class, counter_subclass){
- var output = '<div class="' + counter_class + ' ' + counter_subclass + '">' +
- '<span class="item-count">' +
- count;
- if (counter_class === 'accepted'){
- output += '&#10003;';
- }
- output += '</span>' +
- '<div>' + word + '</div>' +
- '</div>';
- return output;
- };
-
- var render_title = function(result){
- return '<h2>' +
- '<a href="' +
- askbot['urls']['question_url_template']
- .replace('{{QuestionID}}', result['id']) +
- '" onmouseover="load_question_body(this,' + result['id'] + ')">' +
- result['title'] +
- '</a>' +
- '</h2>';
- };
-
- var render_user_link = function(result){
- if (result['u_id'] !== false){
- if (result['u_is_anonymous'] === true){
- return '<span class="anonymous">' +
- askbot['messages']['name_of_anonymous_user'] +
- '</span>';
- } else {
- var u_slug = result['u_name'].toLowerCase().replace(/ +/g, '-');
- return '<a ' +
- 'href="' +
- askbot['urls']['user_url_template']
- .replace('{{user_id}}', result['u_id'])
- .replace('{{slug}}', u_slug) +
- '">' +
- result['u_name'] +
- '</a> ';
- }
- }
- else {
- return '';
- }
- };
-
- var render_badge = function(result, key){
- return '<span ' +
- 'title="' + result[key + '_title'] + '"' +
- '>' +
- '<span ' +
- 'class="' + result[key + '_css_class'] + '"' +
- '>' + result[key + '_badge_symbol'] + '</span>' +
- '<span class="badgecount">' + result[key] + '</span>';
- };
-
- var render_user_badge_and_karma = function(result){
- var rep_title = result['u_rep'] + ' ' + result['u_rep_word'];
- var html = '<span ' +
- 'class="reputation-score" ' +
- 'title="' + rep_title + '"' +
- '>' + result['u_rep'] + '</span>';
- if (result['u_gold'] > 0){
- html += render_badge(result, 'u_gold');
- }
- if (result['u_silver'] > 0){
- html += render_badge(result, 'u_silver');
- }
- if (result['u_bronze'] > 0){
- html += render_badge(result, 'u_bronze');
- }
- return html;
- };
-
- var render_user_flag = function(result){
- var country_code = result['u_country_code'];
- if (country_code) {
- return '<img class="flag" src="'+
- mediaUrl(
- 'media/images/flags/' +
- country_code.toLowerCase() +
- '.gif'
- ) +
- '"/>';
- } else {
- return '';
- }
- };
-
- var render_user_info = function(result){
- var user_html =
- '<div class="userinfo">' +
- '<span class="relativetime" ' +
- 'title="' + result['timestamp'] + '"' +
- '>' +
- result['timesince'] +
- '</span> ' +
- render_user_link(result);
- if (result['u_is_anonymous'] === false){
- user_html += render_user_flag(result);
- //render_user_badge_and_karma(result) +
- }
- user_html += '</div>';
- return user_html;
- };
-
- var render_tag = function(tag_name, linkable, deletable){
- var tag = new Tag();
- tag.setName(tag_name);
- tag.setDeletable(deletable);
- tag.setLinkable(linkable);
- return tag.getElement().outerHTML();
- };
-
- var render_tags = function(tags, linkable, deletable){
- var tags_html = '<ul class="tags">';
- $.each(tags, function(idx, item){
- tags_html += render_tag(item, linkable, deletable);
- });
- tags_html += '</ul>';
- return tags_html;
- };
-
- var render_question = function(question){
- var entry_html =
- '<div class="short-summary">' +
- '<div class="counts">' +
- render_counter(
- question['views'],
- question['views_word'],
- 'views',
- question['views_class']
- ) +
- render_counter(
- question['answers'],
- question['answers_word'],
- 'answers',
- question['answers_class']
- ) +
- render_counter(
- question['votes'],
- question['votes_word'],
- 'votes',
- question['votes_class']
- ) +
- '<div style="clear:both"></div>' +
- render_user_info(question) +
- '</div>' +
- render_title(question) +
- render_tags(question['tags'], true, false) +
- '</div>';
- return entry_html;
- };
-
- var render_question_list = function(questions){
- var output = '';
- for (var i=0; i<questions.length; i++){
- output += render_question(questions[i]);
- }
- return output;
- };
-
- var render_faces = function(faces){
- if (faces.length === 0){
- return;
- }
- $('#contrib-users>a').remove();
- var html = '';
- for (var i=0; i<faces.length; i++){
- html += faces[i];
- }
- $('#contrib-users').append(html);
- };
-
- var render_related_tags = function(tags){
- if (tags.length === 0){
- return;
- }
- var html = '';
- for (var i=0; i<tags.length; i++){
- html += render_tag(tags[i]['name'], true, false);
- html += '<span class="tag-number">&#215; ' +
- tags[i]['used_count'] +
- '</span>' +
- '<br />';
- }
- $('#related-tags').html(html);
- };
-
- var render_paginator = function(paginator){
- var pager = $('#pager');
- if (paginator === ''){
- pager.hide();
- return;
- }
- else {
- pager.show();
- pager.html(paginator);
- }
- };
-
- var set_question_count = function(count_html){
- $('#question-count').html(count_html);
- };
-
- var get_old_tags = function(container){
- var tag_elements = container.find('.tag');
- var old_tags = [];
- tag_elements.each(function(idx, element){
- old_tags.push($(element).html());
- });
- return old_tags;
- };
-
- var render_search_tags = function(tags){
- var search_tags = $('#searchTags');
- search_tags.children().remove();
- var tags_html = '';
- $.each(tags, function(idx, tag_name){
- var tag = new Tag();
- tag.setName(tag_name);
- tag.setDeletable(true);
- tag.setLinkable(false);
- tag.setDeleteHandler(
- function(){
- remove_search_tag(tag_name);
- }
- );
- search_tags.append(tag.getElement());
- });
- };
-
- var create_relevance_tab = function(){
- relevance_tab = $('<a></a>');
- relevance_tab.attr('href', '?sort=relevance-desc');
- relevance_tab.attr('id', 'by_relevance');
- relevance_tab.html('<span>' + sortButtonData['relevance']['label'] + '</span>');
- return relevance_tab;
- }
-
- var set_active_sort_tab = function(sort_method){
- var tabs = $('#sort_tabs>a');
- tabs.attr('class', 'off');
- tabs.each(function(index, element){
- var tab = $(element);
- var tab_name = tab.attr('id').replace(/^by_/,'');
- if (tab_name in sortButtonData){
- tab.attr(
- 'href',
- '?sort=' + tab_name + '-desc'
- );
- tab.attr(
- 'title',
- sortButtonData[tab_name]['desc_tooltip']
- );
- tab.html(sortButtonData[tab_name]['label']);
- }
- });
- var bits = sort_method.split('-', 2);
- var name = bits[0];
- var sense = bits[1];//sense of sort
- var antisense = (sense == 'asc' ? 'desc':'asc');
- var arrow = (sense == 'asc' ? ' &#9650;':' &#9660;');
- var active_tab = $('#by_' + name);
- active_tab.attr('class', 'on');
- active_tab.attr('title', sortButtonData[name][antisense + '_tooltip']);
- active_tab.html(sortButtonData[name]['label'] + arrow);
- };
-
- var render_relevance_sort_tab = function(){
- if (showSortByRelevance === false){
- return;
- }
- var relevance_tab = $('#by_relevance');
- if (prev_text && prev_text.length > 0){
- if (relevance_tab.length == 0){
- relevance_tab = create_relevance_tab();
- $('#sort_tabs>span').after(relevance_tab);
- }
- }
- else {
- if (relevance_tab.length > 0){
- relevance_tab.remove();
- }
- }
- };
-
- var remove_search_tag = function(tag_name){
- $.ajax({
- url: askbot['urls']['questions'],
- data: {remove_tag: tag_name},
- dataType: 'json',
- success: render_result,
- complete: try_again
- });
- };
-
- var activate_search_tags = function(){
- var search_tags = $('#searchTags .tag-left');
- $.each(search_tags, function(idx, element){
- var tag = new Tag();
- tag.decorate($(element));
- //todo: setDeleteHandler and setHandler
- //must work after decorate & must have getName
- tag.setDeleteHandler(
- function(){
- remove_search_tag(tag.getName());
- }
- );
- });
- };
-
- var render_ask_page_result = function(data, text_status, xhr){
- var container = $('#' + q_list_sel);
- container.fadeOut(200, function() {
- container.children().remove();
- if (data.length > 5){
- container.css('overflow-y', 'scroll');
- container.css('height', '120px');
- } else {
- container.css('height', data.length * 24 + 'px');
- container.css('overflow-y', 'hidden');
- }
- $.each(data, function(idx, question){
- var url = question['url'];
- var title = question['title'];
- var answer_count = question['answer_count'];
- var list_item = $('<h2></h2>');
- var count_element = $('<span class="item-count"></span>');
- count_element.html(answer_count);
- list_item.append(count_element);
- var link = $('<a></a>');
- link.attr('href', url);
- list_item.append(link);
- title_element = $('<span class="title"></span>');
- title_element.html(title);
- link.append(title)
- container.append(list_item);
- });
- container.fadeIn();
- });
- };
-
- var render_main_page_result = function(data, text_status, xhr){
- var old_list = $('#' + q_list_sel);
- var new_list = $('<div></div>').hide();
- if (data['questions'].length > 0){
- old_list.stop(true);
-
- new_list.html(render_question_list(data['questions']));
- //old_list.hide();
- old_list.after(new_list);
- //old_list.remove();
- //rename new div to old
- render_paginator(data['paginator']);
- set_question_count(data['question_counter']);
- render_search_tags(data['query_data']['tags']);
- render_faces(data['faces']);
- render_related_tags(data['related_tags']);
- render_relevance_sort_tab();
- set_active_sort_tab(sortMethod);
- query.focus();
-
- //show new div with a fadeIn effect
- old_list.fadeOut(200, function() {
- old_list.remove();
- new_list.attr('id', q_list_sel);
- new_list.fadeIn(400);
- });
- }
- }
-
- var try_again = function(){
- running = false;
- eval_query();
- }
-
- var send_query = function(query_text, sort_method){
- var post_data = {query: query_text};
- $.ajax({
- url: search_url,
- data: {query: query_text, sort: sort_method},
- dataType: 'json',
- success: render_result,
- complete: try_again
- });
- prev_text = query_text;
- }
-
- var reset_query = function(sort_method){
- $.ajax({
- url: search_url,
- data: {reset_query: true, sort: sort_method},
- dataType: 'json',
- success: render_result,
- complete: try_again
- });
- prev_text = '';
- }
-
- var refresh_main_page = function(){
- $.ajax({
- url: askbot['urls']['questions'],
- data: {preserve_state: true},
- dataType: 'json',
- success: render_main_page_result
- });
- };
-
- return {
- refresh: function(){
- query = $('input#keywords');
- refresh_main_page();
- },
- init: function(mode){
- if (mode === 'main_page'){
- //live search for the main page
- query = $('input#keywords');
- search_url = askbot['urls']['questions'];
- render_result = render_main_page_result;
-
- process_query = function(){
- if (prev_text.length === 0 && showSortByRelevance){
- if (sortMethod === 'activity-desc'){
- prevSortMethod = sortMethod;
- sortMethod = 'relevance-desc';
- }
- }
- send_query(cur_text, sortMethod);
- };
- restart_query = function() {
- reset_sort_method();
- refresh_x_button();
- reset_query(sortMethod);
- running = true;
- };
-
- activate_search_tags();
- main_page_search_listen();
- } else {
- query = $('input#id_title.questionTitleInput');
- search_url = askbot['urls']['api_get_questions'];
- render_result = render_ask_page_result;
- process_query = function(){
- send_query(cur_text);
- };
- restart_query = function(){
- $('#' + q_list_sel).css('height',0).children().remove();
- running = false;
- prev_text = '';
- //ask_page_search_listen();
- };
- ask_page_search_listen();
- }
- prev_text = $.trim(query.val());
- running = false;
- }
- };
-
-};
diff --git a/askbot/skins/default/media/js/post.js b/askbot/skins/default/media/js/post.js
deleted file mode 100644
index 52772cc0..00000000
--- a/askbot/skins/default/media/js/post.js
+++ /dev/null
@@ -1,1665 +0,0 @@
-/*
-Scripts for cnprog.com
-Project Name: Lanai
-All Rights Resevred 2008. CNPROG.COM
-*/
-var lanai =
-{
- /**
- * Finds any <pre><code></code></pre> tags which aren't registered for
- * pretty printing, adds the appropriate class name and invokes prettify.
- */
- highlightSyntax: function(){
- var styled = false;
- $("pre code").parent().each(function(){
- if (!$(this).hasClass('prettyprint')){
- $(this).addClass('prettyprint');
- styled = true;
- }
- });
-
- if (styled){
- prettyPrint();
- }
- }
-};
-
-function appendLoader(element) {
- element.append('<img class="ajax-loader" ' +
- 'src="' + mediaUrl("media/images/indicator.gif") + '" title="' +
- $.i18n._('loading...') +
- '" alt="' +
- $.i18n._('loading...') +
- '" />');
-}
-
-function removeLoader() {
- $("img.ajax-loader").remove();
-}
-
-function setSubmitButtonDisabled(form, isDisabled) {
- form.find("input[type='submit']").attr("disabled", isDisabled ? "true" : "");
-}
-
-function enableSubmitButton(form) {
- setSubmitButtonDisabled(form, false);
-}
-
-function disableSubmitButton(form) {
- setSubmitButtonDisabled(form, true);
-}
-
-function setupFormValidation(form, validationRules, validationMessages, onSubmitCallback) {
- enableSubmitButton(form);
- form.validate({
- debug: true,
- rules: (validationRules ? validationRules : {}),
- messages: (validationMessages ? validationMessages : {}),
- errorElement: "span",
- errorClass: "form-error",
- errorPlacement: function(error, element) {
- var span = element.next().find("span.form-error");
- if (span.length === 0) {
- span = element.parent().find("span.form-error");
- if (span.length === 0){
- //for resizable textarea
- var element_id = element.attr('id');
- span = $("label[for='" + element_id + "']");
- }
- }
- span.replaceWith(error);
- },
- submitHandler: function(form_dom) {
- disableSubmitButton($(form_dom));
-
- if (onSubmitCallback){
- onSubmitCallback();
- }
- else{
- form_dom.submit();
- }
- }
- });
-}
-
-var validateTagLength = function(value){
- var tags = getUniqueWords(value);
- var are_tags_ok = true;
- $.each(tags, function(index, value){
- if (value.length > askbot['settings']['maxTagLength']){
- are_tags_ok = false;
- }
- });
- return are_tags_ok;
-};
-var validateTagCount = function(value){
- var tags = getUniqueWords(value);
- return (tags.length <= askbot['settings']['maxTagsPerPost']);
-};
-
-$.validator.addMethod('limit_tag_count', validateTagCount);
-$.validator.addMethod('limit_tag_length', validateTagLength);
-
-var CPValidator = function(){
- return {
- getQuestionFormRules : function(){
- return {
- tags: {
- required: true,
- maxlength: 105,
- limit_tag_count: true,
- limit_tag_length: true
- },
- text: {
- required: true,
- minlength: 10
- }
- /*title: {
- required: true,
- minlength: 10
- }*/
- };
- },
- getQuestionFormMessages: function(){
- return {
- tags: {
- required: " " + $.i18n._('tags cannot be empty'),
- maxlength: askbot['messages']['tagLimits'],
- limit_tag_count: askbot['messages']['maxTagsPerPost'],
- limit_tag_length: askbot['messages']['maxTagLength']
- },
- text: {
- required: " " + $.i18n._('content cannot be empty'),
- minlength: $.i18n._('content minchars').replace('{0}', 10)
- },
- title: {
- required: " " + $.i18n._('please enter title'),
- minlength: $.i18n._('title minchars').replace('{0}', 10)
- }
- };
- }
- };
-}();
-
-/**
- * @constructor
- * @extends {SimpleControl}
- * @param {Comment} comment to upvote
- */
-var CommentVoteButton = function(comment){
- SimpleControl.call(this);
- /**
- * @param {Comment}
- */
- this._comment = comment;
- /**
- * @type {boolean}
- */
- this._voted = false;
- /**
- * @type {number}
- */
- this._score = 0;
-};
-inherits(CommentVoteButton, SimpleControl);
-/**
- * @param {number} score
- */
-CommentVoteButton.prototype.setScore = function(score){
- this._score = score;
- if (this._element){
- this._element.html(score);
- }
-};
-/**
- * @param {boolean} voted
- */
-CommentVoteButton.prototype.setVoted = function(voted){
- this._voted = voted;
- if (this._element){
- this._element.addClass('upvoted');
- }
-};
-
-CommentVoteButton.prototype.getVoteHandler = function(){
- var me = this;
- var comment = this._comment;
- return function(){
- var voted = me._voted;
- var post_id = me._comment.getId();
- var data = {
- cancel_vote: voted ? true:false,
- post_id: post_id
- };
- $.ajax({
- type: 'POST',
- data: data,
- dataType: 'json',
- url: askbot['urls']['upvote_comment'],
- cache: false,
- success: function(data){
- if (data['success'] == true){
- me.setScore(data['score']);
- me.setVoted(true);
- } else {
- showMessage(comment.getElement(), data['message'], 'after');
- }
- }
- });
- };
-};
-
-CommentVoteButton.prototype.decorate = function(element){
- this._element = element;
- this.setHandler(this.getVoteHandler());
-
- var element = this._element;
- var comment = this._comment;
- /* can't call comment.getElement() here due
- * an issue in the getElement() of comment
- * so use an "illegal" access to comment._element here
- */
- comment._element.mouseenter(function(){
- //outside height may not be known
- //var height = comment.getElement().height();
- //element.height(height);
- element.addClass('hover');
- });
- comment._element.mouseleave(function(){
- element.removeClass('hover');
- });
-
-};
-
-CommentVoteButton.prototype.createDom = function(){
- this._element = this.makeElement('div');
- if (this._score > 0){
- this._element.html(this._score);
- }
- this._element.addClass('upvote');
- if (this._voted){
- this._element.addClass('upvoted');
- }
- this.decorate(this._element);
-};
-
-/**
- * legacy Vote class
- * handles all sorts of vote-like operations
- */
-var Vote = function(){
- // All actions are related to a question
- var questionId;
- //question slug to build redirect urls
- var questionSlug;
- // The object we operate on actually. It can be a question or an answer.
- var postId;
- var questionAuthorId;
- var currentUserId;
- var answerContainerIdPrefix = 'answer-container-';
- var voteContainerId = 'vote-buttons';
- var imgIdPrefixAccept = 'answer-img-accept-';
- var classPrefixFollow= 'button follow';
- var classPrefixFollowed= 'button followed';
- var imgIdPrefixQuestionVoteup = 'question-img-upvote-';
- var imgIdPrefixQuestionVotedown = 'question-img-downvote-';
- var imgIdPrefixAnswerVoteup = 'answer-img-upvote-';
- var imgIdPrefixAnswerVotedown = 'answer-img-downvote-';
- var divIdFavorite = 'favorite-number';
- var commentLinkIdPrefix = 'comment-';
- var voteNumberClass = "vote-number";
- var offensiveIdPrefixQuestionFlag = 'question-offensive-flag-';
- var offensiveIdPrefixAnswerFlag = 'answer-offensive-flag-';
- var offensiveClassFlag = 'offensive-flag';
- var questionControlsId = 'question-controls';
- var removeQuestionLinkIdPrefix = 'question-delete-link-';
- var removeAnswerLinkIdPrefix = 'answer-delete-link-';
- var questionSubscribeUpdates = 'question-subscribe-updates';
- var questionSubscribeSidebar= 'question-subscribe-sidebar';
-
- var acceptAnonymousMessage = $.i18n._('insufficient privilege');
- var acceptOwnAnswerMessage = $.i18n._('cannot pick own answer as best');
-
- var pleaseLogin = " <a href='" + askbot['urls']['user_signin']
- + "?next=" + askbot['urls']['question_url_template']
- + "'>"
- + $.i18n._('please login') + "</a>";
-
- var favoriteAnonymousMessage = $.i18n._('anonymous users cannot follow questions') + pleaseLogin;
- var subscribeAnonymousMessage = $.i18n._('anonymous users cannot subscribe to questions') + pleaseLogin;
- var voteAnonymousMessage = $.i18n._('anonymous users cannot vote') + pleaseLogin;
- //there were a couple of more messages...
- var offensiveConfirmation = $.i18n._('please confirm offensive');
- var offensiveAnonymousMessage = $.i18n._('anonymous users cannot flag offensive posts') + pleaseLogin;
- var removeConfirmation = $.i18n._('confirm delete');
- var removeAnonymousMessage = $.i18n._('anonymous users cannot delete/undelete') + pleaseLogin;
- var recoveredMessage = $.i18n._('post recovered');
- var deletedMessage = $.i18n._('post deleted');
-
- var VoteType = {
- acceptAnswer : 0,
- questionUpVote : 1,
- questionDownVote : 2,
- favorite : 4,
- answerUpVote: 5,
- answerDownVote:6,
- offensiveQuestion : 7,
- offensiveAnswer:8,
- removeQuestion: 9,
- removeAnswer:10,
- questionSubscribeUpdates:11,
- questionUnsubscribeUpdates:12
- };
-
- var getFavoriteButton = function(){
- var favoriteButton = 'div.'+ voteContainerId +' a[class='+ classPrefixFollow +']';
- favoriteButton += ', div.'+ voteContainerId +' a[class='+ classPrefixFollowed +']';
- return $(favoriteButton);
- };
- var getFavoriteNumber = function(){
- var favoriteNumber = '#'+ divIdFavorite ;
- return $(favoriteNumber);
- };
- var getQuestionVoteUpButton = function(){
- var questionVoteUpButton = 'div.'+ voteContainerId +' img[id^='+ imgIdPrefixQuestionVoteup +']';
- return $(questionVoteUpButton);
- };
- var getQuestionVoteDownButton = function(){
- var questionVoteDownButton = 'div.'+ voteContainerId +' img[id^='+ imgIdPrefixQuestionVotedown +']';
- return $(questionVoteDownButton);
- };
- var getAnswerVoteUpButtons = function(){
- var answerVoteUpButton = 'div.'+ voteContainerId +' img[id^='+ imgIdPrefixAnswerVoteup +']';
- return $(answerVoteUpButton);
- };
- var getAnswerVoteDownButtons = function(){
- var answerVoteDownButton = 'div.'+ voteContainerId +' img[id^='+ imgIdPrefixAnswerVotedown +']';
- return $(answerVoteDownButton);
- };
- var getAnswerVoteUpButton = function(id){
- var answerVoteUpButton = 'div.'+ voteContainerId +' img[id='+ imgIdPrefixAnswerVoteup + id + ']';
- return $(answerVoteUpButton);
- };
- var getAnswerVoteDownButton = function(id){
- var answerVoteDownButton = 'div.'+ voteContainerId +' img[id='+ imgIdPrefixAnswerVotedown + id + ']';
- return $(answerVoteDownButton);
- };
-
- var getOffensiveQuestionFlag = function(){
- var offensiveQuestionFlag = '#question-table span[class='+ offensiveClassFlag +']';
- return $(offensiveQuestionFlag);
- };
-
- var getOffensiveAnswerFlags = function(){
- var offensiveQuestionFlag = 'div.answer span[class='+ offensiveClassFlag +']';
- return $(offensiveQuestionFlag);
- };
-
- var getremoveQuestionLink = function(){
- var removeQuestionLink = 'div#question-controls a[id^='+ removeQuestionLinkIdPrefix +']';
- return $(removeQuestionLink);
- };
-
- var getquestionSubscribeUpdatesCheckbox = function(){
- return $('#' + questionSubscribeUpdates);
- };
-
- var getquestionSubscribeSidebarCheckbox= function(){
- return $('#' + questionSubscribeSidebar);
- };
-
- var getremoveAnswersLinks = function(){
- var removeAnswerLinks = 'div.answer-controls a[id^='+ removeAnswerLinkIdPrefix +']';
- return $(removeAnswerLinks);
- };
-
- var setVoteImage = function(voteType, undo, object){
- var flag = undo ? "" : "-on";
- var arrow = (voteType == VoteType.questionUpVote || voteType == VoteType.answerUpVote) ? "up" : "down";
- object.attr("src", mediaUrl("media/images/vote-arrow-"+ arrow + flag +".png"));
-
- // if undo voting, then undo the pair of arrows.
- if(undo){
- if(voteType == VoteType.questionUpVote || voteType == VoteType.questionDownVote){
- $(getQuestionVoteUpButton()).attr("src", mediaUrl("media/images/vote-arrow-up.png"));
- $(getQuestionVoteDownButton()).attr("src", mediaUrl("media/images/vote-arrow-down.png"));
- }
- else{
- $(getAnswerVoteUpButton(postId)).attr("src", mediaUrl("media/images/vote-arrow-up.png"));
- $(getAnswerVoteDownButton(postId)).attr("src", mediaUrl("media/images/vote-arrow-down.png"));
- }
- }
- };
-
- var setVoteNumber = function(object, number){
- var voteNumber = object.parent('div.'+ voteContainerId).find('div.'+ voteNumberClass);
- $(voteNumber).text(number);
- };
-
- var bindEvents = function(){
- // accept answers
- if(questionAuthorId == currentUserId){
- var acceptedButtons = 'div.'+ voteContainerId +' img[id^='+ imgIdPrefixAccept +']';
- $(acceptedButtons).unbind('click').click(function(event){
- Vote.accept($(event.target));
- });
- }
- // set favorite question
- var favoriteButton = getFavoriteButton();
- favoriteButton.unbind('click').click(function(event){
- //Vote.favorite($(event.target));
- Vote.favorite(favoriteButton);
- });
-
- // question vote up
- var questionVoteUpButton = getQuestionVoteUpButton();
- questionVoteUpButton.unbind('click').click(function(event){
- Vote.vote($(event.target), VoteType.questionUpVote);
- });
-
- var questionVoteDownButton = getQuestionVoteDownButton();
- questionVoteDownButton.unbind('click').click(function(event){
- Vote.vote($(event.target), VoteType.questionDownVote);
- });
-
- var answerVoteUpButton = getAnswerVoteUpButtons();
- answerVoteUpButton.unbind('click').click(function(event){
- Vote.vote($(event.target), VoteType.answerUpVote);
- });
-
- var answerVoteDownButton = getAnswerVoteDownButtons();
- answerVoteDownButton.unbind('click').click(function(event){
- Vote.vote($(event.target), VoteType.answerDownVote);
- });
-
- getOffensiveQuestionFlag().unbind('click').click(function(event){
- Vote.offensive(this, VoteType.offensiveQuestion);
- });
-
- getOffensiveAnswerFlags().unbind('click').click(function(event){
- Vote.offensive(this, VoteType.offensiveAnswer);
- });
-
- getremoveQuestionLink().unbind('click').click(function(event){
- Vote.remove(this, VoteType.removeQuestion);
- });
-
- getquestionSubscribeUpdatesCheckbox().unbind('click').click(function(event){
- //despeluchar esto
- if (this.checked){
- getquestionSubscribeSidebarCheckbox().attr({'checked': true});
- Vote.vote($(event.target), VoteType.questionSubscribeUpdates);
- }
- else {
- getquestionSubscribeSidebarCheckbox().attr({'checked': false});
- Vote.vote($(event.target), VoteType.questionUnsubscribeUpdates);
- }
- });
-
- getquestionSubscribeSidebarCheckbox().unbind('click').click(function(event){
- if (this.checked){
- getquestionSubscribeUpdatesCheckbox().attr({'checked': true});
- Vote.vote($(event.target), VoteType.questionSubscribeUpdates);
- }
- else {
- getquestionSubscribeUpdatesCheckbox().attr({'checked': false});
- Vote.vote($(event.target), VoteType.questionUnsubscribeUpdates);
- }
- });
-
- getremoveAnswersLinks().unbind('click').click(function(event){
- Vote.remove(this, VoteType.removeAnswer);
- });
- };
-
- var submit = function(object, voteType, callback) {
- //this function submits votes
- $.ajax({
- type: "POST",
- cache: false,
- dataType: "json",
- url: askbot['urls']['vote_url_template'].replace('{{QuestionID}}', questionId),
- data: { "type": voteType, "postId": postId },
- error: handleFail,
- success: function(data){callback(object, voteType, data);}
- });
- };
-
- var handleFail = function(xhr, msg){
- alert("Callback invoke error: " + msg);
- };
-
- // callback function for Accept Answer action
- var callback_accept = function(object, voteType, data){
- if(data.allowed == "0" && data.success == "0"){
- showMessage(object, acceptAnonymousMessage);
- }
- else if(data.allowed == "-1"){
- showMessage(object, acceptOwnAnswerMessage);
- }
- else if(data.status == "1"){
- object.attr("src", mediaUrl("media/images/vote-accepted.png"));
- $("#"+answerContainerIdPrefix+postId).removeClass("accepted-answer");
- $("#"+commentLinkIdPrefix+postId).removeClass("comment-link-accepted");
- }
- else if(data.success == "1"){
- var acceptedButtons = 'div.'+ voteContainerId +' img[id^='+ imgIdPrefixAccept +']';
- $(acceptedButtons).attr("src", mediaUrl("media/images/vote-accepted.png"));
- var answers = ("div[id^="+answerContainerIdPrefix +"]");
- $(answers).removeClass("accepted-answer");
- var commentLinks = ("div[id^="+answerContainerIdPrefix +"] div[id^="+ commentLinkIdPrefix +"]");
- $(commentLinks).removeClass("comment-link-accepted");
-
- object.attr("src", mediaUrl("media/images/vote-accepted-on.png"));
- $("#"+answerContainerIdPrefix+postId).addClass("accepted-answer");
- $("#"+commentLinkIdPrefix+postId).addClass("comment-link-accepted");
- }
- else{
- showMessage(object, data.message);
- }
- };
-
- var callback_favorite = function(object, voteType, data){
- if(data.allowed == "0" && data.success == "0"){
- showMessage(
- object,
- favoriteAnonymousMessage.replace(
- '{{QuestionID}}',
- questionId).replace(
- '{{questionSlug}}',
- ''
- )
- );
- }
- else if(data.status == "1"){
- var follow_html = gettext('Follow');
- object.attr("class", 'button follow');
- object.html(follow_html);
- var fav = getFavoriteNumber();
- fav.removeClass("my-favorite-number");
- if(data.count === 0){
- data.count = '';
- fav.text('');
- }else{
- var fmts = ngettext('%s follower', '%s followers', data.count);
- fav.text(interpolate(fmts, [data.count]));
- }
- }
- else if(data.success == "1"){
- var followed_html = gettext('<div>Following</div><div class="unfollow">Unfollow</div>');
- object.html(followed_html);
- object.attr("class", 'button followed');
- var fav = getFavoriteNumber();
- var fmts = ngettext('%s follower', '%s followers', data.count);
- fav.text(interpolate(fmts, [data.count]));
- fav.addClass("my-favorite-number");
- }
- else{
- showMessage(object, data.message);
- }
- };
-
- var callback_vote = function(object, voteType, data){
- if (data.success == '0'){
- showMessage(object, data.message);
- return;
- }
- else {
- if (data.status == '1'){
- setVoteImage(voteType, true, object);
- }
- else {
- setVoteImage(voteType, false, object);
- }
- setVoteNumber(object, data.count);
- if (data.message && data.message.length > 0){
- showMessage(object, data.message);
- }
- return;
- }
- //may need to take a look at this again
- if (data.status == "1"){
- setVoteImage(voteType, true, object);
- setVoteNumber(object, data.count);
- }
- else if (data.success == "1"){
- setVoteImage(voteType, false, object);
- setVoteNumber(object, data.count);
- if (data.message.length > 0){
- showMessage(object, data.message);
- }
- }
- };
-
- var callback_offensive = function(object, voteType, data){
- //todo: transfer proper translations of these from i18n.js
- //to django.po files
- //_('anonymous users cannot flag offensive posts') + pleaseLogin;
- if (data.success == "1"){
- $(object).children('span[class=darkred]').text("("+ data.count +")");
- }
- else {
- object = $(object);
- showMessage(object, data.message)
- }
- };
-
- var callback_remove = function(object, voteType, data){
- if (data.success == "1"){
- if (removeActionType == 'delete'){
- postNode.addClass('deleted');
- postRemoveLink.innerHTML = $.i18n._('undelete');
- showMessage(object, deletedMessage);
- }
- else if (removeActionType == 'undelete') {
- postNode.removeClass('deleted');
- postRemoveLink.innerHTML = $.i18n._('delete');
- showMessage(object, recoveredMessage);
- }
- }
- else {
- showMessage(object, data.message)
- }
- };
-
- return {
- init : function(qId, qSlug, questionAuthor, userId){
- questionId = qId;
- questionSlug = qSlug;
- questionAuthorId = questionAuthor;
- currentUserId = userId;
- bindEvents();
- },
-
- //accept answer
- accept: function(object){
- postId = object.attr("id").substring(imgIdPrefixAccept.length);
- submit(object, VoteType.acceptAnswer, callback_accept);
- },
- //mark question as favorite
- favorite: function(object){
- if (!currentUserId || currentUserId.toUpperCase() == "NONE"){
- showMessage(
- object,
- favoriteAnonymousMessage.replace(
- "{{QuestionID}}",
- questionId
- ).replace(
- '{{questionSlug}}',
- questionSlug
- )
- );
- return false;
- }
- submit(object, VoteType.favorite, callback_favorite);
- },
-
- vote: function(object, voteType){
- if (!currentUserId || currentUserId.toUpperCase() == "NONE"){
- if (voteType == VoteType.questionSubscribeUpdates || voteType == VoteType.questionUnsubscribeUpdates){
- getquestionSubscribeSidebarCheckbox().removeAttr('checked');
- getquestionSubscribeUpdatesCheckbox().removeAttr('checked');
- showMessage(object, subscribeAnonymousMessage);
- }else {
- showMessage(
- $(object),
- voteAnonymousMessage.replace(
- "{{QuestionID}}",
- questionId
- ).replace(
- '{{questionSlug}}',
- questionSlug
- )
- );
- }
- return false;
- }
- // up and downvote processor
- if (voteType == VoteType.answerUpVote){
- postId = object.attr("id").substring(imgIdPrefixAnswerVoteup.length);
- }
- else if (voteType == VoteType.answerDownVote){
- postId = object.attr("id").substring(imgIdPrefixAnswerVotedown.length);
- }
-
- submit(object, voteType, callback_vote);
- },
- //flag offensive
- offensive: function(object, voteType){
- if (!currentUserId || currentUserId.toUpperCase() == "NONE"){
- showMessage(
- $(object),
- offensiveAnonymousMessage.replace(
- "{{QuestionID}}",
- questionId
- ).replace(
- '{{questionSlug}}',
- questionSlug
- )
- );
- return false;
- }
- if (confirm(offensiveConfirmation)){
- postId = object.id.substr(object.id.lastIndexOf('-') + 1);
- submit(object, voteType, callback_offensive);
- }
- },
- //delete question or answer (comments are deleted separately)
- remove: function(object, voteType){
- if (!currentUserId || currentUserId.toUpperCase() == "NONE"){
- showMessage(
- $(object),
- removeAnonymousMessage.replace(
- '{{QuestionID}}',
- questionId
- ).replace(
- '{{questionSlug}}',
- questionSlug
- )
- );
- return false;
- }
- bits = object.id.split('-');
- postId = bits.pop();/* this seems to be used within submit! */
- postType = bits.shift();
-
- var do_proceed = false;
- if (postType == 'answer'){
- postNode = $('#answer-container-' + postId);
- }
- else if (postType == 'question'){
- postNode = $('#question-table');
- }
- postRemoveLink = object;
- if (postNode.hasClass('deleted')){
- removeActionType = 'undelete';
- do_proceed = true;
- }
- else {
- removeActionType = 'delete';
- do_proceed = confirm(removeConfirmation);
- }
- if (do_proceed) {
- submit($(object), voteType, callback_remove);
- }
- }
- };
-} ();
-
-var questionRetagger = function(){
-
- var oldTagsHTML = '';
- var tagInput = null;
- var tagsDiv = null;
- var retagLink = null;
-
- var restoreEventHandlers = function(){
- $(document).unbind('click');
- };
-
- var cancelRetag = function(){
- tagsDiv.html(oldTagsHTML);
- tagsDiv.removeClass('post-retag');
- tagsDiv.addClass('post-tags');
- restoreEventHandlers();
- initRetagger();
- };
-
- var render_tag = function(tag_name){
- //copy-paste from live search!!!
- var tag = new Tag();
- tag.setName(tag_name);
- return tag.getElement().outerHTML();
- };
-
- var drawNewTags = function(new_tags){
- new_tags = new_tags.split(/\s+/);
- var tags_html = ''
- $.each(new_tags, function(index, name){
- tags_html += render_tag(name);
- });
- tagsDiv.html(tags_html);
- };
-
- var doRetag = function(){
- $.ajax({
- type: "POST",
- url: retagUrl,
- dataType: "json",
- data: { tags: getUniqueWords(tagInput.val()).join(' ') },
- success: function(json) {
- if (json['success'] === true){
- new_tags = getUniqueWords(json['new_tags']);
- oldTagsHtml = '';
- cancelRetag();
- drawNewTags(new_tags.join(' '));
- }
- else {
- cancelRetag();
- showMessage(tagsDiv, json['message']);
- }
- },
- error: function(xhr, textStatus, errorThrown) {
- showMessage(tagsDiv, 'sorry, somethin is not right here');
- cancelRetag();
- }
- });
- return false;
- }
-
- var setupInputEventHandlers = function(input){
- input.keydown(function(e){
- if ((e.which && e.which == 27) || (e.keyCode && e.keyCode == 27)){
- cancelRetag();
- }
- });
- $(document).unbind('click').click(cancelRetag, false);
- input.click(function(){return false});
- };
-
- var createRetagForm = function(old_tags_string){
- var div = $('<form method="post"></form>');
- tagInput = $('<input id="retag_tags" type="text" autocomplete="off" name="tags" size="30"/>');
- //var tagLabel = $('<label for="retag_tags" class="error"></label>');
- tagInput.val(old_tags_string);
- //populate input
- var tagAc = new AutoCompleter({
- url: askbot['urls']['get_tag_list'],
- preloadData: true,
- minChars: 1,
- useCache: true,
- matchInside: true,
- maxCacheLength: 100,
- delay: 10
- });
- tagAc.decorate(tagInput);
- div.append(tagInput);
- //div.append(tagLabel);
- setupInputEventHandlers(tagInput);
-
- //button = $('<input type="submit" />');
- //button.val($.i18n._('save tags'));
- //div.append(button);
- //setupButtonEventHandlers(button);
- div.validate({//copy-paste from utils.js
- rules: {
- tags: {
- required: true,
- maxlength: askbot['settings']['maxTagsPerPost'] * askbot['settings']['maxTagLength'],
- limit_tag_count: true,
- limit_tag_length: true
- }
- },
- messages: {
- tags: {
- required: $.i18n._('tags cannot be empty'),
- maxlength: askbot['messages']['tagLimits'],
- limit_tag_count: askbot['messages']['maxTagsPerPost'],
- limit_tag_length: askbot['messages']['maxTagLength']
- }
- },
- submitHandler: doRetag,
- errorClass: "retag-error"
- });
-
- return div;
- };
-
- var getTagsAsString = function(tags_div){
- var links = tags_div.find('a');
- var tags_str = '';
- links.each(function(index, element){
- if (index === 0){
- tags_str = $(element).html();
- }
- else {
- tags_str += ' ' + $(element).html();
- }
- });
- return tags_str;
- };
-
- var noopHandler = function(){
- tagInput.focus();
- return false;
- };
-
- var deactivateRetagLink = function(){
- retagLink.unbind('click').click(noopHandler);
- retagLink.unbind('keypress').keypress(noopHandler);
- };
-
- var startRetag = function(){
- tagsDiv = $('#question-tags');
- oldTagsHTML = tagsDiv.html();//save to restore on cancel
- var old_tags_string = getTagsAsString(tagsDiv);
- var retag_form = createRetagForm(old_tags_string);
- tagsDiv.html('');
- tagsDiv.append(retag_form);
- tagsDiv.removeClass('post-tags');
- tagsDiv.addClass('post-retag');
- tagInput.focus();
- deactivateRetagLink();
- return false;
- };
-
- var setupClickAndEnterHandler = function(element, callback){
- element.unbind('click').click(callback);
- element.unbind('keypress').keypress(function(e){
- if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)){
- callback();
- }
- });
- }
-
- var initRetagger = function(){
- setupClickAndEnterHandler(retagLink, startRetag);
- };
-
- return {
- init: function(){
- retagLink = $('#retag');
- initRetagger();
- }
- };
-}();
-
-//constructor for the form
-var EditCommentForm = function(){
- WrappedElement.call(this);
- this._comment = null;
- this._comment_widget = null;
- this._element = null;
- this._text = '';
- this._id = 'edit-comment-form';
-};
-inherits(EditCommentForm, WrappedElement);
-
-EditCommentForm.prototype.getElement = function(){
- EditCommentForm.superClass_.getElement.call(this);
- this._textarea.val(this._text);
- return this._element;
-};
-
-EditCommentForm.prototype.attachTo = function(comment, mode){
- this._comment = comment;
- this._type = mode;
- this._comment_widget = comment.getContainerWidget();
- this._text = comment.getText();
- comment.getElement().after(this.getElement());
- comment.getElement().hide();
- this._comment_widget.hideButton();
- if (this._type == 'add'){
- this._submit_btn.html($.i18n._('add comment'));
- }
- else {
- this._submit_btn.html($.i18n._('save comment'));
- }
- this.getElement().show();
- this.focus();
- putCursorAtEnd(this._textarea);
-};
-
-EditCommentForm.prototype.getCounterUpdater = function(){
- //returns event handler
- var counter = this._text_counter;
- var handler = function(){
- var textarea = $(this);
- var length = textarea.val() ? textarea.val().length : 0;
- var length1 = maxCommentLength - 100;
- if (length1 < 0){
- length1 = Math.round(0.7*maxCommentLength);
- }
- var length2 = maxCommentLength - 30;
- if (length2 < 0){
- length2 = Math.round(0.9*maxCommentLength);
- }
-
- var color = 'maroon';
- if (length === 0){
- var feedback = $.i18n._('title minchars').replace('{0}', 10);
- }
- else if (length < 10){
- var feedback = $.i18n._('enter more characters').replace('{0}', 10 - length);
- }
- else {
- color = length > length2 ? "#f00" : length > length1 ? "#f60" : "#999";
- var feedback = $.i18n._('{0} characters left')
- .replace('{0}', maxCommentLength - length);
- }
- counter.html(feedback).css('color', color);
- };
- return handler;
-};
-
-EditCommentForm.prototype.canCancel = function(){
- if (this._element === null){
- return true;
- }
- var ctext = $.trim(this._textarea.val());
- if ($.trim(ctext) == $.trim(this._text)){
- return true;
- }
- else if (this.confirmAbandon()){
- return true;
- }
- this.focus();
- return false;
-};
-
-EditCommentForm.prototype.getCancelHandler = function(){
- var form = this;
- return function(){
- if (form.canCancel()){
- form.detach();
- }
- return false;
- };
-};
-
-EditCommentForm.prototype.detach = function(){
- if (this._comment === null){
- return;
- }
- this._comment.getContainerWidget().showButton();
- if (this._comment.isBlank()){
- this._comment.dispose();
- }
- else {
- this._comment.getElement().show();
- }
- this.reset();
- this._element = this._element.detach();
-};
-
-EditCommentForm.prototype.createDom = function(){
- this._element = $('<form></form>');
- this._element.attr('class', 'post-comments');
-
- var div = $('<div></div>');
- this._textarea = $('<textarea></textarea>');
- this._textarea.attr('id', this._id);
-
- /*
- this._help_text = $('<span></span>').attr('class', 'help-text');
- this._help_text.html(gettext('Markdown is allowed in the comments'));
- div.append(this._help_text);
-
- this._help_text = $('<div></div>').attr('class', 'clearfix');
- div.append(this._help_text);
- */
-
- this._element.append(div);
- div.append(this._textarea);
- this._text_counter = $('<span></span>').attr('class', 'counter');
- div.append(this._text_counter);
- this._submit_btn = $('<button class="submit small"></button>');
- div.append(this._submit_btn);
- this._cancel_btn = $('<button class="submit small"></button>');
- this._cancel_btn.html($.i18n._('cancel'));
- div.append(this._cancel_btn);
-
- setupButtonEventHandlers(this._submit_btn, this.getSaveHandler());
- setupButtonEventHandlers(this._cancel_btn, this.getCancelHandler());
-
- var update_counter = this.getCounterUpdater();
- var escape_handler = makeKeyHandler(27, this.getCancelHandler());
- this._textarea.attr('name', 'comment')
- .attr('cols', 60)
- .attr('rows', 5)
- .attr('maxlength', maxCommentLength)
- .blur(update_counter)
- .focus(update_counter)
- .keyup(update_counter)
- .keyup(escape_handler);
- if (askbot['settings']['saveCommentOnEnter']){
- var save_handler = makeKeyHandler(13, this.getSaveHandler());
- this._textarea.keydown(save_handler);
- }
- this._textarea.val(this._text);
-};
-
-EditCommentForm.prototype.enableButtons = function(){
- this._submit_btn.attr('disabled', '');
- this._cancel_btn.attr('disabled', '');
-};
-
-EditCommentForm.prototype.disableButtons = function(){
- this._submit_btn.attr('disabled', 'disabled');
- this._cancel_btn.attr('disabled', 'disabled');
-};
-
-EditCommentForm.prototype.reset = function(){
- this._comment = null;
- this._text = '';
- this._textarea.val('');
- this.enableButtons();
-};
-
-EditCommentForm.prototype.confirmAbandon = function(){
- this.focus(true);
- this._textarea.addClass('highlight');
- var answer = confirm($.i18n._('confirm abandon comment'));
- this._textarea.removeClass('highlight');
- return answer;
-};
-
-EditCommentForm.prototype.focus = function(hard){
- this._textarea.focus();
- if (hard === true){
- $(this._textarea).scrollTop();
- }
-};
-
-EditCommentForm.prototype.getSaveHandler = function(){
-
- var me = this;
- return function(){
- var text = me._textarea.val();
- if (text.length < 10){
- me.focus();
- return false;
- }
-
- var post_data = {
- comment: text
- };
-
- if (me._type == 'edit'){
- post_data['comment_id'] = me._comment.getId();
- post_url = askbot['urls']['editComment'];
- }
- else {
- post_data['post_type'] = me._comment.getParentType();
- post_data['post_id'] = me._comment.getParentId();
- post_url = askbot['urls']['postComments'];
- }
-
- me.disableButtons();
-
- $.ajax({
- type: "POST",
- url: post_url,
- dataType: "json",
- data: post_data,
- success: function(json) {
- if (me._type == 'add'){
- me._comment.dispose();
- me._comment.getContainerWidget().reRenderComments(json);
- }
- else {
- me._comment.setContent(json);
- me._comment.getElement().show();
- }
- me.detach();
- },
- error: function(xhr, textStatus, errorThrown) {
- me._comment.getElement().show();
- showMessage(me._comment.getElement(), xhr.responseText, 'after');
- me.detach();
- me.enableButtons();
- }
- });
- return false;
- };
-};
-
-//a single instance to reuse
-var editCommentForm = new EditCommentForm();
-
-var Comment = function(widget, data){
- WrappedElement.call(this);
- this._container_widget = widget;
- this._data = data || {};
- this._blank = true;//set to false by setContent
- this._element = null;
- this._delete_prompt = $.i18n._('delete this comment');
- if (data && data['is_deletable']){
- this._deletable = data['is_deletable'];
- }
- else {
- this._deletable = false;
- }
- if (data && data['is_editable']){
- this._editable = data['is_deletable'];
- }
- else {
- this._editable = false;
- }
-};
-inherits(Comment, WrappedElement);
-
-Comment.prototype.decorate = function(element){
- this._element = $(element);
- var parent_type = this._element.parent().parent().attr('id').split('-')[2];
- var comment_id = this._element.attr('id').replace('comment-','');
- this._data = {id: comment_id};
- var delete_img = this._element.find('span.delete-icon');
- if (delete_img.length > 0){
- this._deletable = true;
- this._delete_icon = new DeleteIcon(this.deletePrompt);
- this._delete_icon.setHandler(this.getDeleteHandler());
- this._delete_icon.decorate(delete_img);
- }
- var edit_link = this._element.find('a.edit');
- if (edit_link.length > 0){
- this._editable = true;
- this._edit_link = new EditLink();
- this._edit_link.setHandler(this.getEditHandler());
- this._edit_link.decorate(edit_link);
- }
-
- var vote = new CommentVoteButton(this);
- vote.decorate(this._element.find('.comment-votes .upvote'));
-
- this._blank = false;
-};
-
-Comment.prototype.isBlank = function(){
- return this._blank;
-};
-
-Comment.prototype.getId = function(){
- return this._data['id'];
-};
-
-Comment.prototype.hasContent = function(){
- return ('id' in this._data);
- //shortcut for 'user_url' 'html' 'user_display_name' 'comment_age'
-};
-
-Comment.prototype.hasText = function(){
- return ('text' in this._data);
-}
-
-Comment.prototype.getContainerWidget = function(){
- return this._container_widget;
-};
-
-Comment.prototype.getParentType = function(){
- return this._container_widget.getPostType();
-};
-
-Comment.prototype.getParentId = function(){
- return this._container_widget.getPostId();
-};
-
-Comment.prototype.setContent = function(data){
- this._data = data || this._data;
- this._element.html('');
- this._element.attr('class', 'comment');
- this._element.attr('id', 'comment-' + this._data['id']);
-
- var votes = this.makeElement('div');
- votes.addClass('comment-votes');
-
- var vote = new CommentVoteButton(this);
- if (this._data['upvoted_by_user']){
- vote.setVoted(true);
- }
- vote.setScore(this._data['score']);
- votes.append(vote.getElement());
-
- this._element.append(votes);
-
- this._comment_delete = $('<div class="comment-delete"></div>');
- if (this._deletable){
- this._delete_icon = new DeleteIcon(this._delete_prompt);
- this._delete_icon.setHandler(this.getDeleteHandler());
- this._comment_delete.append(this._delete_icon.getElement());
- }
- this._element.append(this._comment_delete);
-
- this._comment_body = $('<div class="comment-body"></div>');
- this._comment_body.html(this._data['html']);
- //this._comment_body.append(' &ndash; ');
-
- this._user_link = $('<a></a>').attr('class', 'author');
- this._user_link.attr('href', this._data['user_url']);
- this._user_link.html(this._data['user_display_name']);
- this._comment_body.append(this._user_link);
-
- this._comment_body.append(' (');
- this._comment_age = $('<span class="age"></span>');
- this._comment_age.html(this._data['comment_age']);
- this._comment_body.append(this._comment_age);
- this._comment_body.append(')');
-
- if (this._editable){
- this._edit_link = new EditLink();
- this._edit_link.setHandler(this.getEditHandler())
- this._comment_body.append(this._edit_link.getElement());
- }
- this._element.append(this._comment_body);
-
- this._blank = false;
-};
-
-Comment.prototype.dispose = function(){
- if (this._comment_body){
- this._comment_body.remove();
- }
- if (this._comment_delete){
- this._comment_delete.remove();
- }
- if (this._user_link){
- this._user_link.remove();
- }
- if (this._comment_age){
- this._comment_age.remove();
- }
- if (this._delete_icon){
- this._delete_icon.dispose();
- }
- if (this._edit_link){
- this._edit_link.dispose();
- }
- this._data = null;
- Comment.superClass_.dispose.call(this);
-};
-
-Comment.prototype.getElement = function(){
- Comment.superClass_.getElement.call(this);
- if (this.isBlank() && this.hasContent()){
- this.setContent();
- if (enableMathJax === true){
- MathJax.Hub.Queue(['Typeset', MathJax.Hub]);
- }
- }
- return this._element;
-};
-
-Comment.prototype.loadText = function(on_load_handler){
- var me = this;
- $.ajax({
- type: "GET",
- url: askbot['urls']['getComment'],
- data: {id: this._data['id']},
- success: function(json){
- me._data['text'] = json['text'];
- on_load_handler()
- },
- error: function(xhr, textStatus, exception) {
- showMessage(me.getElement(), xhr.responseText, 'after');
- }
- });
-};
-
-Comment.prototype.getText = function(){
- if (!this.isBlank()){
- if ('text' in this._data){
- return this._data['text'];
- }
- }
- return '';
-}
-
-Comment.prototype.getEditHandler = function(){
- var comment = this;
- return function(){
- if (editCommentForm.canCancel()){
- editCommentForm.detach();
- if (comment.hasText()){
- editCommentForm.attachTo(comment, 'edit');
- }
- else {
- comment.loadText(
- function(){
- editCommentForm.attachTo(comment, 'edit');
- }
- );
- }
- }
- };
-};
-
-Comment.prototype.getDeleteHandler = function(){
- var comment = this;
- var del_icon = this._delete_icon;
- return function(){
- if (confirm($.i18n._('confirm delete comment'))){
- comment.getElement().hide();
- $.ajax({
- type: 'POST',
- url: askbot['urls']['deleteComment'],
- data: { comment_id: comment.getId() },
- success: function(json, textStatus, xhr) {
- comment.dispose();
- },
- error: function(xhr, textStatus, exception) {
- comment.getElement().show()
- showMessage(del_icon.getElement(), xhr.responseText);
- },
- dataType: "json"
- });
- }
- };
-};
-
-var PostCommentsWidget = function(){
- WrappedElement.call(this);
- this._denied = false;
-};
-inherits(PostCommentsWidget, WrappedElement);
-
-PostCommentsWidget.prototype.decorate = function(element){
- var element = $(element);
- this._element = element;
-
- var widget_id = element.attr('id');
- var id_bits = widget_id.split('-');
- this._post_id = id_bits[3];
- this._post_type = id_bits[2];
- this._is_truncated = askbot['data'][widget_id]['truncated'];
- this._user_can_post = askbot['data'][widget_id]['can_post'];
-
- //see if user can comment here
- var controls = element.find('.controls');
- this._activate_button = controls.find('.button');
-
- if (this._user_can_post == false){
- setupButtonEventHandlers(
- this._activate_button,
- this.getReadOnlyLoadHandler()
- );
- }
- else {
- setupButtonEventHandlers(
- this._activate_button,
- this.getActivateHandler()
- );
- }
-
- this._cbox = element.find('.content');
- var comments = new Array();
- var me = this;
- this._cbox.children().each(function(index, element){
- var comment = new Comment(me);
- comments.push(comment)
- comment.decorate(element);
- });
- this._comments = comments;
-};
-
-PostCommentsWidget.prototype.getPostType = function(){
- return this._post_type;
-};
-
-PostCommentsWidget.prototype.getPostId = function(){
- return this._post_id;
-};
-
-PostCommentsWidget.prototype.hideButton = function(){
- this._activate_button.hide();
-};
-
-PostCommentsWidget.prototype.showButton = function(){
- if (this._is_truncated === false){
- this._activate_button.html(askbot['messages']['addComment']);
- }
- this._activate_button.show();
-}
-
-PostCommentsWidget.prototype.startNewComment = function(){
- var comment = new Comment(this);
- this._cbox.append(comment.getElement());
- editCommentForm.attachTo(comment, 'add');
-};
-
-PostCommentsWidget.prototype.needToReload = function(){
- return this._is_truncated;
-};
-
-PostCommentsWidget.prototype.getActivateHandler = function(){
- var me = this;
- return function() {
- if (editCommentForm.canCancel()){
- editCommentForm.detach();
- if (me.needToReload()){
- me.reloadAllComments(function(json){
- me.reRenderComments(json);
- me.startNewComment();
- });
- }
- else {
- me.startNewComment();
- }
- }
- };
-};
-
-PostCommentsWidget.prototype.getReadOnlyLoadHandler = function(){
- var me = this;
- return function(){
- me.reloadAllComments(function(json){
- me.reRenderComments(json);
- me._activate_button.remove();
- });
- };
-};
-
-
-PostCommentsWidget.prototype.reloadAllComments = function(callback){
- var post_data = {post_id: this._post_id, post_type: this._post_type};
- var me = this;
- $.ajax({
- type: "GET",
- url: askbot['urls']['postComments'],
- data: post_data,
- success: function(json){
- callback(json);
- me._is_truncated = false;
- },
- dataType: "json"
- });
-};
-
-PostCommentsWidget.prototype.reRenderComments = function(json){
- $.each(this._comments, function(i, item){
- item.dispose();
- });
- this._comments = new Array();
- var me = this;
- $.each(json, function(i, item){
- var comment = new Comment(me, item);
- me._cbox.append(comment.getElement());
- me._comments.push(comment);
- });
-};
-
-
-var socialSharing = function(){
-
- var SERVICE_DATA = {
- //url - template for the sharing service url, params are for the popup
- identica: {
- url: "http://identi.ca/notice/new?status_textarea={TEXT}%20{URL}",
- params: "width=820, height=526,toolbar=1,status=1,resizable=1,scrollbars=1"
- },
- twitter: {
- url: "http://twitter.com/share?url={URL}&ref=twitbtn&text={TEXT}",
- params: "width=820,height=526,toolbar=1,status=1,resizable=1,scrollbars=1"
- },
- facebook: {
- url: "http://www.facebook.com/sharer.php?u={URL}&ref=fbshare&t={TEXT}",
- params: "width=630,height=436,toolbar=1,status=1,resizable=1,scrollbars=1"
- },
- linkedin: {
- url: "http://www.linkedin.com/shareArticle?mini=true&amp;url={URL}&amp;source={TEXT}",
- params: "width=630,height=436,toolbar=1,status=1,resizable=1,scrollbars=1"
- }
- };
- var URL = "";
- var TEXT = "";
-
- var share_page = function(service_name){
- if (SERVICE_DATA[service_name]){
- var url = SERVICE_DATA[service_name]['url'];
- $.ajax({
- async: false,
- url: "http://json-tinyurl.appspot.com/?&callback=?",
- dataType: "json",
- data: {'url':URL},
- success: function(data){
- url = url.replace('{URL}', data.tinyurl);
- },
- error: function(data){
- url = url.replace('{URL}', URL);
- },
- complete: function(data){
- url = url.replace('{TEXT}', TEXT);
- var params = SERVICE_DATA[service_name]['params'];
- if(!window.open(url, "sharing", params)){
- window.location.href=share_url;
- }
- }
- });
- }
- }
-
- return {
- init: function(){
- URL = window.location.href;
- TEXT = escape($('h1 > a').html());
- var fb = $('a.facebook-share')
- var tw = $('a.twitter-share');
- var ln = $('a.linkedin-share');
- var ica = $('a.identica-share');
- copyAltToTitle(fb);
- copyAltToTitle(tw);
- copyAltToTitle(ln);
- copyAltToTitle(ica);
- setupButtonEventHandlers(fb, function(){share_page("facebook")});
- setupButtonEventHandlers(tw, function(){share_page("twitter")});
- setupButtonEventHandlers(ln, function(){share_page("linkedin")});
- setupButtonEventHandlers(ica, function(){share_page("identica")});
- }
- }
-}();
-
-/**
- * @constructor
- * @extends {SimpleControl}
- */
-var QASwapper = function(){
- SimpleControl.call(this);
- this._ans_id = null;
-};
-inherits(QASwapper, SimpleControl);
-
-QASwapper.prototype.decorate = function(element){
- this._element = element;
- this._ans_id = parseInt(element.attr('id').split('-').pop());
- var me = this;
- this.setHandler(function(){
- me.startSwapping();
- });
-};
-
-QASwapper.prototype.startSwapping = function(){
- while (true){
- var title = prompt(gettext('Please enter question title (>10 characters)'));
- if (title.length >= 10){
- var data = {new_title: title, answer_id: this._ans_id};
- $.ajax({
- type: "POST",
- cache: false,
- dataType: "json",
- url: askbot['urls']['swap_question_with_answer'],
- data: data,
- success: function(data){
- var url_template = askbot['urls']['question_url_template'];
- new_question_url = url_template.replace(
- '{{QuestionID}}',
- data['id']
- ).replace(
- '{{questionSlug}}',
- data['slug']
- );
- window.location.href = new_question_url;
- }
- });
- break;
- }
- }
-};
-
-$(document).ready(function() {
- $('[id^="comments-for-"]').each(function(index, element){
- var comments = new PostCommentsWidget();
- comments.decorate(element);
- });
- $('[id^="swap-question-with-answer-"]').each(function(idx, element){
- var swapper = new QASwapper();
- swapper.decorate($(element));
- });
- questionRetagger.init();
- socialSharing.init();
-});
-
-
-/*
-Prettify
-http://www.apache.org/licenses/LICENSE-2.0
-*/
-var PR_SHOULD_USE_CONTINUATION = true; var PR_TAB_WIDTH = 8; var PR_normalizedHtml; var PR; var prettyPrintOne; var prettyPrint; function _pr_isIE6() { var isIE6 = navigator && navigator.userAgent && /\bMSIE 6\./.test(navigator.userAgent); _pr_isIE6 = function() { return isIE6; }; return isIE6; } (function() { function wordSet(words) { words = words.split(/ /g); var set = {}; for (var i = words.length; --i >= 0; ) { var w = words[i]; if (w) { set[w] = null; } } return set; } var FLOW_CONTROL_KEYWORDS = "break continue do else for if return while "; var C_KEYWORDS = FLOW_CONTROL_KEYWORDS + "auto case char const default " + "double enum extern float goto int long register short signed sizeof " + "static struct switch typedef union unsigned void volatile "; var COMMON_KEYWORDS = C_KEYWORDS + "catch class delete false import " + "new operator private protected public this throw true try "; var CPP_KEYWORDS = COMMON_KEYWORDS + "alignof align_union asm axiom bool " + "concept concept_map const_cast constexpr decltype " + "dynamic_cast explicit export friend inline late_check " + "mutable namespace nullptr reinterpret_cast static_assert static_cast " + "template typeid typename typeof using virtual wchar_t where "; var JAVA_KEYWORDS = COMMON_KEYWORDS + "boolean byte extends final finally implements import instanceof null " + "native package strictfp super synchronized throws transient "; var CSHARP_KEYWORDS = JAVA_KEYWORDS + "as base by checked decimal delegate descending event " + "fixed foreach from group implicit in interface internal into is lock " + "object out override orderby params readonly ref sbyte sealed " + "stackalloc string select uint ulong unchecked unsafe ushort var "; var JSCRIPT_KEYWORDS = COMMON_KEYWORDS + "debugger eval export function get null set undefined var with " + "Infinity NaN "; var PERL_KEYWORDS = "caller delete die do dump elsif eval exit foreach for " + "goto if import last local my next no our print package redo require " + "sub undef unless until use wantarray while BEGIN END "; var PYTHON_KEYWORDS = FLOW_CONTROL_KEYWORDS + "and as assert class def del " + "elif except exec finally from global import in is lambda " + "nonlocal not or pass print raise try with yield " + "False True None "; var RUBY_KEYWORDS = FLOW_CONTROL_KEYWORDS + "alias and begin case class def" + " defined elsif end ensure false in module next nil not or redo rescue " + "retry self super then true undef unless until when yield BEGIN END "; var SH_KEYWORDS = FLOW_CONTROL_KEYWORDS + "case done elif esac eval fi " + "function in local set then until "; var ALL_KEYWORDS = (CPP_KEYWORDS + CSHARP_KEYWORDS + JSCRIPT_KEYWORDS + PERL_KEYWORDS + PYTHON_KEYWORDS + RUBY_KEYWORDS + SH_KEYWORDS); var PR_STRING = 'str'; var PR_KEYWORD = 'kwd'; var PR_COMMENT = 'com'; var PR_TYPE = 'typ'; var PR_LITERAL = 'lit'; var PR_PUNCTUATION = 'pun'; var PR_PLAIN = 'pln'; var PR_TAG = 'tag'; var PR_DECLARATION = 'dec'; var PR_SOURCE = 'src'; var PR_ATTRIB_NAME = 'atn'; var PR_ATTRIB_VALUE = 'atv'; var PR_NOCODE = 'nocode'; function isWordChar(ch) { return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'); } function spliceArrayInto(inserted, container, containerPosition, countReplaced) { inserted.unshift(containerPosition, countReplaced || 0); try { container.splice.apply(container, inserted); } finally { inserted.splice(0, 2); } } var REGEXP_PRECEDER_PATTERN = function() { var preceders = ["!", "!=", "!==", "#", "%", "%=", "&", "&&", "&&=", "&=", "(", "*", "*=", "+=", ",", "-=", "->", "/", "/=", ":", "::", ";", "<", "<<", "<<=", "<=", "=", "==", "===", ">", ">=", ">>", ">>=", ">>>", ">>>=", "?", "@", "[", "^", "^=", "^^", "^^=", "{", "|", "|=", "||", "||=", "~", "break", "case", "continue", "delete", "do", "else", "finally", "instanceof", "return", "throw", "try", "typeof"]; var pattern = '(?:' + '(?:(?:^|[^0-9.])\\.{1,3})|' + '(?:(?:^|[^\\+])\\+)|' + '(?:(?:^|[^\\-])-)'; for (var i = 0; i < preceders.length; ++i) { var preceder = preceders[i]; if (isWordChar(preceder.charAt(0))) { pattern += '|\\b' + preceder; } else { pattern += '|' + preceder.replace(/([^=<>:&])/g, '\\$1'); } } pattern += '|^)\\s*$'; return new RegExp(pattern); } (); var pr_amp = /&/g; var pr_lt = /</g; var pr_gt = />/g; var pr_quot = /\"/g; function attribToHtml(str) { return str.replace(pr_amp, '&amp;').replace(pr_lt, '&lt;').replace(pr_gt, '&gt;').replace(pr_quot, '&quot;'); } function textToHtml(str) { return str.replace(pr_amp, '&amp;').replace(pr_lt, '&lt;').replace(pr_gt, '&gt;'); } var pr_ltEnt = /&lt;/g; var pr_gtEnt = /&gt;/g; var pr_aposEnt = /&apos;/g; var pr_quotEnt = /&quot;/g; var pr_ampEnt = /&amp;/g; var pr_nbspEnt = /&nbsp;/g; function htmlToText(html) { var pos = html.indexOf('&'); if (pos < 0) { return html; } for (--pos; (pos = html.indexOf('&#', pos + 1)) >= 0; ) { var end = html.indexOf(';', pos); if (end >= 0) { var num = html.substring(pos + 3, end); var radix = 10; if (num && num.charAt(0) === 'x') { num = num.substring(1); radix = 16; } var codePoint = parseInt(num, radix); if (!isNaN(codePoint)) { html = (html.substring(0, pos) + String.fromCharCode(codePoint) + html.substring(end + 1)); } } } return html.replace(pr_ltEnt, '<').replace(pr_gtEnt, '>').replace(pr_aposEnt, "'").replace(pr_quotEnt, '"').replace(pr_ampEnt, '&').replace(pr_nbspEnt, ' '); } function isRawContent(node) { return 'XMP' === node.tagName; } function normalizedHtml(node, out) { switch (node.nodeType) { case 1: var name = node.tagName.toLowerCase(); out.push('<', name); for (var i = 0; i < node.attributes.length; ++i) { var attr = node.attributes[i]; if (!attr.specified) { continue; } out.push(' '); normalizedHtml(attr, out); } out.push('>'); for (var child = node.firstChild; child; child = child.nextSibling) { normalizedHtml(child, out); } if (node.firstChild || !/^(?:br|link|img)$/.test(name)) { out.push('<\/', name, '>'); } break; case 2: out.push(node.name.toLowerCase(), '="', attribToHtml(node.value), '"'); break; case 3: case 4: out.push(textToHtml(node.nodeValue)); break; } } var PR_innerHtmlWorks = null; function getInnerHtml(node) { if (null === PR_innerHtmlWorks) { var testNode = document.createElement('PRE'); testNode.appendChild(document.createTextNode('<!DOCTYPE foo PUBLIC "foo bar">\n<foo />')); PR_innerHtmlWorks = !/</.test(testNode.innerHTML); } if (PR_innerHtmlWorks) { var content = node.innerHTML; if (isRawContent(node)) { content = textToHtml(content); } return content; } var out = []; for (var child = node.firstChild; child; child = child.nextSibling) { normalizedHtml(child, out); } return out.join(''); } function makeTabExpander(tabWidth) { var SPACES = ' '; var charInLine = 0; return function(plainText) { var out = null; var pos = 0; for (var i = 0, n = plainText.length; i < n; ++i) { var ch = plainText.charAt(i); switch (ch) { case '\t': if (!out) { out = []; } out.push(plainText.substring(pos, i)); var nSpaces = tabWidth - (charInLine % tabWidth); charInLine += nSpaces; for (; nSpaces >= 0; nSpaces -= SPACES.length) { out.push(SPACES.substring(0, nSpaces)); } pos = i + 1; break; case '\n': charInLine = 0; break; default: ++charInLine; } } if (!out) { return plainText; } out.push(plainText.substring(pos)); return out.join(''); }; } var pr_chunkPattern = /(?:[^<]+|<!--[\s\S]*?-->|<!\[CDATA\[([\s\S]*?)\]\]>|<\/?[a-zA-Z][^>]*>|<)/g; var pr_commentPrefix = /^<!--/; var pr_cdataPrefix = /^<\[CDATA\[/; var pr_brPrefix = /^<br\b/i; var pr_tagNameRe = /^<(\/?)([a-zA-Z]+)/; function extractTags(s) { var matches = s.match(pr_chunkPattern); var sourceBuf = []; var sourceBufLen = 0; var extractedTags = []; if (matches) { for (var i = 0, n = matches.length; i < n; ++i) { var match = matches[i]; if (match.length > 1 && match.charAt(0) === '<') { if (pr_commentPrefix.test(match)) { continue; } if (pr_cdataPrefix.test(match)) { sourceBuf.push(match.substring(9, match.length - 3)); sourceBufLen += match.length - 12; } else if (pr_brPrefix.test(match)) { sourceBuf.push('\n'); ++sourceBufLen; } else { if (match.indexOf(PR_NOCODE) >= 0 && isNoCodeTag(match)) { var name = match.match(pr_tagNameRe)[2]; var depth = 1; end_tag_loop: for (var j = i + 1; j < n; ++j) { var name2 = matches[j].match(pr_tagNameRe); if (name2 && name2[2] === name) { if (name2[1] === '/') { if (--depth === 0) { break end_tag_loop; } } else { ++depth; } } } if (j < n) { extractedTags.push(sourceBufLen, matches.slice(i, j + 1).join('')); i = j; } else { extractedTags.push(sourceBufLen, match); } } else { extractedTags.push(sourceBufLen, match); } } } else { var literalText = htmlToText(match); sourceBuf.push(literalText); sourceBufLen += literalText.length; } } } return { source: sourceBuf.join(''), tags: extractedTags }; } function isNoCodeTag(tag) { return !!tag.replace(/\s(\w+)\s*=\s*(?:\"([^\"]*)\"|'([^\']*)'|(\S+))/g, ' $1="$2$3$4"').match(/[cC][lL][aA][sS][sS]=\"[^\"]*\bnocode\b/); } function createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns) { var shortcuts = {}; (function() { var allPatterns = shortcutStylePatterns.concat(fallthroughStylePatterns); for (var i = allPatterns.length; --i >= 0; ) { var patternParts = allPatterns[i]; var shortcutChars = patternParts[3]; if (shortcutChars) { for (var c = shortcutChars.length; --c >= 0; ) { shortcuts[shortcutChars.charAt(c)] = patternParts; } } } })(); var nPatterns = fallthroughStylePatterns.length; var notWs = /\S/; return function(sourceCode, opt_basePos) { opt_basePos = opt_basePos || 0; var decorations = [opt_basePos, PR_PLAIN]; var lastToken = ''; var pos = 0; var tail = sourceCode; while (tail.length) { var style; var token = null; var match; var patternParts = shortcuts[tail.charAt(0)]; if (patternParts) { match = tail.match(patternParts[1]); token = match[0]; style = patternParts[0]; } else { for (var i = 0; i < nPatterns; ++i) { patternParts = fallthroughStylePatterns[i]; var contextPattern = patternParts[2]; if (contextPattern && !contextPattern.test(lastToken)) { continue; } match = tail.match(patternParts[1]); if (match) { token = match[0]; style = patternParts[0]; break; } } if (!token) { style = PR_PLAIN; token = tail.substring(0, 1); } } decorations.push(opt_basePos + pos, style); pos += token.length; tail = tail.substring(token.length); if (style !== PR_COMMENT && notWs.test(token)) { lastToken = token; } } return decorations; }; } var PR_MARKUP_LEXER = createSimpleLexer([], [[PR_PLAIN, /^[^<]+/, null], [PR_DECLARATION, /^<!\w[^>]*(?:>|$)/, null], [PR_COMMENT, /^<!--[\s\S]*?(?:-->|$)/, null], [PR_SOURCE, /^<\?[\s\S]*?(?:\?>|$)/, null], [PR_SOURCE, /^<%[\s\S]*?(?:%>|$)/, null], [PR_SOURCE, /^<(script|style|xmp)\b[^>]*>[\s\S]*?<\/\1\b[^>]*>/i, null], [PR_TAG, /^<\/?\w[^<>]*>/, null]]); var PR_SOURCE_CHUNK_PARTS = /^(<[^>]*>)([\s\S]*)(<\/[^>]*>)$/; function tokenizeMarkup(source) { var decorations = PR_MARKUP_LEXER(source); for (var i = 0; i < decorations.length; i += 2) { if (decorations[i + 1] === PR_SOURCE) { var start, end; start = decorations[i]; end = i + 2 < decorations.length ? decorations[i + 2] : source.length; var sourceChunk = source.substring(start, end); var match = sourceChunk.match(PR_SOURCE_CHUNK_PARTS); if (match) { decorations.splice(i, 2, start, PR_TAG, start + match[1].length, PR_SOURCE, start + match[1].length + (match[2] || '').length, PR_TAG); } } } return decorations; } var PR_TAG_LEXER = createSimpleLexer([[PR_ATTRIB_VALUE, /^\'[^\']*(?:\'|$)/, null, "'"], [PR_ATTRIB_VALUE, /^\"[^\"]*(?:\"|$)/, null, '"'], [PR_PUNCTUATION, /^[<>\/=]+/, null, '<>/=']], [[PR_TAG, /^[\w:\-]+/, /^</], [PR_ATTRIB_VALUE, /^[\w\-]+/, /^=/], [PR_ATTRIB_NAME, /^[\w:\-]+/, null], [PR_PLAIN, /^\s+/, null, ' \t\r\n']]); function splitTagAttributes(source, decorations) { for (var i = 0; i < decorations.length; i += 2) { var style = decorations[i + 1]; if (style === PR_TAG) { var start, end; start = decorations[i]; end = i + 2 < decorations.length ? decorations[i + 2] : source.length; var chunk = source.substring(start, end); var subDecorations = PR_TAG_LEXER(chunk, start); spliceArrayInto(subDecorations, decorations, i, 2); i += subDecorations.length - 2; } } return decorations; } function sourceDecorator(options) { var shortcutStylePatterns = [], fallthroughStylePatterns = []; if (options.tripleQuotedStrings) { shortcutStylePatterns.push([PR_STRING, /^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/, null, '\'"']); } else if (options.multiLineStrings) { shortcutStylePatterns.push([PR_STRING, /^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/, null, '\'"`']); } else { shortcutStylePatterns.push([PR_STRING, /^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/, null, '"\'']); } fallthroughStylePatterns.push([PR_PLAIN, /^(?:[^\'\"\`\/\#]+)/, null, ' \r\n']); if (options.hashComments) { shortcutStylePatterns.push([PR_COMMENT, /^#[^\r\n]*/, null, '#']); } if (options.cStyleComments) { fallthroughStylePatterns.push([PR_COMMENT, /^\/\/[^\r\n]*/, null]); fallthroughStylePatterns.push([PR_COMMENT, /^\/\*[\s\S]*?(?:\*\/|$)/, null]); } if (options.regexLiterals) { var REGEX_LITERAL = ('^/(?=[^/*])' + '(?:[^/\\x5B\\x5C]' + '|\\x5C[\\s\\S]' + '|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+' + '(?:/|$)'); fallthroughStylePatterns.push([PR_STRING, new RegExp(REGEX_LITERAL), REGEXP_PRECEDER_PATTERN]); } var keywords = wordSet(options.keywords); options = null; var splitStringAndCommentTokens = createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns); var styleLiteralIdentifierPuncRecognizer = createSimpleLexer([], [[PR_PLAIN, /^\s+/, null, ' \r\n'], [PR_PLAIN, /^[a-z_$@][a-z_$@0-9]*/i, null], [PR_LITERAL, /^0x[a-f0-9]+[a-z]/i, null], [PR_LITERAL, /^(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d+)(?:e[+\-]?\d+)?[a-z]*/i, null, '123456789'], [PR_PUNCTUATION, /^[^\s\w\.$@]+/, null]]); function splitNonStringNonCommentTokens(source, decorations) { for (var i = 0; i < decorations.length; i += 2) { var style = decorations[i + 1]; if (style === PR_PLAIN) { var start, end, chunk, subDecs; start = decorations[i]; end = i + 2 < decorations.length ? decorations[i + 2] : source.length; chunk = source.substring(start, end); subDecs = styleLiteralIdentifierPuncRecognizer(chunk, start); for (var j = 0, m = subDecs.length; j < m; j += 2) { var subStyle = subDecs[j + 1]; if (subStyle === PR_PLAIN) { var subStart = subDecs[j]; var subEnd = j + 2 < m ? subDecs[j + 2] : chunk.length; var token = source.substring(subStart, subEnd); if (token === '.') { subDecs[j + 1] = PR_PUNCTUATION; } else if (token in keywords) { subDecs[j + 1] = PR_KEYWORD; } else if (/^@?[A-Z][A-Z$]*[a-z][A-Za-z$]*$/.test(token)) { subDecs[j + 1] = token.charAt(0) === '@' ? PR_LITERAL : PR_TYPE; } } } spliceArrayInto(subDecs, decorations, i, 2); i += subDecs.length - 2; } } return decorations; } return function(sourceCode) { var decorations = splitStringAndCommentTokens(sourceCode); decorations = splitNonStringNonCommentTokens(sourceCode, decorations); return decorations; }; } var decorateSource = sourceDecorator({ keywords: ALL_KEYWORDS, hashComments: true, cStyleComments: true, multiLineStrings: true, regexLiterals: true }); function splitSourceNodes(source, decorations) { for (var i = 0; i < decorations.length; i += 2) { var style = decorations[i + 1]; if (style === PR_SOURCE) { var start, end; start = decorations[i]; end = i + 2 < decorations.length ? decorations[i + 2] : source.length; var subDecorations = decorateSource(source.substring(start, end)); for (var j = 0, m = subDecorations.length; j < m; j += 2) { subDecorations[j] += start; } spliceArrayInto(subDecorations, decorations, i, 2); i += subDecorations.length - 2; } } return decorations; } function splitSourceAttributes(source, decorations) { var nextValueIsSource = false; for (var i = 0; i < decorations.length; i += 2) { var style = decorations[i + 1]; var start, end; if (style === PR_ATTRIB_NAME) { start = decorations[i]; end = i + 2 < decorations.length ? decorations[i + 2] : source.length; nextValueIsSource = /^on|^style$/i.test(source.substring(start, end)); } else if (style === PR_ATTRIB_VALUE) { if (nextValueIsSource) { start = decorations[i]; end = i + 2 < decorations.length ? decorations[i + 2] : source.length; var attribValue = source.substring(start, end); var attribLen = attribValue.length; var quoted = (attribLen >= 2 && /^[\"\']/.test(attribValue) && attribValue.charAt(0) === attribValue.charAt(attribLen - 1)); var attribSource; var attribSourceStart; var attribSourceEnd; if (quoted) { attribSourceStart = start + 1; attribSourceEnd = end - 1; attribSource = attribValue; } else { attribSourceStart = start + 1; attribSourceEnd = end - 1; attribSource = attribValue.substring(1, attribValue.length - 1); } var attribSourceDecorations = decorateSource(attribSource); for (var j = 0, m = attribSourceDecorations.length; j < m; j += 2) { attribSourceDecorations[j] += attribSourceStart; } if (quoted) { attribSourceDecorations.push(attribSourceEnd, PR_ATTRIB_VALUE); spliceArrayInto(attribSourceDecorations, decorations, i + 2, 0); } else { spliceArrayInto(attribSourceDecorations, decorations, i, 2); } } nextValueIsSource = false; } } return decorations; } function decorateMarkup(sourceCode) { var decorations = tokenizeMarkup(sourceCode); decorations = splitTagAttributes(sourceCode, decorations); decorations = splitSourceNodes(sourceCode, decorations); decorations = splitSourceAttributes(sourceCode, decorations); return decorations; } function recombineTagsAndDecorations(sourceText, extractedTags, decorations) { var html = []; var outputIdx = 0; var openDecoration = null; var currentDecoration = null; var tagPos = 0; var decPos = 0; var tabExpander = makeTabExpander(PR_TAB_WIDTH); var adjacentSpaceRe = /([\r\n ]) /g; var startOrSpaceRe = /(^| ) /gm; var newlineRe = /\r\n?|\n/g; var trailingSpaceRe = /[ \r\n]$/; var lastWasSpace = true; function emitTextUpTo(sourceIdx) { if (sourceIdx > outputIdx) { if (openDecoration && openDecoration !== currentDecoration) { html.push('</span>'); openDecoration = null; } if (!openDecoration && currentDecoration) { openDecoration = currentDecoration; html.push('<span class="', openDecoration, '">'); } var htmlChunk = textToHtml(tabExpander(sourceText.substring(outputIdx, sourceIdx))).replace(lastWasSpace ? startOrSpaceRe : adjacentSpaceRe, '$1&nbsp;'); lastWasSpace = trailingSpaceRe.test(htmlChunk); html.push(htmlChunk.replace(newlineRe, '<br />')); outputIdx = sourceIdx; } } while (true) { var outputTag; if (tagPos < extractedTags.length) { if (decPos < decorations.length) { outputTag = extractedTags[tagPos] <= decorations[decPos]; } else { outputTag = true; } } else { outputTag = false; } if (outputTag) { emitTextUpTo(extractedTags[tagPos]); if (openDecoration) { html.push('</span>'); openDecoration = null; } html.push(extractedTags[tagPos + 1]); tagPos += 2; } else if (decPos < decorations.length) { emitTextUpTo(decorations[decPos]); currentDecoration = decorations[decPos + 1]; decPos += 2; } else { break; } } emitTextUpTo(sourceText.length); if (openDecoration) { html.push('</span>'); } return html.join(''); } var langHandlerRegistry = {}; function registerLangHandler(handler, fileExtensions) { for (var i = fileExtensions.length; --i >= 0; ) { var ext = fileExtensions[i]; if (!langHandlerRegistry.hasOwnProperty(ext)) { langHandlerRegistry[ext] = handler; } else if ('console' in window) { console.log('cannot override language handler %s', ext); } } } registerLangHandler(decorateSource, ['default-code']); registerLangHandler(decorateMarkup, ['default-markup', 'html', 'htm', 'xhtml', 'xml', 'xsl']); registerLangHandler(sourceDecorator({ keywords: CPP_KEYWORDS, hashComments: true, cStyleComments: true }), ['c', 'cc', 'cpp', 'cs', 'cxx', 'cyc']); registerLangHandler(sourceDecorator({ keywords: JAVA_KEYWORDS, cStyleComments: true }), ['java']); registerLangHandler(sourceDecorator({ keywords: SH_KEYWORDS, hashComments: true, multiLineStrings: true }), ['bsh', 'csh', 'sh']); registerLangHandler(sourceDecorator({ keywords: PYTHON_KEYWORDS, hashComments: true, multiLineStrings: true, tripleQuotedStrings: true }), ['cv', 'py']); registerLangHandler(sourceDecorator({ keywords: PERL_KEYWORDS, hashComments: true, multiLineStrings: true, regexLiterals: true }), ['perl', 'pl', 'pm']); registerLangHandler(sourceDecorator({ keywords: RUBY_KEYWORDS, hashComments: true, multiLineStrings: true, regexLiterals: true }), ['rb']); registerLangHandler(sourceDecorator({ keywords: JSCRIPT_KEYWORDS, cStyleComments: true, regexLiterals: true }), ['js']); function prettyPrintOne(sourceCodeHtml, opt_langExtension) { try { var sourceAndExtractedTags = extractTags(sourceCodeHtml); var source = sourceAndExtractedTags.source; var extractedTags = sourceAndExtractedTags.tags; if (!langHandlerRegistry.hasOwnProperty(opt_langExtension)) { opt_langExtension = /^\s*</.test(source) ? 'default-markup' : 'default-code'; } var decorations = langHandlerRegistry[opt_langExtension].call({}, source); return recombineTagsAndDecorations(source, extractedTags, decorations); } catch (e) { if ('console' in window) { console.log(e); console.trace(); } return sourceCodeHtml; } } function prettyPrint(opt_whenDone) { var isIE6 = _pr_isIE6(); var codeSegments = [document.getElementsByTagName('pre'), document.getElementsByTagName('code'), document.getElementsByTagName('xmp')]; var elements = []; for (var i = 0; i < codeSegments.length; ++i) { for (var j = 0; j < codeSegments[i].length; ++j) { elements.push(codeSegments[i][j]); } } codeSegments = null; var k = 0; function doWork() { var endTime = (PR_SHOULD_USE_CONTINUATION ? new Date().getTime() + 250 : Infinity); for (; k < elements.length && new Date().getTime() < endTime; k++) { var cs = elements[k]; if (cs.className && cs.className.indexOf('prettyprint') >= 0) { var langExtension = cs.className.match(/\blang-(\w+)\b/); if (langExtension) { langExtension = langExtension[1]; } var nested = false; for (var p = cs.parentNode; p; p = p.parentNode) { if ((p.tagName === 'pre' || p.tagName === 'code' || p.tagName === 'xmp') && p.className && p.className.indexOf('prettyprint') >= 0) { nested = true; break; } } if (!nested) { var content = getInnerHtml(cs); content = content.replace(/(?:\r\n?|\n)$/, ''); var newContent = prettyPrintOne(content, langExtension); if (!isRawContent(cs)) { cs.innerHTML = newContent; } else { var pre = document.createElement('PRE'); for (var i = 0; i < cs.attributes.length; ++i) { var a = cs.attributes[i]; if (a.specified) { var aname = a.name.toLowerCase(); if (aname === 'class') { pre.className = a.value; } else { pre.setAttribute(a.name, a.value); } } } pre.innerHTML = newContent; cs.parentNode.replaceChild(pre, cs); cs = pre; } if (isIE6 && cs.tagName === 'PRE') { var lineBreaks = cs.getElementsByTagName('br'); for (var j = lineBreaks.length; --j >= 0; ) { var lineBreak = lineBreaks[j]; lineBreak.parentNode.replaceChild(document.createTextNode('\r\n'), lineBreak); } } } } } if (k < elements.length) { setTimeout(doWork, 250); } else if (opt_whenDone) { opt_whenDone(); } } doWork(); } window['PR_normalizedHtml'] = normalizedHtml; window['prettyPrintOne'] = prettyPrintOne; window['prettyPrint'] = prettyPrint; window['PR'] = { 'createSimpleLexer': createSimpleLexer, 'registerLangHandler': registerLangHandler, 'sourceDecorator': sourceDecorator, 'PR_ATTRIB_NAME': PR_ATTRIB_NAME, 'PR_ATTRIB_VALUE': PR_ATTRIB_VALUE, 'PR_COMMENT': PR_COMMENT, 'PR_DECLARATION': PR_DECLARATION, 'PR_KEYWORD': PR_KEYWORD, 'PR_LITERAL': PR_LITERAL, 'PR_NOCODE': PR_NOCODE, 'PR_PLAIN': PR_PLAIN, 'PR_PUNCTUATION': PR_PUNCTUATION, 'PR_SOURCE': PR_SOURCE, 'PR_STRING': PR_STRING, 'PR_TAG': PR_TAG, 'PR_TYPE': PR_TYPE }; })();
diff --git a/askbot/skins/default/media/js/user.js b/askbot/skins/default/media/js/user.js
deleted file mode 100644
index 438a3273..00000000
--- a/askbot/skins/default/media/js/user.js
+++ /dev/null
@@ -1,185 +0,0 @@
-$(document).ready(function(){
-
- var getSelected = function(){
-
- var id_list = new Array();
- var elements = $('#responses input:checked').parent();
-
- elements.each(function(index, element){
- var id = $(element).attr('id').replace(/^re_/,'');
- id_list.push(id);
- });
-
- if (id_list.length === 0){
- alert($.i18n._('Please select at least one item'));
- }
-
- return {id_list: id_list, elements: elements};
- };
-
- var submit = function(id_list, elements, action_type){
- if (action_type == 'delete' || action_type == 'mark_new' || action_type == 'mark_seen'){
- $.ajax({
- type: 'POST',
- cache: false,
- dataType: 'json',
- data: JSON.stringify({memo_list: id_list, action_type: action_type}),
- url: askbot['urls']['manageInbox'],
- success: function(response_data){
- if (response_data['success'] === true){
- if (action_type == 'delete'){
- elements.remove();
- }
- else if (action_type == 'mark_new'){
- elements.addClass('highlight');
- elements.addClass('new');
- elements.removeClass('seen');
- }
- else if (action_type == 'mark_seen'){
- elements.removeClass('highlight');
- elements.addClass('seen');
- elements.removeClass('new');
- }
- }
- else {
- showMessage($('#responses'), response_data['message']);
- }
- }
- });
- }
- };
-
- var startAction = function(action_type){
- var data = getSelected();
- if (data['id_list'].length === 0){
- return;
- }
- if (action_type == 'delete'){
- if (data['id_list'].length === 1){
- var msg = $.i18n._('Delete this notification?')
- }
- else {
- var msg = $.i18n._('Delete these notifications?')
- }
- if (confirm(msg) === false){
- return;
- }
- }
- submit(data['id_list'], data['elements'], action_type);
- };
- setupButtonEventHandlers($('#re_mark_seen'), function(){startAction('mark_seen')});
- setupButtonEventHandlers($('#re_mark_new'), function(){startAction('mark_new')});
- setupButtonEventHandlers($('#re_dismiss'), function(){startAction('delete')});
- setupButtonEventHandlers(
- $('#sel_all'),
- function(){
- setCheckBoxesIn('#responses .new', true);
- setCheckBoxesIn('#responses .seen', true);
- }
- );
- setupButtonEventHandlers(
- $('#sel_seen'),
- function(){
- setCheckBoxesIn('#responses .seen', true);
- }
- );
- setupButtonEventHandlers(
- $('#sel_new'),
- function(){
- setCheckBoxesIn('#responses .new', true);
- }
- );
- setupButtonEventHandlers(
- $('#sel_none'),
- function(){
- setCheckBoxesIn('#responses .new', false);
- setCheckBoxesIn('#responses .seen', false);
- }
- );
-});
-
-/**
- * @constructor
- * allows to follow/unfollow users
- */
-var FollowUser = function(){
- WrappedElement.call(this);
- this._user_id = null;
- this._user_name = null;
-};
-inherits(FollowUser, WrappedElement);
-
-/**
- * @param {string} user_name
- */
-FollowUser.prototype.setUserName = function(user_name){
- this._user_name = user_name;
-};
-
-FollowUser.prototype.decorate = function(element){
- this._element = element;
- this._user_id = parseInt(element.attr('id').split('-').pop());
- this._available_action = element.children().hasClass('follow') ? 'follow':'unfollow';
- var me = this;
- setupButtonEventHandlers(this._element, function(){ me.go() });
-};
-
-FollowUser.prototype.go = function(){
- if (askbot['data']['userIsAuthenticated'] === false){
- var message = gettext('Please <a href="%(signin_url)s">signin</a> to follow %(username)s');
- var message_data = {
- signin_url: askbot['urls']['user_signin'] + '?next=' + window.location.href,
- username: this._user_name
- }
- message = interpolate(message, message_data, true);
- showMessage(this._element, message);
- return;
- }
- var user_id = this._user_id;
- if (this._available_action === 'follow'){
- var url = askbot['urls']['follow_user'];
- } else {
- var url = askbot['urls']['unfollow_user'];
- }
- var me = this;
- $.ajax({
- type: 'POST',
- cache: false,
- dataType: 'json',
- url: url.replace('{{userId}}', user_id),
- success: function(){ me.toggleState() }
- });
-};
-
-FollowUser.prototype.toggleState = function(){
- if (this._available_action === 'follow'){
- this._available_action = 'unfollow';
- var unfollow_div = document.createElement('div');
- unfollow_div.setAttribute('class', 'unfollow');
- var red_div = document.createElement('div');
- red_div.setAttribute('class', 'unfollow-red');
- red_div.innerHTML = interpolate(gettext('unfollow %s'), [this._user_name]);
- var green_div = document.createElement('div');
- green_div.setAttribute('class', 'unfollow-green');
- green_div.innerHTML = interpolate(gettext('following %s'), [this._user_name]);
- unfollow_div.appendChild(red_div);
- unfollow_div.appendChild(green_div);
- this._element.html(unfollow_div);
- } else {
- var follow_div = document.createElement('div');
- follow_div.innerHTML = interpolate(gettext('follow %s'), [this._user_name]);
- follow_div.setAttribute('class', 'follow');
- this._available_action = 'follow';
- this._element.html(follow_div);
- }
-};
-
-(function(){
- var fbtn = $('.follow-toggle');
- if (fbtn.length === 1){
- var follow_user = new FollowUser();
- follow_user.decorate(fbtn);
- follow_user.setUserName(askbot['data']['viewUserName']);
- }
-})();
-
diff --git a/askbot/skins/default/media/js/utils.js b/askbot/skins/default/media/js/utils.js
deleted file mode 100644
index 2b2579ab..00000000
--- a/askbot/skins/default/media/js/utils.js
+++ /dev/null
@@ -1,405 +0,0 @@
-//var $, scriptUrl, askbotSkin
-var mediaUrl = function(resource){
- return scriptUrl + 'm/' + askbotSkin + '/' + resource;
-};
-
-var cleanUrl = function(url){
- var re = new RegExp('//', 'g');
- return url.replace(re, '/');
-};
-
-var copyAltToTitle = function(sel){
- sel.attr('title', sel.attr('alt'));
-};
-
-var animateHashes = function(){
- var id_value = window.location.hash;
- if (id_value != ""){
- var previous_color = $(id_value).css('background-color');
- $(id_value).css('backgroundColor', '#FFF8C6');
- $(id_value)
- .animate({backgroundColor: '#ff7f2a'}, 500)
- .animate({backgroundColor: '#FFF8C6'}, 500, function(){
- $(id_value).css('backgroundColor', previous_color);
- });
- }
-};
-
-var getUniqueWords = function(value){
- var words = $.trim(value).split(/\s+/);
- var uniques = new Object();
- var out = new Array();
- $.each(words, function(idx, item){
- if (!(item in uniques)){
- uniques[item] = 1;
- out.push(item);
- };
- });
- return out;
-};
-
-var showMessage = function(element, msg, where) {
- var div = $('<div class="vote-notification"><h3>' + msg + '</h3>(' +
- $.i18n._('click to close') + ')</div>');
-
- div.click(function(event) {
- $(".vote-notification").fadeOut("fast", function() { $(this).remove(); });
- });
-
- var where = where || 'parent';
-
- if (where == 'parent'){
- element.parent().append(div);
- }
- else {
- element.after(div);
- }
-
- div.fadeIn("fast");
-};
-
-//outer html hack - https://github.com/brandonaaron/jquery-outerhtml/
-(function($){
- var div;
- $.fn.outerHTML = function() {
- var elem = this[0],
- tmp;
- return !elem ? null
- : typeof ( tmp = elem.outerHTML ) === 'string' ? tmp
- : ( div = div || $('<div/>') ).html( this.eq(0).clone() ).html();
- };
-})(jQuery);
-
-var makeKeyHandler = function(key, callback){
- return function(e){
- if ((e.which && e.which == key) || (e.keyCode && e.keyCode == key)){
- if(!e.shiftKey){
- callback();
- return false;
- }
- }
- };
-};
-
-
-var setupButtonEventHandlers = function(button, callback){
- button.keydown(makeKeyHandler(13, callback));
- button.click(callback);
-};
-
-
-var putCursorAtEnd = function(element){
- var el = element.get()[0];
- if (el.setSelectionRange){
- var len = element.val().length * 2;
- el.setSelectionRange(len, len);
- }
- else{
- element.val(element.val());
- }
- element.scrollTop = 999999;
-};
-
-var setCheckBoxesIn = function(selector, value){
- return $(selector + '> input[type=checkbox]').attr('checked', value);
-};
-
-var notify = function() {
- var visible = false;
- return {
- show: function(html) {
- if (html) {
- $("body").css("margin-top", "2.2em");
- $(".notify span").html(html);
- }
- $(".notify").fadeIn("slow");
- visible = true;
- },
- close: function(doPostback) {
- if (doPostback) {
- $.post(
- askbot['urls']['mark_read_message'],
- { formdata: "required" }
- );
- }
- $(".notify").fadeOut("fast");
- $("body").css("margin-top", "0");
- visible = false;
- },
- isVisible: function() { return visible; }
- };
-} ();
-
-/* some google closure-like code for the ui elements */
-var inherits = function(childCtor, parentCtor) {
- /** @constructor taken from google closure */
- function tempCtor() {};
- tempCtor.prototype = parentCtor.prototype;
- childCtor.superClass_ = parentCtor.prototype;
- childCtor.prototype = new tempCtor();
- childCtor.prototype.constructor = childCtor;
-};
-
-/* wrapper around jQuery object */
-var WrappedElement = function(){
- this._element = null;
- this._in_document = false;
-};
-WrappedElement.prototype.setElement = function(element){
- this._element = element;
-};
-WrappedElement.prototype.createDom = function(){
- this._element = $('<div></div>');
-};
-WrappedElement.prototype.getElement = function(){
- if (this._element === null){
- this.createDom();
- }
- return this._element;
-};
-WrappedElement.prototype.inDocument = function(){
- return this._in_document;
-};
-WrappedElement.prototype.enterDocument = function(){
- return this._in_document = true;
-};
-WrappedElement.prototype.hasElement = function(){
- return (this._element !== null);
-};
-WrappedElement.prototype.makeElement = function(html_tag){
- //makes jQuery element with tags
- return $('<' + html_tag + '></' + html_tag + '>');
-};
-WrappedElement.prototype.dispose = function(){
- this._element.remove();
- this._in_document = false;
-};
-
-var SimpleControl = function(){
- WrappedElement.call(this);
- this._handler = null;
- this._title = null;
-};
-inherits(SimpleControl, WrappedElement);
-
-SimpleControl.prototype.setHandler = function(handler){
- this._handler = handler;
- if (this.hasElement()){
- this.setHandlerInternal();
- }
-};
-
-SimpleControl.prototype.setHandlerInternal = function(){
- //default internal setHandler behavior
- setupButtonEventHandlers(this._element, this._handler);
-};
-
-SimpleControl.prototype.setTitle = function(title){
- this._title = title;
-};
-
-var EditLink = function(){
- SimpleControl.call(this)
-};
-inherits(EditLink, SimpleControl);
-
-EditLink.prototype.createDom = function(){
- var element = $('<a></a>');
- element.addClass('edit');
- this.decorate(element);
-};
-
-EditLink.prototype.decorate = function(element){
- this._element = element;
- this._element.attr('title', $.i18n._('click to edit this comment'));
- this._element.html($.i18n._('edit'));
- this.setHandlerInternal();
-};
-
-var DeleteIcon = function(title){
- SimpleControl.call(this);
- this._title = title;
-};
-inherits(DeleteIcon, SimpleControl);
-
-DeleteIcon.prototype.decorate = function(element){
- this._element = element;
- this._element.attr('class', 'delete-icon');
- this._element.attr('title', this._title);
- if (this._handler !== null){
- this.setHandlerInternal();
- }
-};
-
-DeleteIcon.prototype.setHandlerInternal = function(){
- setupButtonEventHandlers(this._element, this._handler);
-};
-
-DeleteIcon.prototype.createDom = function(){
- this._element = this.makeElement('span');
- this.decorate(this._element);
-};
-
-var Tag = function(){
- SimpleControl.call(this);
- this._deletable = false;
- this._delete_handler = null;
- this._delete_icon_title = null;
- this._tag_title = null;
- this._name = null;
- this._url_params = null;
- this._inner_html_tag = 'a';
- this._html_tag = 'li';
-}
-inherits(Tag, SimpleControl);
-
-Tag.prototype.setName = function(name){
- this._name = name;
-};
-
-Tag.prototype.getName = function(){
- return this._name;
-};
-
-Tag.prototype.setHtmlTag = function(html_tag){
- this._html_tag = html_tag;
-};
-
-Tag.prototype.setDeletable = function(is_deletable){
- this._deletable = is_deletable;
-};
-
-Tag.prototype.setLinkable = function(is_linkable){
- if (is_linkable === true){
- this._inner_html_tag = 'a';
- } else {
- this._inner_html_tag = 'span';
- }
-};
-
-Tag.prototype.isLinkable = function(){
- return (this._inner_html_tag === 'a');
-};
-
-Tag.prototype.isDeletable = function(){
- return this._deletable;
-};
-
-Tag.prototype.isWildcard = function(){
- return (this.getName().substr(-1) === '*');
-};
-
-Tag.prototype.setUrlParams = function(url_params){
- this._url_params = url_params;
-};
-
-Tag.prototype.setHandlerInternal = function(){
- setupButtonEventHandlers(this._element.find('.tag'), this._handler);
-};
-
-/* delete handler will be specific to the task */
-Tag.prototype.setDeleteHandler = function(delete_handler){
- this._delete_handler = delete_handler;
- if (this.hasElement() && this.isDeletable()){
- this._delete_icon.setHandler(delete_handler);
- }
-};
-
-Tag.prototype.getDeleteHandler = function(){
- return this._delete_handler;
-};
-
-Tag.prototype.setDeleteIconTitle = function(title){
- this._delete_icon_title = title;
-};
-
-Tag.prototype.decorate = function(element){
- this._element = element;
- var del = element.find('.delete-icon');
- if (del.length === 1){
- this.setDeletable(true);
- this._delete_icon = new DeleteIcon();
- if (this._delete_icon_title != null){
- this._delete_icon.setTitle(this._delete_icon_title);
- }
- //do not set the delete handler here
- this._delete_icon.decorate(del);
- }
- this._inner_element = this._element.find('.tag');
- this._name = this.decodeTagName($.trim(this._inner_element.html()));
- if (this._title !== null){
- this._inner_element.attr('title', this._title);
- }
- if (this._handler !== null){
- this.setHandlerInternal();
- }
-};
-
-Tag.prototype.getDisplayTagName = function(){
- //replaces the trailing * symbol with the unicode asterisk
- return this._name.replace(/\*$/, '&#10045;');
-};
-
-Tag.prototype.decodeTagName = function(encoded_name){
- return encoded_name.replace('\u273d', '*');
-};
-
-Tag.prototype.createDom = function(){
- this._element = this.makeElement(this._html_tag);
- //render the outer element
- if (this._deletable){
- this._element.addClass('deletable-tag');
- }
- this._element.addClass('tag-left');
-
- //render the inner element
- this._inner_element = this.makeElement(this._inner_html_tag);
- if (this.isLinkable()){
- var url = askbot['urls']['questions'];
- url += '?tags=' + escape(this.getName());
- if (this._url_params !== null){
- url += escape('&' + this._url_params);
- }
- this._inner_element.attr('href', url);
- }
- this._inner_element.addClass('tag tag-right');
- this._inner_element.attr('rel', 'tag');
- if (this._title === null){
- this.setTitle(
- $.i18n._(
- "see questions tagged '{tag}'"
- ).replace(
- '{tag}',
- this.getName()
- )
- );
- }
- this._inner_element.attr('title', this._title);
- this._inner_element.html(this.getDisplayTagName());
-
- this._element.append(this._inner_element);
-
- if (!this.isLinkable() && this._handler !== null){
- this.setHandlerInternal();
- }
-
- if (this._deletable){
- this._delete_icon = new DeleteIcon();
- this._delete_icon.setHandler(this.getDeleteHandler());
- if (this._delete_icon_title !== null){
- this._delete_icon.setTitle(this._delete_icon_title);
- }
- this._element.append(this._delete_icon.getElement());
- }
-};
-
-//Search Engine Keyword Highlight with Javascript
-//http://scott.yang.id.au/code/se-hilite/
-Hilite={elementid:"content",exact:true,max_nodes:1000,onload:true,style_name:"hilite",style_name_suffix:true,debug_referrer:""};Hilite.search_engines=[["local","q"],["cnprog\\.","q"],["google\\.","q"],["search\\.yahoo\\.","p"],["search\\.msn\\.","q"],["search\\.live\\.","query"],["search\\.aol\\.","userQuery"],["ask\\.com","q"],["altavista\\.","q"],["feedster\\.","q"],["search\\.lycos\\.","q"],["alltheweb\\.","q"],["technorati\\.com/search/([^\\?/]+)",1],["dogpile\\.com/info\\.dogpl/search/web/([^\\?/]+)",1,true]];Hilite.decodeReferrer=function(d){var g=null;var e=new RegExp("");for(var c=0;c<Hilite.search_engines.length;c++){var f=Hilite.search_engines[c];e.compile("^http://(www\\.)?"+f[0],"i");var b=d.match(e);if(b){var a;if(isNaN(f[1])){a=Hilite.decodeReferrerQS(d,f[1])}else{a=b[f[1]+1]}if(a){a=decodeURIComponent(a);if(f.length>2&&f[2]){a=decodeURIComponent(a)}a=a.replace(/\'|"/g,"");a=a.split(/[\s,\+\.]+/);return a}break}}return null};Hilite.decodeReferrerQS=function(f,d){var b=f.indexOf("?");var c;if(b>=0){var a=new String(f.substring(b+1));b=0;c=0;while((b>=0)&&((c=a.indexOf("=",b))>=0)){var e,g;e=a.substring(b,c);b=a.indexOf("&",c)+1;if(e==d){if(b<=0){return a.substring(c+1)}else{return a.substring(c+1,b-1)}}else{if(b<=0){return null}}}}return null};Hilite.hiliteElement=function(f,e){if(!e||f.childNodes.length==0){return}var c=new Array();for(var b=0;b<e.length;b++){e[b]=e[b].toLowerCase();if(Hilite.exact){c.push("\\b"+e[b]+"\\b")}else{c.push(e[b])}}c=new RegExp(c.join("|"),"i");var a={};for(var b=0;b<e.length;b++){if(Hilite.style_name_suffix){a[e[b]]=Hilite.style_name+(b+1)}else{a[e[b]]=Hilite.style_name}}var d=function(m){var j=c.exec(m.data);if(j){var n=j[0];var i="";var h=m.splitText(j.index);var g=h.splitText(n.length);var l=m.ownerDocument.createElement("SPAN");m.parentNode.replaceChild(l,h);l.className=a[n.toLowerCase()];l.appendChild(h);return l}else{return m}};Hilite.walkElements(f.childNodes[0],1,d)};Hilite.hilite=function(){var a=Hilite.debug_referrer?Hilite.debug_referrer:document.referrer;var b=null;a=Hilite.decodeReferrer(a);if(a&&((Hilite.elementid&&(b=document.getElementById(Hilite.elementid)))||(b=document.body))){Hilite.hiliteElement(b,a)}};Hilite.walkElements=function(d,f,e){var a=/^(script|style|textarea)/i;var c=0;while(d&&f>0){c++;if(c>=Hilite.max_nodes){var b=function(){Hilite.walkElements(d,f,e)};setTimeout(b,50);return}if(d.nodeType==1){if(!a.test(d.tagName)&&d.childNodes.length>0){d=d.childNodes[0];f++;continue}}else{if(d.nodeType==3){d=e(d)}}if(d.nextSibling){d=d.nextSibling}else{while(f>0){d=d.parentNode;f--;if(d.nextSibling){d=d.nextSibling;break}}}}};if(Hilite.onload){if(window.attachEvent){window.attachEvent("onload",Hilite.hilite)}else{if(window.addEventListener){window.addEventListener("load",Hilite.hilite,false)}else{var __onload=window.onload;window.onload=function(){Hilite.hilite();__onload()}}}};
-/* json2.js by D. Crockford */
-if(!this.JSON){this.JSON={}}(function(){function f(n){return n<10?"0"+n:n}if(typeof Date.prototype.toJSON!=="function"){Date.prototype.toJSON=function(key){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf()}}var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==="string"?c:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+string+'"'}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==="object"&&typeof value.toJSON==="function"){value=value.toJSON(key)}if(typeof rep==="function"){value=rep.call(holder,key,value)}switch(typeof value){case"string":return quote(value);case"number":return isFinite(value)?String(value):"null";case"boolean":case"null":return String(value);case"object":if(!value){return"null"}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==="[object Array]"){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||"null"}v=partial.length===0?"[]":gap?"[\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"]":"["+partial.join(",")+"]";gap=mind;return v}if(rep&&typeof rep==="object"){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==="string"){v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}else{for(k in value){if(Object.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}v=partial.length===0?"{}":gap?"{\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"}":"{"+partial.join(",")+"}";gap=mind;return v}}if(typeof JSON.stringify!=="function"){JSON.stringify=function(value,replacer,space){var i;gap="";indent="";if(typeof space==="number"){for(i=0;i<space;i+=1){indent+=" "}}else{if(typeof space==="string"){indent=space}}rep=replacer;if(replacer&&typeof replacer!=="function"&&(typeof replacer!=="object"||typeof replacer.length!=="number")){throw new Error("JSON.stringify")}return str("",{"":value})}}if(typeof JSON.parse!=="function"){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==="object"){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v}else{delete value[k]}}}}return reviver.call(holder,key,value)}text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){j=eval("("+text+")");return typeof reviver==="function"?walk({"":j},""):j}throw new SyntaxError("JSON.parse")}}}());
-//jquery fieldselection
-(function(){var a={getSelection:function(){var b=this.jquery?this[0]:this;return(("selectionStart" in b&&function(){var c=b.selectionEnd-b.selectionStart;return{start:b.selectionStart,end:b.selectionEnd,length:c,text:b.value.substr(b.selectionStart,c)}})||(document.selection&&function(){b.focus();var d=document.selection.createRange();if(d==null){return{start:0,end:b.value.length,length:0}}var c=b.createTextRange();var e=c.duplicate();c.moveToBookmark(d.getBookmark());e.setEndPoint("EndToStart",c);return{start:e.text.length,end:e.text.length+d.text.length,length:d.text.length,text:d.text}})||function(){return{start:0,end:b.value.length,length:0}})()},replaceSelection:function(){var b=this.jquery?this[0]:this;var c=arguments[0]||"";return(("selectionStart" in b&&function(){b.value=b.value.substr(0,b.selectionStart)+c+b.value.substr(b.selectionEnd,b.value.length);return this})||(document.selection&&function(){b.focus();document.selection.createRange().text=c;return this})||function(){b.value+=c;return this})()}};jQuery.each(a,function(b){jQuery.fn[b]=this})})();
-//our custom autocompleter
-var AutoCompleter=function(a){var b={autocompleteMultiple:true,multipleSeparator:" ",inputClass:"acInput",loadingClass:"acLoading",resultsClass:"acResults",selectClass:"acSelect",queryParamName:"q",limitParamName:"limit",extraParams:{},lineSeparator:"\n",cellSeparator:"|",minChars:2,maxItemsToShow:10,delay:400,useCache:true,maxCacheLength:10,matchSubset:true,matchCase:false,matchInside:true,mustMatch:false,preloadData:false,selectFirst:false,stopCharRegex:/\s+/,selectOnly:false,formatItem:null,onItemSelect:false,autoFill:false,filterResults:true,sortResults:true,sortFunction:false,onNoMatch:false};this.options=$.extend({},b,a);this.cacheData_={};this.cacheLength_=0;this.selectClass_="jquery-autocomplete-selected-item";this.keyTimeout_=null;this.lastKeyPressed_=null;this.lastProcessedValue_=null;this.lastSelectedValue_=null;this.active_=false;this.finishOnBlur_=true;this.options.minChars=parseInt(this.options.minChars,10);if(isNaN(this.options.minChars)||this.options.minChars<1){this.options.minChars=2}this.options.maxItemsToShow=parseInt(this.options.maxItemsToShow,10);if(isNaN(this.options.maxItemsToShow)||this.options.maxItemsToShow<1){this.options.maxItemsToShow=10}this.options.maxCacheLength=parseInt(this.options.maxCacheLength,10);if(isNaN(this.options.maxCacheLength)||this.options.maxCacheLength<1){this.options.maxCacheLength=10}if(this.options.preloadData===true){this.fetchRemoteData("",function(){})}};inherits(AutoCompleter,WrappedElement);AutoCompleter.prototype.decorate=function(a){this._element=a;this._element.attr("autocomplete","off");this._results=$("<div></div>").hide();if(this.options.resultsClass){this._results.addClass(this.options.resultsClass)}this._results.css({position:"absolute"});$("body").append(this._results);this.setEventHandlers()};AutoCompleter.prototype.setEventHandlers=function(){var a=this;a._element.keydown(function(b){a.lastKeyPressed_=b.keyCode;switch(a.lastKeyPressed_){case 38:b.preventDefault();if(a.active_){a.focusPrev()}else{a.activate()}return false;break;case 40:b.preventDefault();if(a.active_){a.focusNext()}else{a.activate()}return false;break;case 9:case 13:if(a.active_){b.preventDefault();a.selectCurrent();return false}break;case 27:if(a.active_){b.preventDefault();a.finish();return false}break;default:a.activate()}});a._element.blur(function(){if(a.finishOnBlur_){setTimeout(function(){a.finish()},200)}})};AutoCompleter.prototype.position=function(){var a=this._element.offset();this._results.css({top:a.top+this._element.outerHeight(),left:a.left})};AutoCompleter.prototype.cacheRead=function(d){var f,c,b,a,e;if(this.options.useCache){d=String(d);f=d.length;if(this.options.matchSubset){c=1}else{c=f}while(c<=f){if(this.options.matchInside){a=f-c}else{a=0}e=0;while(e<=a){b=d.substr(0,c);if(this.cacheData_[b]!==undefined){return this.cacheData_[b]}e++}c++}}return false};AutoCompleter.prototype.cacheWrite=function(a,b){if(this.options.useCache){if(this.cacheLength_>=this.options.maxCacheLength){this.cacheFlush()}a=String(a);if(this.cacheData_[a]!==undefined){this.cacheLength_++}return this.cacheData_[a]=b}return false};AutoCompleter.prototype.cacheFlush=function(){this.cacheData_={};this.cacheLength_=0};AutoCompleter.prototype.callHook=function(c,b){var a=this.options[c];if(a&&$.isFunction(a)){return a(b,this)}return false};AutoCompleter.prototype.activate=function(){var b=this;var a=function(){b.activateNow()};var c=parseInt(this.options.delay,10);if(isNaN(c)||c<=0){c=250}if(this.keyTimeout_){clearTimeout(this.keyTimeout_)}this.keyTimeout_=setTimeout(a,c)};AutoCompleter.prototype.activateNow=function(){var a=this.getValue();if(a!==this.lastProcessedValue_&&a!==this.lastSelectedValue_){if(a.length>=this.options.minChars){this.active_=true;this.lastProcessedValue_=a;this.fetchData(a)}}};AutoCompleter.prototype.fetchData=function(b){if(this.options.data){this.filterAndShowResults(this.options.data,b)}else{var a=this;this.fetchRemoteData(b,function(c){a.filterAndShowResults(c,b)})}};AutoCompleter.prototype.fetchRemoteData=function(c,e){var d=this.cacheRead(c);if(d){e(d)}else{var a=this;if(this._element){this._element.addClass(this.options.loadingClass)}var b=function(g){var f=false;if(g!==false){f=a.parseRemoteData(g);a.options.data=f;a.cacheWrite(c,f)}if(a._element){a._element.removeClass(a.options.loadingClass)}e(f)};$.ajax({url:this.makeUrl(c),success:b,error:function(){b(false)}})}};AutoCompleter.prototype.setOption=function(a,b){this.options[a]=b};AutoCompleter.prototype.setExtraParam=function(b,c){var a=$.trim(String(b));if(a){if(!this.options.extraParams){this.options.extraParams={}}if(this.options.extraParams[a]!==c){this.options.extraParams[a]=c;this.cacheFlush()}}};AutoCompleter.prototype.makeUrl=function(e){var a=this;var b=this.options.url;var d=$.extend({},this.options.extraParams);if(this.options.queryParamName===false){b+=encodeURIComponent(e)}else{d[this.options.queryParamName]=e}if(this.options.limitParamName&&this.options.maxItemsToShow){d[this.options.limitParamName]=this.options.maxItemsToShow}var c=[];$.each(d,function(f,g){c.push(a.makeUrlParam(f,g))});if(c.length){b+=b.indexOf("?")==-1?"?":"&";b+=c.join("&")}return b};AutoCompleter.prototype.makeUrlParam=function(a,b){return String(a)+"="+encodeURIComponent(b)};AutoCompleter.prototype.splitText=function(a){return String(a).replace(/(\r\n|\r|\n)/g,"\n").split(this.options.lineSeparator)};AutoCompleter.prototype.parseRemoteData=function(c){var h,b,f,d,g;var e=[];var b=this.splitText(c);for(f=0;f<b.length;f++){var a=b[f].split(this.options.cellSeparator);g=[];for(d=0;d<a.length;d++){g.push(unescape(a[d]))}h=g.shift();e.push({value:unescape(h),data:g})}return e};AutoCompleter.prototype.filterAndShowResults=function(a,b){this.showResults(this.filterResults(a,b),b)};AutoCompleter.prototype.filterResults=function(d,b){var f=[];var l,c,e,m,j,a;var k,h,g;for(e=0;e<d.length;e++){m=d[e];j=typeof m;if(j==="string"){l=m;c={}}else{if($.isArray(m)){l=m[0];c=m.slice(1)}else{if(j==="object"){l=m.value;c=m.data}}}l=String(l);if(l>""){if(typeof c!=="object"){c={}}if(this.options.filterResults){h=String(b);g=String(l);if(!this.options.matchCase){h=h.toLowerCase();g=g.toLowerCase()}a=g.indexOf(h);if(this.options.matchInside){a=a>-1}else{a=a===0}}else{a=true}if(a){f.push({value:l,data:c})}}}if(this.options.sortResults){f=this.sortResults(f,b)}if(this.options.maxItemsToShow>0&&this.options.maxItemsToShow<f.length){f.length=this.options.maxItemsToShow}return f};AutoCompleter.prototype.sortResults=function(c,d){var b=this;var a=this.options.sortFunction;if(!$.isFunction(a)){a=function(g,e,h){return b.sortValueAlpha(g,e,h)}}c.sort(function(f,e){return a(f,e,d)});return c};AutoCompleter.prototype.sortValueAlpha=function(d,c,e){d=String(d.value);c=String(c.value);if(!this.options.matchCase){d=d.toLowerCase();c=c.toLowerCase()}if(d>c){return 1}if(d<c){return -1}return 0};AutoCompleter.prototype.showResults=function(e,b){var k=this;var g=$("<ul></ul>");var f,l,j,a,h=false,d=false;var c=e.length;for(f=0;f<c;f++){l=e[f];j=$("<li>"+this.showResult(l.value,l.data)+"</li>");j.data("value",l.value);j.data("data",l.data);j.click(function(){var i=$(this);k.selectItem(i)}).mousedown(function(){k.finishOnBlur_=false}).mouseup(function(){k.finishOnBlur_=true});g.append(j);if(h===false){h=String(l.value);d=j;j.addClass(this.options.firstItemClass)}if(f==c-1){j.addClass(this.options.lastItemClass)}}this.position();this._results.html(g).show();a=this._results.outerWidth()-this._results.width();this._results.width(this._element.outerWidth()-a);$("li",this._results).hover(function(){k.focusItem(this)},function(){});if(this.autoFill(h,b)){this.focusItem(d)}};AutoCompleter.prototype.showResult=function(b,a){if($.isFunction(this.options.showResult)){return this.options.showResult(b,a)}else{return b}};AutoCompleter.prototype.autoFill=function(e,c){var b,a,d,f;if(this.options.autoFill&&this.lastKeyPressed_!=8){b=String(e).toLowerCase();a=String(c).toLowerCase();d=e.length;f=c.length;if(b.substr(0,f)===a){this._element.val(e);this.selectRange(f,d);return true}}return false};AutoCompleter.prototype.focusNext=function(){this.focusMove(+1)};AutoCompleter.prototype.focusPrev=function(){this.focusMove(-1)};AutoCompleter.prototype.focusMove=function(a){var b,c=$("li",this._results);a=parseInt(a,10);for(var b=0;b<c.length;b++){if($(c[b]).hasClass(this.selectClass_)){this.focusItem(b+a);return}}this.focusItem(0)};AutoCompleter.prototype.focusItem=function(b){var a,c=$("li",this._results);if(c.length){c.removeClass(this.selectClass_).removeClass(this.options.selectClass);if(typeof b==="number"){b=parseInt(b,10);if(b<0){b=0}else{if(b>=c.length){b=c.length-1}}a=$(c[b])}else{a=$(b)}if(a){a.addClass(this.selectClass_).addClass(this.options.selectClass)}}};AutoCompleter.prototype.selectCurrent=function(){var a=$("li."+this.selectClass_,this._results);if(a.length==1){this.selectItem(a)}else{this.finish()}};AutoCompleter.prototype.selectItem=function(d){var c=d.data("value");var b=d.data("data");var a=this.displayValue(c,b);this.lastProcessedValue_=a;this.lastSelectedValue_=a;this.setValue(a);this.setCaret(a.length);this.callHook("onItemSelect",{value:c,data:b});this.finish()};AutoCompleter.prototype.isContentChar=function(a){if(a.match(this.options.stopCharRegex)){return false}else{if(a===this.options.multipleSeparator){return false}else{return true}}};AutoCompleter.prototype.getValue=function(){var c=this._element.getSelection();var d=this._element.val();var f=c.start;var e=f;for(cpos=f;cpos>=0;cpos=cpos-1){if(cpos===d.length){continue}var b=d.charAt(cpos);if(!this.isContentChar(b)){break}e=cpos}var a=f;for(cpos=f;cpos<d.length;cpos=cpos+1){if(cpos===0){continue}var b=d.charAt(cpos);if(!this.isContentChar(b)){break}a=cpos}this._selection_start=e;this._selection_end=a;return d.substring(e,a)};AutoCompleter.prototype.setValue=function(b){var a=this._element.val().substring(0,this._selection_start);var c=this._element.val().substring(this._selection_end+1);this._element.val(a+b+c)};AutoCompleter.prototype.displayValue=function(b,a){if($.isFunction(this.options.displayValue)){return this.options.displayValue(b,a)}else{return b}};AutoCompleter.prototype.finish=function(){if(this.keyTimeout_){clearTimeout(this.keyTimeout_)}if(this._element.val()!==this.lastSelectedValue_){if(this.options.mustMatch){this._element.val("")}this.callHook("onNoMatch")}this._results.hide();this.lastKeyPressed_=null;this.lastProcessedValue_=null;if(this.active_){this.callHook("onFinish")}this.active_=false};AutoCompleter.prototype.selectRange=function(d,a){var c=this._element.get(0);if(c.setSelectionRange){c.focus();c.setSelectionRange(d,a)}else{if(this.createTextRange){var b=this.createTextRange();b.collapse(true);b.moveEnd("character",a);b.moveStart("character",d);b.select()}}};AutoCompleter.prototype.setCaret=function(a){this.selectRange(a,a)};
-(function($){function isRGBACapable(){var $script=$("script:first"),color=$script.css("color"),result=false;if(/^rgba/.test(color)){result=true}else{try{result=(color!=$script.css("color","rgba(0, 0, 0, 0.5)").css("color"));$script.css("color",color)}catch(e){}}return result}$.extend(true,$,{support:{rgba:isRGBACapable()}});var properties=["color","backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","outlineColor"];$.each(properties,function(i,property){$.fx.step[property]=function(fx){if(!fx.init){fx.begin=parseColor($(fx.elem).css(property));fx.end=parseColor(fx.end);fx.init=true}fx.elem.style[property]=calculateColor(fx.begin,fx.end,fx.pos)}});$.fx.step.borderColor=function(fx){if(!fx.init){fx.end=parseColor(fx.end)}var borders=properties.slice(2,6);$.each(borders,function(i,property){if(!fx.init){fx[property]={begin:parseColor($(fx.elem).css(property))}}fx.elem.style[property]=calculateColor(fx[property].begin,fx.end,fx.pos)});fx.init=true};function calculateColor(begin,end,pos){var color="rgb"+($.support.rgba?"a":"")+"("+parseInt((begin[0]+pos*(end[0]-begin[0])),10)+","+parseInt((begin[1]+pos*(end[1]-begin[1])),10)+","+parseInt((begin[2]+pos*(end[2]-begin[2])),10);if($.support.rgba){color+=","+(begin&&end?parseFloat(begin[3]+pos*(end[3]-begin[3])):1)}color+=")";return color}function parseColor(color){var match,triplet;if(match=/#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})/.exec(color)){triplet=[parseInt(match[1],16),parseInt(match[2],16),parseInt(match[3],16),1]}else{if(match=/#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])/.exec(color)){triplet=[parseInt(match[1],16)*17,parseInt(match[2],16)*17,parseInt(match[3],16)*17,1]}else{if(match=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color)){triplet=[parseInt(match[1]),parseInt(match[2]),parseInt(match[3]),1]}else{if(match=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9\.]*)\s*\)/.exec(color)){triplet=[parseInt(match[1],10),parseInt(match[2],10),parseInt(match[3],10),parseFloat(match[4])]}else{if(color=="transparent"){triplet=[0,0,0,0]}}}}}return triplet}})(jQuery);
diff --git a/askbot/skins/default/templates/macros/macros.html b/askbot/skins/default/templates/macros/macros.html
index 7cae28b3..15b6bf67 100644
--- a/askbot/skins/default/templates/macros/macros.html
+++ b/askbot/skins/default/templates/macros/macros.html
@@ -105,6 +105,25 @@ poor design of the data or methods on data objects #}
{% endif %}
{%- endmacro -%}
+{%- macro post_last_updater_and_creator_info(post, min_rep_to_edit_wiki) -%}
+ {{
+ post_contributor_info(
+ post,
+ "original_author",
+ post.wiki,
+ min_rep_to_edit_wiki
+ )
+ }}
+ {{
+ post_contributor_info(
+ post,
+ "last_updater",
+ post.wiki,
+ min_rep_to_edit_wiki,
+ )
+ }}
+{%- endmacro -%}
+
{%- macro if_else(condition, if_true, if_false) -%}
{%- if condition == True -%}
{{if_true}}
@@ -519,3 +538,7 @@ for the purposes of the AJAX comment editor #}
});
tagAc.decorate($("{{ id }}"));
{%- endmacro -%}
+
+{%- macro answer_classes(answer, question) -%}
+answer {% if answer.accepted %}accepted-answer{% endif %} {% if answer.author_id==question.author_id %} answered-by-owner{% endif %} {% if answer.deleted %}deleted{% endif -%}
+{%- endmacro -%}
diff --git a/askbot/skins/default/templates/question.html b/askbot/skins/default/templates/question.html
index c5434525..7dc85d84 100644
--- a/askbot/skins/default/templates/question.html
+++ b/askbot/skins/default/templates/question.html
@@ -10,13 +10,12 @@
<link rel="stylesheet" type="text/css" href="{{'/js/wmd/wmd.css'|media}}" />
{% endblock %}
{% block content %}
-{%include "question/content.html" %}
+ {%include "question/content.html" %}
{% endblock %}
-
{% block sidebar %}
-{%include "question/sidebar.html" %}
+ {%include "question/sidebar.html" %}
{% endblock %}
{% block endjs %}
-{%include "question/javascript.html" %}
+ {%include "question/javascript.html" %}
{% endblock %}
diff --git a/askbot/skins/default/templates/question/answer_author_info.html b/askbot/skins/default/templates/question/answer_author_info.html
new file mode 100644
index 00000000..f17cb62c
--- /dev/null
+++ b/askbot/skins/default/templates/question/answer_author_info.html
@@ -0,0 +1,6 @@
+{{
+ macros.post_last_updater_and_creator_info(
+ answer,
+ settings.MIN_REP_TO_EDIT_WIKI
+ )
+}}
diff --git a/askbot/skins/default/templates/question/answer_card.html b/askbot/skins/default/templates/question/answer_card.html
index b3790b33..750c9157 100644
--- a/askbot/skins/default/templates/question/answer_card.html
+++ b/askbot/skins/default/templates/question/answer_card.html
@@ -1,49 +1,12 @@
<a name="{{ answer.id }}"></a>
-<div id="answer-container-{{ answer.id }}" class="answer {% if answer.accepted %}accepted-answer{% endif %} {% if answer.author_id==question.author_id %} answered-by-owner{% endif %} {% if answer.deleted %}deleted{% endif %}">
+<div
+ id="answer-container-{{ answer.id }}"
+ class="{{ macros.answer_classes(answer, question) }}">
<table class="answer-table">
<tr>
<td>
<div class="vote-buttons">
- <img id="answer-img-upvote-{{ answer.id }}" class="answer-img-upvote"
- {% if user_answer_votes[answer.id] == 1 %}
- src="{{'/images/vote-arrow-up-on.png'|media}}"
- {% else %}
- src="{{'/images/vote-arrow-up.png'|media}}"
- {% endif %}
- alt="{% trans %}i like this answer (click again to cancel){% endtrans %}"
- title="{% trans %}i like this answer (click again to cancel){% endtrans %}"/>
- <div id="answer-vote-number-{{ answer.id }}" class="vote-number" title="{% trans %}current number of votes{% endtrans %}">
- {{ answer.score }}
- </div>
- <img id="answer-img-downvote-{{ answer.id }}" class="answer-img-downvote"
- {% if user_answer_votes[answer.id] == -1 %}
- src="{{'/images/vote-arrow-down-on.png'|media}}"
- {% else %}
- src="{{'/images/vote-arrow-down.png'|media}}"
- {% endif %}
- alt="{% trans %}i dont like this answer (click again to cancel){% endtrans %}"
- title="{% trans %}i dont like this answer (click again to cancel){% endtrans %}" />
- {% if request.user == question.author %}
- <img id="answer-img-accept-{{ answer.id }}" class="answer-img-accept"
- {% if answer.accepted %}
- src="{{'/images/vote-accepted-on.png'|media}}"
- {% else %}
- src="{{'/images/vote-accepted.png'|media}}"
- {% endif %}
- alt="{% trans %}mark this answer as favorite (click again to undo){% endtrans %}"
- title="{% trans %}mark this answer as favorite (click again to undo){% endtrans %}" />
- {% else %}
- {% if answer.accepted %}
- <img id="answer-img-accept-{{ answer.id }}" class="answer-img-accept"
- {% if answer.accepted %}
- src="{{'/images/vote-accepted-on.png'|media}}"
- {% else %}
- src="{{'/images/vote-accepted.png'|media}}"
- {% endif %}
- alt="{% trans question_author=question.author.username %}{{question_author}} has selected this answer as correct{% endtrans %}"
- title="{% trans questsion_author=question.author.username%}{{question_author}} has selected this answer as correct{% endtrans %}"
- {% endif %}
- {% endif %}
+ {% include "question/answer_vote_buttons.html" %}
</div>
</td>
<td>
@@ -55,33 +18,9 @@
{% include "widgets/answer_controls.html" %}
</div>
<div class="post-update-info-container">
- {{
- macros.post_contributor_info(
- answer,
- "original_author",
- answer.wiki,
- settings.MIN_REP_TO_EDIT_WIKI
- )
- }}
- {{
- macros.post_contributor_info(
- answer,
- "last_updater",
- answer.wiki,
- settings.MIN_REP_TO_EDIT_WIKI
- )
- }}
+ {% include "question/answer_author_info.html" %}
</div>
- {{
- macros.post_comments_widget(
- post = answer,
- show_post = show_post,
- show_comment = show_comment,
- show_comment_position = show_comment_position,
- user = request.user,
- max_comments = settings.MAX_COMMENTS_TO_SHOW
- )
- }}
+ {% include "question/answer_comments.html" %}
</div>
</td>
</tr>
diff --git a/askbot/skins/default/templates/question/answer_comments.html b/askbot/skins/default/templates/question/answer_comments.html
new file mode 100644
index 00000000..1a1e97fb
--- /dev/null
+++ b/askbot/skins/default/templates/question/answer_comments.html
@@ -0,0 +1,10 @@
+{{
+ macros.post_comments_widget(
+ post = answer,
+ show_post = show_post,
+ show_comment = show_comment,
+ show_comment_position = show_comment_position,
+ user = request.user,
+ max_comments = settings.MAX_COMMENTS_TO_SHOW
+ )
+}}
diff --git a/askbot/skins/default/templates/question/answer_vote_buttons.html b/askbot/skins/default/templates/question/answer_vote_buttons.html
new file mode 100644
index 00000000..bef26b75
--- /dev/null
+++ b/askbot/skins/default/templates/question/answer_vote_buttons.html
@@ -0,0 +1,40 @@
+<img id="answer-img-upvote-{{ answer.id }}" class="answer-img-upvote"
+ {% if user_answer_votes[answer.id] == 1 %}
+ src="{{'/images/vote-arrow-up-on.png'|media}}"
+ {% else %}
+ src="{{'/images/vote-arrow-up.png'|media}}"
+ {% endif %}
+ alt="{% trans %}i like this answer (click again to cancel){% endtrans %}"
+ title="{% trans %}i like this answer (click again to cancel){% endtrans %}"/>
+<div id="answer-vote-number-{{ answer.id }}" class="vote-number" title="{% trans %}current number of votes{% endtrans %}">
+ {{ answer.score }}
+</div>
+<img id="answer-img-downvote-{{ answer.id }}" class="answer-img-downvote"
+ {% if user_answer_votes[answer.id] == -1 %}
+ src="{{'/images/vote-arrow-down-on.png'|media}}"
+ {% else %}
+ src="{{'/images/vote-arrow-down.png'|media}}"
+ {% endif %}
+ alt="{% trans %}i dont like this answer (click again to cancel){% endtrans %}"
+ title="{% trans %}i dont like this answer (click again to cancel){% endtrans %}" />
+{% if request.user == question.author %}
+<img id="answer-img-accept-{{ answer.id }}" class="answer-img-accept"
+ {% if answer.accepted %}
+ src="{{'/images/vote-accepted-on.png'|media}}"
+ {% else %}
+ src="{{'/images/vote-accepted.png'|media}}"
+ {% endif %}
+ alt="{% trans %}mark this answer as favorite (click again to undo){% endtrans %}"
+ title="{% trans %}mark this answer as favorite (click again to undo){% endtrans %}" />
+{% else %}
+ {% if answer.accepted %}
+ <img id="answer-img-accept-{{ answer.id }}" class="answer-img-accept"
+ {% if answer.accepted %}
+ src="{{'/images/vote-accepted-on.png'|media}}"
+ {% else %}
+ src="{{'/images/vote-accepted.png'|media}}"
+ {% endif %}
+ alt="{% trans question_author=question.author.username %}{{question_author}} has selected this answer as correct{% endtrans %}"
+ title="{% trans questsion_author=question.author.username%}{{question_author}} has selected this answer as correct{% endtrans %}"
+ {% endif %}
+{% endif %}
diff --git a/askbot/skins/default/templates/question/content.html b/askbot/skins/default/templates/question/content.html
index 6e16a808..132a9a11 100644
--- a/askbot/skins/default/templates/question/content.html
+++ b/askbot/skins/default/templates/question/content.html
@@ -1,13 +1,11 @@
{% import "macros/macros.html" as macros %}
{% import "macros/utils_macros.html" as utils_macros %}
-<h1><a href="{{ question.get_absolute_url() }}">{{ question.get_question_title() }}</a></h1>
{% include "question/question_card.html" %}
{% if question.closed %}
{% include "question/closed_question_info.html" %}
{% endif %}
{% if answers %}
{% include "question/answer_tab_bar.html" %}
-
{{ utils_macros.paginator(paginator_context) }}
{% for answer in answers %}
{% include "question/answer_card.html" %}
@@ -16,27 +14,7 @@
{% else %}
{% include "question/sharing_prompt_phrase.html" %}
{% endif %}
-<form
- id="fmanswer"
- {% if user == question.author %}style="display:none"{% endif %}
- action="{% url answer question.id %}"
- method="post"
->{% csrf_token %}
- {% include "question/subscribe_by_email_prompt.html" %}
- <div style="clear:both"></div>
- {% if request.user.is_anonymous() and settings.ALLOW_POSTING_BEFORE_LOGGING_IN == False %}
- {% if not question.closed %}
- <a
- class="submit"
- href="{{settings.LOGIN_URL}}?next={% url question question.id %}"
- >{% trans %}Login/Signup to Answer{% endtrans %}</a>
- {% endif %}
- {% else %}
- {% if not question.closed %}
- {% include "question/new_answer_input.html" %}
- {% endif %}
- {% endif %}
-</form>
- {% if request.user == question.author %}
+ {% include "question/new_answer_form.html" %}
+ {% if request.user == question.author %}{# this is outside the form on purpose #}
<input type="button" class="submit after-editor" id="fmanswer_button" value="{% trans %}Answer Your Own Question{% endtrans %}"/>
{%endif%}
diff --git a/askbot/skins/default/templates/question/new_answer_form.html b/askbot/skins/default/templates/question/new_answer_form.html
new file mode 100644
index 00000000..49474baa
--- /dev/null
+++ b/askbot/skins/default/templates/question/new_answer_form.html
@@ -0,0 +1,57 @@
+<form
+ id="fmanswer"
+ {% if user == question.author %}style="display:none"{% endif %}
+ action="{% url answer question.id %}"
+ method="post"
+>{% csrf_token %}
+ {% include "question/subscribe_by_email_prompt.html" %}
+ <div style="clear:both"></div>
+ {% if request.user.is_anonymous() and settings.ALLOW_POSTING_BEFORE_LOGGING_IN == False %}
+ {% if not question.closed %}
+ <a
+ class="submit"
+ href="{{settings.LOGIN_URL}}?next={% url question question.id %}"
+ >{% trans %}Login/Signup to Answer{% endtrans %}</a>
+ {% endif %}
+ {% else %}
+ {% if not question.closed %}
+ <div>
+ {% spaceless %}
+ <h2>
+ {% if answers %}
+ {% trans %}Your answer{% endtrans %}
+ {% else %}
+ {% trans %}Be the first one to answer this question!{% endtrans %}
+ {% endif %}
+ </h2>
+ {% endspaceless %}
+ </div>
+ {% if request.user.is_anonymous() %}
+ <div class="message">{% trans %}you can answer anonymously and then login{% endtrans %}</div>
+ {% else %}
+ <p class="message">
+ {% if request.user==question.author %}
+ {% trans %}answer your own question only to give an answer{% endtrans %}
+ {% else %}
+ {% trans %}please only give an answer, no discussions{% endtrans %}
+ {% endif %}
+ </p>
+ {% endif %}
+ {{ macros.edit_post(answer) }}
+ <input type="submit"
+ {% if user.is_anonymous() %}
+ value="{% trans %}Login/Signup to Post Your Answer{% endtrans %}"
+ {% else %}
+ {% if user == question.author %}
+ value="{% trans %}Answer Your Own Question{% endtrans %}"
+ {% else %}
+ value="{% trans %}Answer the question{% endtrans %}"
+ {% endif %}
+ {% endif %}
+ class="submit after-editor" style="float:left"/>
+ {% if settings.WIKI_ON %}
+ {{ macros.checkbox_in_div(answer.wiki) }}
+ {% endif %}
+ {% endif %}
+ {% endif %}
+</form>
diff --git a/askbot/skins/default/templates/question/new_answer_input.html b/askbot/skins/default/templates/question/new_answer_input.html
deleted file mode 100644
index da4be08a..00000000
--- a/askbot/skins/default/templates/question/new_answer_input.html
+++ /dev/null
@@ -1,37 +0,0 @@
-<div>
- {% spaceless %}
- <h2>
- {% if answers %}
- {% trans %}Your answer{% endtrans %}
- {% else %}
- {% trans %}Be the first one to answer this question!{% endtrans %}
- {% endif %}
- </h2>
- {% endspaceless %}
-</div>
-{% if request.user.is_anonymous() %}
- <div class="message">{% trans %}you can answer anonymously and then login{% endtrans %}</div>
-{% else %}
- <p class="message">
- {% if request.user==question.author %}
- {% trans %}answer your own question only to give an answer{% endtrans %}
- {% else %}
- {% trans %}please only give an answer, no discussions{% endtrans %}
- {% endif %}
- </p>
-{% endif %}
-{{ macros.edit_post(answer) }}
-<input type="submit"
- {% if user.is_anonymous() %}
- value="{% trans %}Login/Signup to Post Your Answer{% endtrans %}"
- {% else %}
- {% if user == question.author %}
- value="{% trans %}Answer Your Own Question{% endtrans %}"
- {% else %}
- value="{% trans %}Answer the question{% endtrans %}"
- {% endif %}
- {% endif %}
- class="submit after-editor" style="float:left"/>
-{% if settings.WIKI_ON %}
- {{ macros.checkbox_in_div(answer.wiki) }}
-{% endif %}
diff --git a/askbot/skins/default/templates/question/question_author_info.html b/askbot/skins/default/templates/question/question_author_info.html
new file mode 100644
index 00000000..e43f8931
--- /dev/null
+++ b/askbot/skins/default/templates/question/question_author_info.html
@@ -0,0 +1,6 @@
+{{
+ macros.post_last_updater_and_creator_info(
+ question,
+ settings.MIN_REP_TO_EDIT_WIKI
+ )
+}}
diff --git a/askbot/skins/default/templates/question/question_card.html b/askbot/skins/default/templates/question/question_card.html
index 337c9018..07223f70 100644
--- a/askbot/skins/default/templates/question/question_card.html
+++ b/askbot/skins/default/templates/question/question_card.html
@@ -1,3 +1,4 @@
+<h1><a href="{{ question.get_absolute_url() }}">{{ question.get_question_title() }}</a></h1>
<table id="question-table" {% if question.deleted %}class="deleted"{%endif%}>
<tr>
<td>
@@ -10,44 +11,14 @@
<div class="question-body">
{{question.html}}
</div>
- {{ macros.tag_list_widget(
- tags = question.get_tag_names(),
- id = 'question-tags',
- css_class = 'post-tags tags',
- tag_css_class = 'post-tag',
- )
- }}
+ {% include "question/question_tags.html" %}
<div id="question-controls" class="post-controls">
{% include "widgets/question_controls.html" %}
</div>
<div class="post-update-info-container">
- {{
- macros.post_contributor_info(
- question,
- "original_author",
- question.wiki,
- settings.MIN_REP_TO_EDIT_WIKI
- )
- }}
- {{
- macros.post_contributor_info(
- question,
- "last_updater",
- question.wiki,
- settings.MIN_REP_TO_EDIT_WIKI,
- )
- }}
+ {% include "question/question_author_info.html" %}
</div>
- {{
- macros.post_comments_widget(
- post = question,
- show_post = show_post,
- show_comment = show_comment,
- show_comment_position = show_comment_position,
- user = request.user,
- max_comments = settings.MAX_COMMENTS_TO_SHOW
- )
- }}
+ {% include "question/question_comments.html" %}
</td>
</tr>
</table>
diff --git a/askbot/skins/default/templates/question/question_comments.html b/askbot/skins/default/templates/question/question_comments.html
new file mode 100644
index 00000000..36d175a5
--- /dev/null
+++ b/askbot/skins/default/templates/question/question_comments.html
@@ -0,0 +1,10 @@
+{{
+ macros.post_comments_widget(
+ post = question,
+ show_post = show_post,
+ show_comment = show_comment,
+ show_comment_position = show_comment_position,
+ user = request.user,
+ max_comments = settings.MAX_COMMENTS_TO_SHOW
+ )
+}}
diff --git a/askbot/skins/default/templates/question/question_tags.html b/askbot/skins/default/templates/question/question_tags.html
new file mode 100644
index 00000000..d104fe05
--- /dev/null
+++ b/askbot/skins/default/templates/question/question_tags.html
@@ -0,0 +1,7 @@
+{{ macros.tag_list_widget(
+ tags = question.get_tag_names(),
+ id = 'question-tags',
+ css_class = 'post-tags tags',
+ tag_css_class = 'post-tag',
+ )
+}}