User:Yair rand/DiscussionSandbox.js

Note – after saving, you may have to bypass your browser’s cache to see the changes.

  • Mozilla / Firefox / Safari: hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (Command-R on a Macintosh);
  • Konqueror and Chrome: click Reload or press F5;
  • Opera: clear the cache in Tools → Preferences;
  • Internet Explorer: hold Ctrl while clicking Refresh, or press Ctrl-F5.

$(function($){
  $("#discussionstartbutton").click(function(e){
    e.preventDefault();
    $(this).append($("<div>").css({"text-align":"left","padding":"7px"}).append(
      "Title: ", 
      $("<input>").css("width","80%"), 
      $("<textarea>").attr("rows","6"),
      $("<button>").append("Save").click(function(){
        var a = $(this.parentNode).find("input").val(), b = $(this.parentNode).find("textarea").val(), c = 2;
        if( !a || !b ){return}
        document.body.style.cursor = "wait";
        JsMwApi()({action:"query",prop:"info",titles:wgPageName+"/"+a+"|"+wgPageName,intoken:"edit"},function(res){
          res = res.query.pages;
          if( ! res[-1] ){
            $("#previewbox").empty().append($("<span>").css("color","#F00").text("Error: A discussion with this title already exists. Please choose a different title."));
            document.body.style.cursor = "";
            return;
          }
          JsMwApi()({action:"edit",title:wgPageName+"/"+a,createonly:"",text:"{{discussionsection|"+a+"}}\n"+b,watchlist:"watch",token:res[-1].edittoken},function(){
            for(var i in res){
              i != -1 && JsMwApi()({action:"edit",title:wgPageName,summary:"/* " + a + " */ new section", appendtext:"\n\n{{/"+a+"}}",token:res[i].edittoken}, function(){
                location.href = location.pathname + "#" + a;
                location.reload();
              })
            }
          })
        })
      }),
      $("<button>").append("Preview").click(function(){
        $("#previewbox").empty().append("Loading...");
        JsMwApi()({action:"parse",prop:"text",title:wgPageName+"/"+$(this.parentNode).find("input").val(),text:$(this.parentNode).find("textarea").val()},function(res){
          console.log(res);
          $("#previewbox").html(res.parse.text['*']);
        })
      })),
      $("<div>").attr("id","previewbox")
    ).unbind("click");
  })
})