]> git.openstreetmap.org Git - osqa.git/blobdiff - forum/skins/default/media/js/osqa.main.js
be able to submit comment only with Ctrl + Enter
[osqa.git] / forum / skins / default / media / js / osqa.main.js
index b52fd61e764e3f2c729b3d5f2095880c1e3dad99..0c16eeabed6e49166e8ef477d51db2c313947df6 100644 (file)
@@ -1,3 +1,32 @@
+/**\r
+ * We do not want the CSRF protection enabled for the AJAX post requests, it causes only trouble.\r
+ * Get the csrftoken cookie and pass it to the X-CSRFToken HTTP request property.\r
+ */\r
+\r
+$('html').ajaxSend(function(event, xhr, settings) {\r
+    function getCookie(name) {\r
+        var cookieValue = null;\r
+        if (document.cookie && document.cookie != '') {\r
+            var cookies = document.cookie.split(';');\r
+            for (var i = 0; i < cookies.length; i++) {\r
+                var cookie = jQuery.trim(cookies[i]);\r
+                // Does this cookie string begin with the name we want?\r
+                if (cookie.substring(0, name.length + 1) == (name + '=')) {\r
+                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));\r
+                    break;\r
+                }\r
+            }\r
+        }\r
+        return cookieValue;\r
+    }\r
+    try {\r
+        if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {\r
+            // Only send the token to relative URLs i.e. locally.\r
+            xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));\r
+        }\r
+    } catch (e) {}\r
+});\r
+\r
 var response_commands = {\r
     refresh_page: function() {\r
         window.location.reload(true)\r
@@ -71,7 +100,11 @@ var response_commands = {
         });\r
     },\r
 \r
-    insert_comment: function(post_id, comment_id, comment, username, profile_url, delete_url, edit_url) {\r
+    award_points: function(id) {\r
+        alert('ok');\r
+    },\r
+\r
+    insert_comment: function(post_id, comment_id, comment, username, profile_url, delete_url, edit_url, convert_url, can_convert) {\r
         var $container = $('#comments-container-' + post_id);\r
         var skeleton = $('#new-comment-skeleton-' + post_id).html().toString();\r
 \r
@@ -80,10 +113,16 @@ var response_commands = {
                 .replace(new RegExp('%USERNAME%', 'g'), username)\r
                 .replace(new RegExp('%PROFILE_URL%', 'g'), profile_url)\r
                 .replace(new RegExp('%DELETE_URL%', 'g'), delete_url)\r
-                .replace(new RegExp('%EDIT_URL%', 'g'), edit_url);\r
+                .replace(new RegExp('%EDIT_URL%', 'g'), edit_url)\r
+                .replace(new RegExp('%CONVERT_URL%', 'g'), convert_url);\r
 \r
         $container.append(skeleton);\r
 \r
+        // Show the convert comment to answer tool only if the current comment can be converted\r
+        if (can_convert == true) {\r
+            $('#comment-' + comment_id + '-convert').show();\r
+        }\r
+\r
         $('#comment-' + comment_id).slideDown('slow');\r
     },\r
 \r
@@ -95,12 +134,12 @@ var response_commands = {
     },\r
 \r
     mark_deleted: function(post_type, post_id) {\r
-        if (post_type == 'answer') {\r
-            var $answer = $('#answer-container-' + post_id);\r
-            $answer.addClass('deleted');\r
-        } else {\r
+        if (post_type == 'question') {\r
             var $container = $('#question-table');\r
             $container.addClass('deleted');\r
+        } else {\r
+            var $el = $('#' + post_type + '-container-' + post_id);\r
+            $el.addClass('deleted');\r
         }\r
     },\r
 \r
@@ -120,6 +159,9 @@ var response_commands = {
 \r
     set_subscription_status: function(text) {\r
         $('.subscription-status').html(text);\r
+    },\r
+\r
+    copy_url: function(url) {\r
     }\r
 }\r
 \r
@@ -141,11 +183,17 @@ function show_dialog (extern) {
         yes_callback: default_close_function,\r
         no_text: messages.cancel,\r
         show_no: false,\r
-        close_on_clickoutside: false\r
+        close_on_clickoutside: false,\r
+        copy: false\r
     }\r
 \r
     $.extend(options, extern);\r
 \r
+    var copy_id = '';\r
+    if (options.copy) {\r
+        copy_id = ' id="copy_clip_button"'\r
+    }\r
+\r
     if (options.event != undefined) {\r
         options.pos = {x: options.event.pageX, y: options.event.pageY};\r
     }\r
@@ -157,8 +205,7 @@ function show_dialog (extern) {
         html += '<button class="dialog-no">' + options.no_text + '</button>';\r
     }\r
 \r
-    html += '<button class="dialog-yes">' + options.yes_text + '</button>'\r
-            + '</div></div>';\r
+    html += '<button class="dialog-yes"' + copy_id + '>' + options.yes_text + '</button>' + '</div></div>';\r
 \r
     $dialog = $(html);\r
     $('body').append($dialog);\r
@@ -184,10 +231,29 @@ function show_dialog (extern) {
         top: options.pos.y,\r
         left: options.pos.x\r
     });\r
-\r
+    \r
+    top_position_change = (options.dim.h / 2)\r
+    left_position_change = (options.dim.w / 2)\r
+    \r
+    new_top_position = options.pos.y - top_position_change\r
+    new_left_position = options.pos.x - left_position_change\r
+    \r
+    if (new_left_position < 0) {\r
+        left_position_change = 0\r
+    }\r
+    if (($(window).scrollTop() - new_top_position) > 0) {\r
+        top_position_change = 0\r
+    }\r
+    if ((options.event.pageY + options.dim.h) > ($(window).height() + $(window).scrollTop())) {\r
+        top_position_change = options.dim.h\r
+    }\r
+    if ((options.event.pageX + options.dim.w) > ($(window).width() + $(window).scrollLeft())) {\r
+        left_position_change = options.dim.w\r
+    }\r
+    \r
     $dialog.animate({\r
-        top: "-=" + (options.dim.h / 2),\r
-        left: "-=" + (options.dim.w / 2),\r
+        top: "-=" + top_position_change,\r
+        left: "-=" + left_position_change,\r
         width: options.dim.w,\r
         height: options.dim.h\r
     }, 200, function() {\r
@@ -245,7 +311,12 @@ function load_prompt(evt, el, url) {
                     process_ajax_response(data, evt);\r
                 }, 'json');\r
             },\r
-            show_no: true\r
+            show_no: true,\r
+            copy: false\r
+        }\r
+\r
+        if (el.hasClass('copy')) {\r
+            $.extend(doptions, { yes_text : 'Copy', copy: true});\r
         }\r
 \r
         if (!el.is('.centered')) {\r
@@ -263,6 +334,8 @@ function process_ajax_response(data, evt, callback) {
     } else if (typeof data['commands'] != undefined){\r
         for (var command in data.commands) {\r
             response_commands[command].apply(null, data.commands[command])\r
+\r
+\r
         }\r
 \r
         if (data['message'] != undefined) {\r
@@ -294,23 +367,47 @@ function end_command(success) {
     }\r
 }\r
 \r
+var comment_box_cursor_position = 0;\r
+function canned_comment(post_id, comment) {\r
+    textarea = $('#comment-' + post_id + '-form textarea')\r
+\r
+    // Get the text from the beginning to the caret\r
+    textarea_start = textarea.val().substr(0, comment_box_cursor_position)\r
+\r
+    // Get the text from the caret to the end\r
+    textarea_end = textarea.val().substr(comment_box_cursor_position, textarea.val().length)\r
+\r
+    textarea.val(textarea_start + comment + textarea_end);\r
+}\r
+\r
 $(function() {\r
+    $('textarea.commentBox').bind('keydown keyup mousedown mouseup mousemove', function(evt) {\r
+        comment_box_cursor_position = $(this).caret().start;\r
+    });\r
+\r
+    $('textarea.commentBox').blur(function() {\r
+        //alert(comment_box_cursor_position);\r
+    });\r
+\r
     $('a.ajax-command').live('click', function(evt) {\r
         if (running) return false;\r
 \r
-        $('.context-menu-dropdown').slideUp('fast');\r
-\r
         var el = $(this);\r
 \r
+        var ajax_url = el.attr('href')\r
+        ajax_url = ajax_url + "?nocache=" + new Date().getTime()\r
+\r
+        $('.context-menu-dropdown').slideUp('fast');\r
+\r
         if (el.is('.withprompt')) {\r
-            load_prompt(evt, el, el.attr('href'));\r
+            load_prompt(evt, el, ajax_url);\r
         } else if(el.is('.confirm')) {\r
             var doptions = {\r
                 html: messages.confirm,\r
                 extra_class: 'confirm',\r
                 yes_callback: function() {\r
                     start_command();\r
-                    $.getJSON(el.attr('href'), function(data) {\r
+                    $.getJSON(ajax_url, function(data) {\r
                         process_ajax_response(data, evt);\r
                         $dialog.fadeOut('fast', function() {\r
                             $dialog.remove();\r
@@ -328,7 +425,7 @@ $(function() {
             var $dialog = show_dialog(doptions);\r
         } else {\r
             start_command();\r
-            $.getJSON(el.attr('href'), function(data) {\r
+            $.getJSON(ajax_url, function(data) {\r
                 process_ajax_response(data, evt);\r
             });\r
         }\r
@@ -512,6 +609,14 @@ $(function() {
                 return false;\r
             });\r
 \r
+            // Submit comment with CTRL + Enter\r
+            $textarea.keydown(function(e) {\r
+                if (e.ctrlKey && e.keyCode == 13 && !$button.attr('disabled')) {\r
+                    // console.log('submit');\r
+                    $(this).parent().find('input.comment-submit').click();\r
+                }\r
+            });\r
+\r
             $cancel.click(function(event) {\r
                 if (confirm("You will lose all of your changes in this comment.  Do you still wish to proceed?")){\r
                     if (comment_in_form) {\r
@@ -537,8 +642,8 @@ $(function() {
         var $previewer = $('#previewer');\r
         var $container = $('#editor-metrics');\r
 \r
-        var initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi;\r
-        var non_alphanumerics_rExp = rExp = /[^A-Za-z0-9]+/gi;\r
+        var initial_whitespace_rExp = /^[^A-Za-zА-Яа-я0-9]+/gi;\r
+        var non_alphanumerics_rExp = rExp = /[^A-Za-zА-Яа-я0-9]+/gi;\r
         var editor_interval = null;\r
 \r
         $editor.focus(function() {\r
@@ -655,9 +760,9 @@ function pickedTags(){
                 tag_link.attr('rel','tag');\r
                 tag_link.attr('href', scriptUrl + $.i18n._('tags/') + tagname + '/');\r
                 tag_link.html(tagname);\r
-                var del_link = $('<img></img>');\r
+                var del_link = $('<img />');\r
                 del_link.addClass('delete-icon');\r
-                del_link.attr('src', mediaUrl('/media/images/close-small-dark.png'));\r
+                del_link.attr('src', mediaUrl('media/images/close-small-dark.png'));\r
 \r
                 setupTagDeleteEvents(del_link, to_target, tagname, reason, true);\r
 \r
@@ -894,8 +999,8 @@ var i18nZh = {
        'please confirm offensive':"??????????????????????",\r
        'anonymous users cannot flag offensive posts':'???????????',\r
        'cannot flag message as offensive twice':'???????',\r
-       'flag offensive cap exhausted':'?????????????5?\91??\92???',\r
-       'need >15 points to report spam':"??+15??????\91???\92?",\r
+       'flag offensive cap exhausted':'?????????????5?Â\91??Â\92???',\r
+       'need >15 points to report spam':"??+15??????Â\91???Â\92?",\r
        'confirm delete':"?????/????????",\r
        'anonymous users cannot delete/undelete':"???????????????",\r
        'post recovered':"?????????????",\r
@@ -973,8 +1078,8 @@ var i18nEs = {
        'insufficient privilege':'privilegio insuficiente',\r
        'cannot pick own answer as best':'no puede escoger su propia respuesta como la mejor',\r
        'anonymous users cannot select favorite questions':'usuarios anonimos no pueden seleccionar',\r
-       'please login':'por favor inicie sesión',\r
-       'anonymous users cannot vote':'usuarios anónimos no pueden votar',\r
+       'please login':'por favor inicie sesión',\r
+       'anonymous users cannot vote':'usuarios anónimos no pueden votar',\r
        '>15 points requried to upvote': '>15 puntos requeridos para votar positivamente',\r
        '>100 points required to downvote':'>100 puntos requeridos para votar negativamente',\r
        'please see': 'por favor vea',\r
@@ -982,31 +1087,31 @@ var i18nEs = {
        'daily vote cap exhausted':'cuota de votos diarios excedida',\r
        'cannot revoke old vote':'no puede revocar un voto viejo',\r
        'please confirm offensive':"por favor confirme ofensiva",\r
-       'anonymous users cannot flag offensive posts':'usuarios anónimos no pueden marcar publicaciones como ofensivas',\r
+       'anonymous users cannot flag offensive posts':'usuarios anónimos no pueden marcar publicaciones como ofensivas',\r
        'cannot flag message as offensive twice':'no puede marcar mensaje como ofensivo dos veces',\r
        'flag offensive cap exhausted':'cuota para marcar ofensivas ha sido excedida',\r
        'need >15 points to report spam':"necesita >15 puntos para reportar spam",\r
-       'confirm delete':"¿Está seguro que desea borrar esto?",\r
-       'anonymous users cannot delete/undelete':"usuarios anónimos no pueden borrar o recuperar publicaciones",\r
-       'post recovered':"publicación recuperada",\r
-       'post deleted':"publicación borrada?",\r
+       'confirm delete':"¿Está seguro que desea borrar esto?",\r
+       'anonymous users cannot delete/undelete':"usuarios anónimos no pueden borrar o recuperar publicaciones",\r
+       'post recovered':"publicación recuperada",\r
+       'post deleted':"publicación borrada?",\r
        'add comment':'agregar comentario',\r
-       'community karma points':'reputación comunitaria',\r
-       'to comment, need':'para comentar, necesita reputación',\r
+       'community karma points':'reputación comunitaria',\r
+       'to comment, need':'para comentar, necesita reputación',\r
        'delete this comment':'borrar este comentario',\r
        'hide comments':"ocultar comentarios",\r
        'add a comment':"agregar comentarios",\r
        'comments':"comentarios",\r
-       'confirm delete comment':"¿Realmente desea borrar este comentario?",\r
+       'confirm delete comment':"¿Realmente desea borrar este comentario?",\r
        'characters':'caracteres faltantes',\r
        'can write':'tiene ',\r
        'click to close':'haga click para cerrar',\r
        'loading...':'cargando...',\r
-       'tags cannot be empty':'las etiquetas no pueden estar vacías',\r
+       'tags cannot be empty':'las etiquetas no pueden estar vacías',\r
        'tablimits info':"hasta 5 etiquetas de no mas de 20 caracteres cada una",\r
-       'content cannot be empty':'el contenido no puede estar vacío',\r
+       'content cannot be empty':'el contenido no puede estar vacío',\r
        'content minchars': 'por favor introduzca mas de {0} caracteres',\r
-       'please enter title':'por favor ingrese un título',\r
+       'please enter title':'por favor ingrese un título',\r
        'title minchars':"por favor introduzca al menos {0} caracteres",\r
        'delete':'borrar',\r
        'undelete':     'recuperar',\r
@@ -1045,7 +1150,7 @@ var i18n_dict = i18n[i18nLang];
 /*\r
  * Autocomplete - jQuery plugin 1.0.3\r
  *\r
- * Copyright (c) 2007 Dylan Verheul, Dan G. Switzer, Anjesh Tuladhar, Jörn Zaefferer\r
+ * Copyright (c) 2007 Dylan Verheul, Dan G. Switzer, Anjesh Tuladhar, Jörn Zaefferer\r
  *\r
  * Dual licensed under the MIT and GPL licenses:\r
  *   http://www.opensource.org/licenses/mit-license.php\r