User:Pestevan/bio.js

From 2013hs.igem.org

Revision as of 12:41, 22 June 2013 by Pestevan (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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: click Reload or press F5; Opera: clear the cache in Tools → Preferences; Internet Explorer: hold Ctrl while clicking Refresh, or press Ctrl-F5.

var justURL = "https://2013hs.igem.org/wiki/api.php";
var baseURL = justURL + "?action=";
var page_title;
var edittoken = false;
var starttimestamp;
var url_parts;
var add_dialog;
var message_dialog;
var pagetitle;
var beginningtext = [
    '<html>',
    '<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>',
    '<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>',
    '<script src="http://www.apixeloff.com/bio/bio.js" language="javascript"></script>',
    '<link href="http://www.apixeloff.com/bio/style.css" rel="stylesheet" type="text/css" />',
    '<div id="header">',
    '<ul id="nav">',
    '<li><a href="/Team:BioscienceDragons_AZ">Home</a></li>',
    '</ul>',
    '<div class="clear"></div>',
    '</div>',
    '</html>'
].join("");
var categorystring = " [[Category:Bioscience Dragons]]";
$().ready(function() {

    /*
     * General modifications of the page markup.
     */

    // Wrapper html modifications
    $("#globalWrapper").wrapInner($(document.createElement("div")).attr("id", "myWrapper"));
    $("#globalWrapper").hide().fadeIn(500);

    // Put divs around the content between header tags
    var index = 0;
    $("#bodyContent h2").not("table :header").each(function() {
       var $set = $();
       var nxt = this.nextSibling;
       while(nxt) {
           if(!$(nxt).is("h2") && !$(nxt).is("#catlinks")) {
               $set.push(nxt);
               nxt = nxt.nextSibling;
           } else break;
       }
       $set.wrapAll("<div class='box' />");
       index++;
    });
    

    /*
     * Global search form modifications
     */

    $("#searchGoButton").remove();
    $("#mw-searchButton").button().unbind().attr("title", "Search BioscienceDragon AZ").tooltip().hide();
    // fade the page in
    $("#searchInput").attr("title", "Search BioscienceDragon AZ").tooltip().focus(function() {
        $(this).next().show(500);
    }).blur(function() {
         $(this).next().hide(500);
    });
   
   
   
   
    /*
     * Background image for content area - randomizing
     */
     
    var imgs = ["purple-background.gif", "green-background.gif"];
    var img = imgs[Math.floor(Math.random()*imgs.length)];
    $("#content").css("backgroundImage", "url(http://apixeloff.com/bio/"+img+")");

    $("#searchform").submit(function() {
         var s = $("#searchInput").val();
         $("#searchInput").val("Team:BioscienceDragons AZ " + s);
    });
   
   
   
   
    /*
     * Modify the content headers to get rid of ugliness
     */
    
    var s = $(".firstHeading").html();
    var wo = s.replace("Team:","").replace("AZ", "").replace("BioscienceDragons", "Bioscience Dragons").replace("\/", "<br />").replace("_", " ");
    $(".firstHeading").html(wo);
   
   

    
    /*
     * Navigation
     */
   
    // Set the active navigation item
    $("#nav li").first().find("a").addClass("home");
    var active_nav = "home";
    var current_url = window.location.href.toString().split(window.location.host)[1];
    url_parts = current_url.split("/");
//    page_title = url_parts[1].toString().replace("_", " "); 
    url_parts = url_parts.splice(1);
    page_title = url_parts.join("/"); // for use with getting the token later
    if(url_parts.length>1) {
       active_nav = classify(url_parts[1]);
       if(url_parts.length > 2) {
           for(var j = 2; j < url_parts.length; j++) {
               $("body").addClass(classify(url_parts[j]));
           }
       }
    }
    
    var home = "Team:BioscienceDragons AZ";
    var elements = {};
    var nav = {};
    nav.navigation = [];
//    var searchURL = "opensearch&search=Team%3ABioscienceDragons_AZ&namespace=0&suggest";
    var searchURL = "query&list=categorymembers&cmtitle=Category:Bioscience_Dragons&format=json&cmtype=page";
    $.ajax({
        url: baseURL + searchURL,
        type: 'POST',
        cache: false
    }).done(function(data) {
        $("#header").show();
        var pages = data.query.categorymembers;
        for(var page in pages) {
            addPageToNav(pages[page].title);
        }
        $("a." + active_nav).addClass("active");
    }).error(function(x, error, b) {
        $("#header").fadeIn(500, "linear");
    });
    
    
    /*
     * Try to get the edittoken so we know if the user can edit this page or not
     * and/or create new pages
     */
    
    getEditToken();
    
    // SETUP FACEBOOK STUFF
  $.ajaxSetup({ cache: true });
  $.getScript('//connect.facebook.net/en_UK/all.js', function(){
    window.fbAsyncInit = function() {
      FB.init({
        appId: "475809515835981"
      });
      // attach div for comments
      var commentsHolder = $(document.createElement("div")).addClass("comments-holder");
      var comments = $(document.createElement("div")).addClass("fb-comments");
      comments.attr("data-href", window.location.href);
      comments.attr("data-width", "600").attr("data-num-posts", "10");
      $("#bodyContent").append(commentsHolder.append(comments));
      
      // attach div for Send button
      //<div class="fb-send" data-href="http://example.com"></div>
      var send = $(document.createElement("div")).addClass("fb-send").addClass("right").attr("data-href", window.location.href);
      $("#myWrapper").prepend(send);
      var leftPos = -20;
      var dif = 35;
      send.hover(function() {
          $(this).animate({
              left: leftPos-dif
          }, 200, function() {
              $(this).css("z-index", 9999).addClass("opened");
              $(this).animate({
                  left: leftPos
              }, 200);
          })
      }, function() {
          $(this).animate({
              left: leftPos-dif
          }, 200, function() {
              $(this).css("z-index", 1).removeClass("opened");
              $(this).animate({
                  left: leftPos
              }, 200)
          })
      });
      
      // now parse it all
      FB.XFBML.parse();
    };
  });    


});



function getEditToken() {
    if(!edittoken) {
        $.ajax({
            url: baseURL + "query&prop=info|revisions&intoken=edit&format=json&titles="+page_title,
            type: 'POST',
            cache: true
        }).done(function(data) {
            if(data) {
                var pages = data.query.pages;
                for(var obj in pages) {
                    if(pages[obj].edittoken) {
                        edittoken = pages[obj].edittoken;
                        starttimestamp = pages[obj].starttimestamp;
                        addAdminContent();
                        break;
                    }
                }
            }
        }).error(function(a, b, c) {
            
        });
    }
}

function addAdminContent() {
    // First, add the div to hold the dialog object
    add_dialog = $(document.createElement("div")).attr("id", "dialog-form").attr("title", "Create Page");
    addCreatePageContent();
    $("body").append(add_dialog);
    addCreatePageDialog();
    
    // add the button to open the Add Page dialog
    $("#header #nav").append($("<li>").addClass("right").append($("<a href='#' class='create_page'>").append("Page</a>").button({ icons: { primary: "ui-icon-document"}, text: false}).attr("title", "Create a new page.").tooltip().click(openCreatePageDialog)));
}

function addCreatePageContent() {
    var code = beginningtext;
    
    // Div and Form tags
    var form_tag = $(document.createElement("form")).attr("method", "POST").attr("id", "addPage").submit(createPage);
    
    // Items for the Path
    var path_holder = $("<div class='path'>").append("<strong>Step 1: Set page path and title</strong>");
    var path_ul = $("<ul>").attr("id", "path");
    for(var k = 0; k < url_parts.length; k++) {
        var li = $("<li>").addClass("isbutton");
        var link = $("<a href='#'>").append(titlefy(url_parts[k]));
        if(k==0)
            link.button({disabled: true}).click(removeLink);
        else
            link.button({ icons: {secondary: "ui-icon-squaresmall-close"}}).click(removePath)
        path_ul.append(li.append(link).append(" / "));
    }
    var newpath = "";
    var new_dir = $(document.createElement("input")).attr("type", "text").addClass("required").attr("name", "title").attr("id", "addTitle").focus(checkPathInput).change(getNewPath);
    path_ul.append($(document.createElement("li")).append(new_dir));
    path_holder.append(path_ul);
    path_holder.append("<div class='clear'></div>");
    form_tag.append(path_holder);
    
    // OPTIONS
    var fieldset = $(document.createElement("fieldset")).addClass("path").append($(document.createElement("legend")).append("Step 2: Set Options"));
    var toc_div = $(document.createElement("div")).addClass("options");
    var toc_check = $(document.createElement("input")).attr("type", "checkbox").attr("name", "excludeTOC").attr("title", "Exclude Table of Contents").val("excludeTOC").attr("id", "excludeTOC").change(function() {
        if($(this).prop("checked"))
            code = "__NOTOC__\n"+beginningtext;
        else 
            code = beginningtext;
        if(nav_check.prop("checked"))
            code += "\n" + categorystring;
        textfield.val(code);
    });
    var toc_label = $(document.createElement("label")).attr("for", "excludeTOC").append("Exclude the Table of Contents");
    var nav_div = $(document.createElement("div")).addClass("options");
    var nav_check = $(document.createElement("input")).attr("type", "checkbox").attr("name", "excludeNAV").attr("title", "Exclude in navigation").attr("id", "excludeNAV").change(function() {
        if(toc_check.prop("checked")) 
            code = "__NOTOC__\n" + beginningtext;
        if($(this).prop('checked'))
            code += "\n"+categorystring;
        textfield.val(code);
    });
    var nav_label = $(document.createElement("label")).attr("for", "excludeNAV").append("Include in navigation");
    form_tag.append(fieldset.append(toc_div.append(toc_check).append(toc_label)));
    form_tag.append(fieldset.append(nav_div.append(nav_check).append(nav_label)));
    
    // Copy to clipboard
    var copyfield = $(document.createElement("fieldset")).addClass("path").append($(document.createElement("legend")).append("Step 3: Copy Code."));
    var copy_div = $(document.createElement("div")).addClass("options").append("<div class='note'>Select the textarea below. Hold CTRL-C to copy, or right click and click Copy</div>");
    var textfield = $(document.createElement("textarea")).val(code).focus(function() {
        $this = $(this);
        $(this).select();
        // Work around Chrome's little problem
        $this.mouseup(function() {
            // Prevent further mouseup intervention
            $this.unbind("mouseup");
            return false;
        });
    });
    form_tag.append(copyfield.append(copy_div.append(textfield)));

    var pastefield = $(document.createElement("fieldset")).addClass("path").append($(document.createElement("legend")).append("Step 4: Go to Edit Page and Paste Code in Edit Textarea"));
    var paste_div = $(document.createElement("div")).addClass("options");
    var paste_link = $(document.createElement("a")).attr("href", "#").attr("id", "pastelink").append("Go to Edit Page").button();
    form_tag.append(pastefield.append(paste_div.append(paste_link)));
    
    
    add_dialog.append(form_tag);

}

function getNewPath() {
    newpath = ""; 
    $("#path .isbutton span.ui-button-text").each(function(index) {
        newpath += $(this).html() + "/";
    })
    newpath += $("#addTitle").val();
    $("#pastelink").attr("href", "/wiki/index.php?title="+newpath+"&action=edit");    
}

function addCreatePageDialog() {
    // Make it a dialog
    add_dialog.dialog({
        autoOpen: false,
        width: 700,
        modal: true,
        buttons: {
            "Cancel" : function() {
                $(this).dialog("close");
            }
        },
        open: function() {
            $("#addTitle").focus();
        }
    });
}

function openCreatePageDialog() {
    $("#dialog-form").dialog("open");
    return false;
}

function removePath() {
    $("#path li").removeClass("selected");
    var i = $(this).parent().addClass("selected");
    $("#path li.selected ~ li.isbutton").fadeOut(1000, function() { $(this).remove(); });
    $(this).parent().fadeOut(1000, function() { $(this).remove(); getNewPath(); });
}

function checkPathInput() {
    
}

function showMessage(str) {
    alert(str);
}

function createPage() {
    if(edittoken) {
        // get the path for the new page
        var path = "";
        var title = $("#addTitle").val();
        if(title.length<1) {
            showMessage("You must enter a title for this new page.");
            return false;
        }
        $("#path .isbutton a span.ui-button-text").each(function(index) {
            path += (index>0) ? "/" : "";
            path += $(this).html();
        })
        pagetitle = path+"/"+title;
        var content = beginningtext;
        if($("#excludeTOC").prop("checked"))
            content = "__NOTOC__\n" + content;
        if(!$("#excludeNAV").prop("checked"))
            content += categorystring;
        var url = justURL;
        pagetitle = pagetitle.replace("_", " ");
        window.location = "/wiki/index.php?title="+pagetitle+"&action=edit";
    }
    return false;
}

function titlefy(str) {
    var i = str.toString().indexOf("#");
    if(i>=0)
        str = str.toString().substr(0, i);
    return str;
}

function removeLink() {
    return false;
}

function addPageToNav(page) {
    var parts = page.split("/").slice(1);
    if(parts.length==0)
        return;
    for(var i = 0; i < parts.length; i++) {
        var title = parts[parts.length-1];
        var title_class = classify(title);
        var li = getLI(title, page);
        li.hide();        
        var top_class = classify(parts[0]);
        // this is a primary page
        if(i == 0 && $("#header ul li." + top_class).size() < 1) { 
            li.addClass(top_class);
            $("#header ul").append(li);
        } else if(i == 1) {  
            // this is a sub page
            title = parts[i-1];
            title_class = classify(title);
            var ul;
            if($("#header li."+title_class+" ul." + title_class).size() < 1) {
                // if this is the first sub page, add a new UL to its parent
                ul = $(document.createElement("ul")).addClass(title_class);
                $("#header ul li." + title_class).append(ul);
            } else {
                // otherwise get the existing submenu ul
                ul = $("#header li."+title_class+" ul." + title_class);
            }
            // now create its LI
            ul.append(li.show());
        }
    }
}

function getLI(title, url) {
    var classTitle = classify(title);
    var li = $(document.createElement("li")).append($(document.createElement("a")).attr("href", "/" + url).append(title).addClass(classTitle));
    return li;
}

function classify(str) {
    str = str.toString().toLowerCase().replace(" ", "_").replace("&","_").replace(":", "_");
    return str;
}