nitdoc: Fix bug: Add a function to close comments
[nit.git] / share / nitdoc / scripts / js-facilities.js
1 // User
2 var userB64 = null;
3 var userName = "";
4 var password = "";
5 var sessionStarted = false;
6 var editComment = 0;
7 var currentfileContent = '';
8 var addNewComment = false;
9 var commentLineStart;
10 var commentLineEnd;
11
12 // SHA GitHub
13 var shaLastCommit = "";
14 var shaBaseTree;
15 var shaNewTree;
16 var shaNewCommit;
17 var shaBlob;
18 var shaMaster;
19 var repoExist = false;
20 var branchExist = false;
21 var githubRepo;
22
23 // Spinner vars
24 var opts = {
25 lines: 11, // The number of lines to draw
26 length: 7, // The length of each line
27 width: 4, // The line thickness
28 radius: 10, // The radius of the inner circle
29 corners: 1, // Corner roundness (0..1)
30 rotate: 0, // The rotation offset
31 color: '#FFF', // #rgb or #rrggbb
32 speed: 1, // Rounds per second
33 trail: 60, // Afterglow percentage
34 shadow: false, // Whether to render a shadow
35 hwaccel: false, // Whether to use hardware acceleration
36 className: 'spinner', // The CSS class to assign to the spinner
37 zIndex: 99999, // The z-index (defaults to 2000000000)
38 top: '300', // Top position relative to parent in px
39 left: 'auto' // Left position relative to parent in px
40 };
41 var targetSpinner = document.getElementById('waitCommit');
42 var spinner = new Spinner(opts).spin(targetSpinner);
43
44 /*
45 * JQuery Case Insensitive :icontains selector
46 */
47 $.expr[':'].icontains = function(obj, index, meta, stack){
48 return (obj.textContent.replace(/\[[0-9]+\]/g, "") || obj.innerText.replace(/\[[0-9]+\]/g, "") || jQuery(obj).text().replace(/\[[0-9]+\]/g, "") || '').toLowerCase().indexOf(meta[3].toLowerCase()) >= 0;
49 };
50
51 /*
52 * Quick Search global vars
53 */
54
55 // Current search results preview table
56 var currentTable = null;
57
58 //Hightlighted index in search result preview table
59 var currentIndex = -1;
60
61 // Check if a comment is editing
62 window.onbeforeunload = function() {
63 if(editComment > 0){
64 return 'Are you sure you want to leave this page?';
65 }
66 };
67
68 /*
69 * Add folding and filtering facilities to class description page.
70 */
71 $(document).ready(function() {
72
73 // Hide edit tags
74 $('textarea').hide();
75 $('a[id=commitBtn]').hide();
76 $('a[id=cancelBtn]').hide();
77 // Hide Authenfication form
78 $(".popover").hide();
79 githubRepo = $('#repoName').attr('name');
80 // Update display
81 updateDisplaying();
82 /*
83 * Highlight the spoted element
84 */
85 highlightBlock(currentAnchor());
86
87 /*
88 * Nav block folding
89 */
90
91 // Menu nav folding
92 $(".menu nav h3")
93 .prepend(
94 $(document.createElement("a"))
95 .html("-")
96 .addClass("fold")
97 )
98 .css("cursor", "pointer")
99 .click( function() {
100 if($(this).find("a.fold").html() == "+") {
101 $(this).find("a.fold").html("-");
102 } else {
103 $(this).find("a.fold").html("+");
104 }
105 $(this).nextAll().toggle();
106 })
107
108 // Insert search field
109 $("nav.main ul")
110 .append(
111 $(document.createElement("li"))
112 .append(
113 $(document.createElement("form"))
114 .append(
115 $(document.createElement("input"))
116 .attr({
117 id: "search",
118 type: "text",
119 autocomplete: "off",
120 value: "quick search..."
121 })
122 .addClass("notUsed")
123
124 // Key management
125 .keyup(function(e) {
126 switch(e.keyCode) {
127
128 // Select previous result on "Up"
129 case 38:
130 // If already on first result, focus search input
131 if(currentIndex == 0) {
132 $("#search").val($(currentTable.find("tr")[currentIndex]).data("searchDetails").name);
133 $("#search").focus();
134 // Else select previous result
135 } else if(currentIndex > 0) {
136 $(currentTable.find("tr")[currentIndex]).removeClass("activeSearchResult");
137 currentIndex--;
138 $(currentTable.find("tr")[currentIndex]).addClass("activeSearchResult");
139 $("#search").val($(currentTable.find("tr")[currentIndex]).data("searchDetails").name);
140 $("#search").focus();
141 }
142 break;
143
144 // Select next result on "Down"
145 case 40:
146 if(currentIndex < currentTable.find("tr").length - 1) {
147 $(currentTable.find("tr")[currentIndex]).removeClass("activeSearchResult");
148 currentIndex++;
149 $(currentTable.find("tr")[currentIndex]).addClass("activeSearchResult");
150 $("#search").val($(currentTable.find("tr")[currentIndex]).data("searchDetails").name);
151 $("#search").focus();
152 }
153 break;
154 // Go to url on "Enter"
155 case 13:
156 if(currentIndex > -1) {
157 window.location = $(currentTable.find("tr")[currentIndex]).data("searchDetails").url;
158 return false;
159 }
160 if($("#search").val().length == 0)
161 return false
162
163 window.location = "full-index.html#q=" + $("#search").val();
164 if(window.location.href.indexOf("full-index.html") > -1) {
165 location.reload();
166 }
167 return false;
168 break;
169
170 // Hide results preview on "Escape"
171 case 27:
172 $(this).blur();
173 if(currentTable != null) {
174 currentTable.remove();
175 currentTable = null;
176 }
177 break;
178
179 default:
180 if($("#search").val().length == 0) {
181 return false;
182 }
183
184 // Remove previous table
185 if(currentTable != null) {
186 currentTable.remove();
187 }
188
189 // Build results table
190 currentIndex = -1;
191 currentTable = $(document.createElement("table"));
192
193 // Escape regexp related characters in query
194 var query = $("#search").val();
195 query = query.replace(/\[/gi, "\\[");
196 query = query.replace(/\|/gi, "\\|");
197 query = query.replace(/\*/gi, "\\*");
198 query = query.replace(/\+/gi, "\\+");
199 query = query.replace(/\\/gi, "\\\\");
200 query = query.replace(/\?/gi, "\\?");
201 query = query.replace(/\(/gi, "\\(");
202 query = query.replace(/\)/gi, "\\)");
203
204 var index = 0;
205 var regexp = new RegExp("^" + query, "i");
206 for(var entry in entries) {
207 if(index > 10) {
208 break;
209 }
210 var result = entry.match(regexp);
211 if(result != null && result.toString().toUpperCase() == $("#search").val().toUpperCase()) {
212 for(var i = 0; i < entries[entry].length; i++) {
213 if(index > 10) {
214 break;
215 }
216 currentTable.append(
217 $(document.createElement("tr"))
218 .data("searchDetails", {name: entry, url: entries[entry][i]["url"]})
219 .data("index", index)
220 .append($(document.createElement("td")).html(entry))
221 .append(
222 $(document.createElement("td"))
223 .addClass("entryInfo")
224 .html(entries[entry][i]["txt"] + "&nbsp;&raquo;"))
225 .mouseover( function() {
226 $(currentTable.find("tr")[currentIndex]).removeClass("activeSearchResult");
227 $(this).addClass("activeSearchResult");
228 currentIndex = $(this).data("index");
229 })
230 .mouseout( function() {
231 $(this).removeClass("activeSearchResult");
232 })
233 .click( function() {
234 window.location = $(this).data("searchDetails")["url"];
235 })
236 );
237 index++;
238 }
239 }
240 }
241
242 // Initialize table properties
243 currentTable.attr("id", "searchTable");
244 currentTable.css("position", "absolute");
245 currentTable.width($("#search").outerWidth());
246 $("header").append(currentTable);
247 currentTable.offset({left: $("#search").offset().left + ($("#search").outerWidth() - currentTable.outerWidth()), top: $("#search").offset().top + $("#search").outerHeight()});
248
249 // Preselect first entry
250 if(currentTable.find("tr").length > 0) {
251 currentIndex = 0;
252 $(currentTable.find("tr")[currentIndex]).addClass("activeSearchResult");
253 $("#search").focus();
254 }
255 break;
256 }
257 })
258 .focusout(function() {
259 if($(this).val() == "") {
260 $(this).addClass("notUsed");
261 $(this).val("quick search...");
262 }
263 })
264 .focusin(function() {
265 if($(this).val() == "quick search...") {
266 $(this).removeClass("notUsed");
267 $(this).val("");
268 }
269 })
270 )
271 .submit( function() {
272 return false;
273 })
274 )
275 );
276
277 // Close quicksearch list on click
278 $(document).click(function(e) {
279 if(e.target != $("#search")[0] && e.target != $("#searchTable")[0]) {
280 if(currentTable != null) {
281 currentTable.remove();
282 currentTable = null;
283 }
284 }
285 });
286
287 // Insert filter field
288 $("article.filterable h2, nav.filterable h3")
289 .after(
290 $(document.createElement("div"))
291 .addClass("filter")
292 .append(
293 $(document.createElement("input"))
294 .attr({
295 type: "text",
296 value: "filter..."
297 })
298 .addClass("notUsed")
299 .keyup(function() {
300 $(this).parent().parent().find("ul li:not(:icontains('" + $(this).val() + "'))").addClass("hide");
301 $(this).parent().parent().find("ul li:icontains('" + $(this).val() + "')").removeClass("hide");
302 })
303 .focusout(function() {
304 if($(this).val() == "") {
305 $(this).addClass("notUsed");
306 $(this).val("filter...");
307 }
308 })
309 .focusin(function() {
310 if($(this).val() == "filter...") {
311 $(this).removeClass("notUsed");
312 $(this).val("");
313 }
314 })
315 )
316 );
317
318 // Filter toggle between H I R in nav porperties list
319 $("nav.properties.filterable .filter")
320 .append(
321 $(document.createElement("a"))
322 .html("H")
323 .attr({
324 title: "hide inherited properties"
325 })
326 .click( function() {
327 if($(this).hasClass("hidden")) {
328 $(this).parent().parent().find("li.inherit").show();
329 } else {
330 $(this).parent().parent().find("li.inherit").hide();
331 }
332
333 $(this).toggleClass("hidden");
334 })
335 )
336 .append(
337 $(document.createElement("a"))
338 .html("R")
339 .attr({
340 title: "hide redefined properties"
341 })
342 .click( function() {
343 if($(this).hasClass("hidden")) {
344 $(this).parent().parent().find("li.redef").show();
345 } else {
346 $(this).parent().parent().find("li.redef").hide();
347 }
348
349 $(this).toggleClass("hidden");
350 })
351 )
352 .append(
353 $(document.createElement("a"))
354 .html("I")
355 .attr({
356 title: "hide introduced properties"
357 })
358 .click( function() {
359 if($(this).hasClass("hidden")) {
360 $(this).parent().parent().find("li.intro").show();
361 } else {
362 $(this).parent().parent().find("li.intro").hide();
363 }
364
365 $(this).toggleClass("hidden");
366 })
367 );
368
369 // Filter toggle between I R in
370 $("article.properties.filterable .filter, article.classes.filterable .filter")
371 .append(
372 $(document.createElement("a"))
373 .html("I")
374 .attr({
375 title: "hide introduced properties"
376 })
377 .click( function() {
378 if($(this).hasClass("hidden")) {
379 $(this).parent().parent().find("li.intro").show();
380 } else {
381 $(this).parent().parent().find("li.intro").hide();
382 }
383
384 $(this).toggleClass("hidden");
385 })
386 )
387 .append(
388 $(document.createElement("a"))
389 .html("R")
390 .attr({
391 title: "hide redefined properties"
392 })
393 .click( function() {
394 if($(this).hasClass("hidden")) {
395 $(this).parent().parent().find("li.redef").show();
396 } else {
397 $(this).parent().parent().find("li.redef").hide();
398 }
399
400 $(this).toggleClass("hidden");
401 })
402 );
403
404 /*
405 * Anchors jumps
406 */
407 $("a[href*='#']").click( function() {
408 highlightBlock($(this).attr("href").split(/#/)[1]);
409 });
410
411 //Preload filter fields with query string
412 preloadFilters();
413 // Hide Authenfication form
414 $(".popover").hide();
415 // Display Login modal
416 $("#logGitHub").click(function(){ displayLogginModal(); });
417 // Update display
418 updateDisplaying();
419 // If cookie existing the session is opened
420 if(sessionStarted){ userB64 = "Basic " + getUserPass("logginNitdoc"); }
421
422 // Sign In an github user or Log out him
423 $("#signIn").click(function(){
424 if(!sessionStarted){
425 if($('#loginGit').val() == "" || $('#passwordGit').val() == ""){ displayMessage('The comment field is empty!', 40, 45); }
426 else
427 {
428 userName = $('#loginGit').val();
429 password = $('#passwordGit').val();
430 repoName = $('#repositoryGit').val();
431 branchName = $('#branchGit').val();
432 userB64 = "Basic " + base64.encode(userName+':'+password);
433 setCookie("logginNitdoc", base64.encode(userName+':'+password+':'+repoName+':'+branchName), 1);
434 $('#loginGit').val("");
435 $('#passwordGit').val("");
436 reloadComment();
437 }
438 }
439 else
440 {
441 // Delete cookie and reset settings
442 del_cookie("logginNitdoc");
443 closeAllCommentInEdtiting();
444 }
445 displayLogginModal();
446 });
447
448 // Activate edit mode
449 $('pre[class=text_label]').click(function(){
450 // the customer is loggued ?
451 if(!sessionStarted || userName == ""){
452 // No => nothing happen
453 return;
454 }
455 else{
456 var arrayNew = $(this).text().split('\n');
457 var lNew = arrayNew.length - 1;
458 var adapt = "";
459
460 for (var i = 0; i < lNew; i++) {
461 adapt += arrayNew[i];
462 if(i < lNew-1){ adapt += "\n"; }
463 }
464 editComment += 1;
465 // hide comment
466 $(this).hide();
467 // Show edit box
468 $(this).next().show();
469 // Show cancel button
470 $(this).next().next().show();
471 // Show commit button
472 $(this).next().next().next().show();
473 // Add text in edit box
474 if($(this).next().val() == "" || $(this).next().val() != adapt){ $(this).next().val(adapt); }
475 // Resize edit box
476 $(this).next().height($(this).next().prop("scrollHeight"));
477 // Select it
478 $(this).next().select();
479 preElement = $(this);
480 }
481 });
482
483 // Disable the edit mode
484 $('a[id=cancelBtn]').click(function(){
485 closeEditing($(this));
486 });
487
488 // Display commit form
489 $('a[id=commitBtn]').click(function(){
490 updateComment = $(this).prev().prev().val();
491 commentType = $(this).prev().prev().prev().attr('type');
492
493 if(updateComment == ""){ displayMessage('The comment field is empty!', 40, 45); }
494 else{
495 if(!sessionStarted){
496 displayMessage("You need to be loggued before commit something", 45, 40);
497 displayLogginModal();
498 return;
499 }
500 $('#commitMessage').val('New commit');
501 pathFile = $(this).prev().prev().prev().attr('tag');
502 $('#modal').show().prepend('<a class="close"><img src="resources/icons/close.png" class="btn_close" title="Close" alt="Close" /></a>');
503 $('body').append('<div id="fade"></div>');
504 $('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn();
505 }
506 });
507
508 // Close commit form
509 $('.btn_close').click(function(){
510 $(this).hide();
511 $(this).next().hide();
512 if(editComment > 0){ editComment -= 1; }
513 });
514
515 //Close Popups and Fade Layer
516 $('body').on('click', 'a.close, #fade', function() {
517 if(editComment > 0){ editComment -= 1; }
518 $('#fade , #modal').fadeOut(function() {
519 $('#fade, a.close').remove();
520 });
521 $('#modalQuestion').hide();
522 });
523
524 $('#loginAction').click(function(){
525 var text;
526 var url;
527 var line;
528 // Look if the customer is logged
529 if(!sessionStarted){
530 displayMessage("You need to be loggued before commit something", 100, 40);
531 $('.popover').show();
532 return;
533 }
534 else{ userB64 = "Basic " + getUserPass("logginNitdoc"); }
535 githubRepo = repoName;
536 // Check if repo exist
537 isRepoExisting();
538 if(repoExist){
539 isBranchExisting();
540 if(branchExist){
541 editComment -= 1;
542 commitMessage = $('#commitMessage').val();
543 if(commitMessage == ""){ commitMessage = "New commit";}
544 if(sessionStarted){
545 if ($.trim(updateComment) == ''){ this.value = (this.defaultValue ? this.defaultValue : ''); }
546 else{
547 displaySpinner();
548 startCommitProcess();
549 }
550 }
551 $('#modal, #modalQuestion').fadeOut(function() {
552 $('#login').val("");
553 $('#password').val("");
554 $('textarea').hide();
555 $('textarea').prev().show();
556 });
557 $('a[id=cancelBtn]').hide();
558 $('a[id=commitBtn]').hide();
559 // Re-load all comment
560 reloadComment();
561 }
562 }
563 else{ editComment -= 1; }
564 });
565
566 // Cancel creating branch
567 $('#btnCancelBranch').click(function(){
568 editComment -= 1;
569 $('#modalQuestion').hide();
570 $('#fade , #modal').fadeOut(function() { $('#fade, a.close').remove(); });
571 return;
572 });
573
574 // Create new branch and continu
575 $('#btnCreateBranch').click(function(){
576 $('#modalQuestion').hide();
577 if($('#btnCreateBranch').text() != 'Ok'){
578 // Create the branch
579 createBranch();
580 commitMessage = $('#commitMessage').val();
581 if(commitMessage == ""){ commitMessage = "New commit"; }
582 if(userB64 != ""){
583 if ($.trim(updateComment) == ''){ this.value = (this.defaultValue ? this.defaultValue : ''); }
584 else{ startCommitProcess(); }
585 }
586 }
587 else
588 {
589 $('#fade , #modalQuestion, #modal').fadeOut(function() { $('#fade, a.close').remove(); });
590 }
591 });
592
593 $('a[class=newComment]').click(function(){
594 addNewComment = true;
595 editComment += 1;
596 // hide comment
597 $(this).hide();
598 // Show edit box
599 $(this).next().show();
600 // Show cancel button
601 $(this).next().next().show();
602 // Show commit button
603 $(this).next().next().next().show();
604 // Resize edit box
605 $(this).next().height($(this).next().prop("scrollHeight"));
606 // Select it
607 $(this).next().select();
608 preElement = $(this);
609 });
610
611 $("#dropBranches").change(function () {
612 $("#dropBranches option:selected").each(function () {
613 if(branchName != $(this).text()){
614 branchName = $(this).text();
615 }
616 });
617 $.when(updateCookie(userName, password, repoName, branchName)).done(function(){
618 closeAllCommentInEdtiting();
619 reloadComment();
620 });
621 });
622 });
623
624 /* Parse current URL and return anchor name */
625 function currentAnchor() {
626 var index = document.location.hash.indexOf("#");
627 if (index >= 0) {
628 return document.location.hash.substring(index + 1);
629 }
630 return null;
631 }
632
633 /* Prealod filters field using search query */
634 function preloadFilters() {
635 // Parse URL and get query string
636 var search = currentAnchor();
637
638 if(search == null || search.indexOf("q=") == -1)
639 return;
640
641 search = search.substring(2, search.length);
642
643 if(search == "" || search == "undefined")
644 return;
645
646 $(":text").val(search);
647 $(".filter :text")
648 .removeClass("notUsed")
649 .trigger("keyup");
650
651 }
652
653 /* Hightlight the spoted block */
654 function highlightBlock(a) {
655 if(a == undefined) {
656 return;
657 }
658
659 $(".highlighted").removeClass("highlighted");
660
661 var target = $("#" + a);
662
663 if(target.is("article")) {
664 target.parent().addClass("highlighted");
665 }
666
667 target.addClass("highlighted");
668 target.show();
669 }
670
671 // Init process to commit the new comment
672 function startCommitProcess()
673 {
674 var numL = preElement.attr("title");
675 commentLineStart = numL.split('-')[0] - 1;
676 if(addNewComment) { commentLineStart++; }
677 commentLineEnd = (commentLineStart + preElement.text().split('\n').length) - 1;
678 state = true;
679 replaceComment(updateComment, currentfileContent);
680 getLastCommit();
681 getBaseTree();
682 editComment = false;
683 }
684
685 function displayLogginModal(){
686 if ($('.popover').is(':hidden')) {
687 if(sessionStarted){ getListBranches(); }
688 $('.popover').show();
689 }
690 else { $('.popover').hide(); }
691 updateDisplaying();
692 }
693
694 function updateDisplaying(){
695 if (checkCookie())
696 {
697 userB64 = "Basic " + getUserPass("logginNitdoc");
698 $('#loginGit').hide();
699 $('#passwordGit').hide();
700 $('#lbpasswordGit').hide();
701 $('#lbloginGit').hide();
702 $('#repositoryGit').hide();
703 $('#lbrepositoryGit').hide();
704 $('#lbbranchGit').hide();
705 $('#branchGit').hide();
706 $('#listBranches').show();
707 $("#liGitHub").attr("class", "current");
708 $("#imgGitHub").attr("src", "resources/icons/github-icon-w.png");
709 $('#nickName').text(userName);
710 $('#githubAccount').attr("href", "https://github.com/"+userName);
711 $('#logginMessage').css({'display' : 'block'});
712 $('#logginMessage').css({'text-align' : 'center'});
713 $('.popover').css({'height' : '120px'});
714 $('#signIn').text("Sign out");
715 sessionStarted = true;
716 reloadComment();
717 }
718 else
719 {
720 sessionStarted = false;
721 $('#logginMessage').css({'display' : 'none'});
722 $("#liGitHub").attr("class", "");
723 $("#imgGitHub").attr("src", "resources/icons/github-icon.png");
724 $('#loginGit').val("");
725 $('#passwordGit').val("");
726 $('#nickName').text("");
727 $('.popover').css({'height' : '280px'});
728 $('#logginMessage').css({'display' : 'none'});
729 $('#repositoryGit').val($('#repoName').attr('name'));
730 $('#branchGit').val('wikidoc');
731 $('#signIn').text("Sign In");
732 $('#loginGit').show();
733 $('#passwordGit').show();
734 $('#lbpasswordGit').show();
735 $('#lbloginGit').show();
736 $('#repositoryGit').show();
737 $('#lbrepositoryGit').show();
738 $('#lbbranchGit').show();
739 $('#branchGit').show();
740 $('#listBranches').hide();
741 }
742 }
743
744 function setCookie(c_name, value, exdays)
745 {
746 var exdate=new Date();
747 exdate.setDate(exdate.getDate() + exdays);
748 var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
749 document.cookie=c_name + "=" + c_value;
750 }
751
752 function del_cookie(c_name)
753 {
754 document.cookie = c_name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
755 }
756
757 function updateCookie(user, pwd, repo, branch){
758 if(checkCookie()){
759 branchName = branch;
760 setCookie("logginNitdoc", base64.encode(user+':'+pwd+':'+repo+':'+branch), 1);
761 }
762 }
763
764 function getCookie(c_name)
765 {
766 var c_value = document.cookie;
767 var c_start = c_value.indexOf(" " + c_name + "=");
768 if (c_start == -1) { c_start = c_value.indexOf(c_name + "="); }
769 if (c_start == -1) { c_value = null; }
770 else
771 {
772 c_start = c_value.indexOf("=", c_start) + 1;
773 var c_end = c_value.indexOf(";", c_start);
774 if (c_end == -1) { c_end = c_value.length; }
775 c_value = unescape(c_value.substring(c_start,c_end));
776 }
777 return c_value;
778 }
779
780 function getUserPass(c_name){
781 var cookie = base64.decode(getCookie(c_name));
782 return base64.encode(cookie.split(':')[0] + ':' + cookie.split(':')[1]);
783 }
784
785 function checkCookie()
786 {
787 var cookie=getCookie("logginNitdoc");
788 if (cookie!=null && cookie!="")
789 {
790 cookie = base64.decode(cookie);
791 userName = cookie.split(':')[0];
792 password = cookie.split(':')[1];
793 repoName = cookie.split(':')[2];
794 branchName = cookie.split(':')[3];
795 return true;
796 }
797 else { return false; }
798 }
799
800
801 /*
802 * Base64
803 */
804 base64 = {};
805 base64.PADCHAR = '=';
806 base64.ALPHA = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
807 base64.getbyte64 = function(s,i) {
808 // This is oddly fast, except on Chrome/V8.
809 // Minimal or no improvement in performance by using a
810 // object with properties mapping chars to value (eg. 'A': 0)
811 var idx = base64.ALPHA.indexOf(s.charAt(i));
812 if (idx == -1) {
813 throw "Cannot decode base64";
814 }
815 return idx;
816 }
817
818 base64.decode = function(s) {
819 // convert to string
820 s = "" + s;
821 var getbyte64 = base64.getbyte64;
822 var pads, i, b10;
823 var imax = s.length
824 if (imax == 0) {
825 return s;
826 }
827
828 if (imax % 4 != 0) {
829 throw "Cannot decode base64";
830 }
831
832 pads = 0
833 if (s.charAt(imax -1) == base64.PADCHAR) {
834 pads = 1;
835 if (s.charAt(imax -2) == base64.PADCHAR) {
836 pads = 2;
837 }
838 // either way, we want to ignore this last block
839 imax -= 4;
840 }
841
842 var x = [];
843 for (i = 0; i < imax; i += 4) {
844 b10 = (getbyte64(s,i) << 18) | (getbyte64(s,i+1) << 12) |
845 (getbyte64(s,i+2) << 6) | getbyte64(s,i+3);
846 x.push(String.fromCharCode(b10 >> 16, (b10 >> 8) & 0xff, b10 & 0xff));
847 }
848
849 switch (pads) {
850 case 1:
851 b10 = (getbyte64(s,i) << 18) | (getbyte64(s,i+1) << 12) | (getbyte64(s,i+2) << 6)
852 x.push(String.fromCharCode(b10 >> 16, (b10 >> 8) & 0xff));
853 break;
854 case 2:
855 b10 = (getbyte64(s,i) << 18) | (getbyte64(s,i+1) << 12);
856 x.push(String.fromCharCode(b10 >> 16));
857 break;
858 }
859 return x.join('');
860 }
861
862 base64.getbyte = function(s,i) {
863 var x = s.charCodeAt(i);
864 if (x > 255) {
865 throw "INVALID_CHARACTER_ERR: DOM Exception 5";
866 }
867 return x;
868 }
869
870
871 base64.encode = function(s) {
872 if (arguments.length != 1) {
873 throw "SyntaxError: Not enough arguments";
874 }
875 var padchar = base64.PADCHAR;
876 var alpha = base64.ALPHA;
877 var getbyte = base64.getbyte;
878
879 var i, b10;
880 var x = [];
881
882 // convert to string
883 s = "" + s;
884
885 var imax = s.length - s.length % 3;
886
887 if (s.length == 0) {
888 return s;
889 }
890 for (i = 0; i < imax; i += 3) {
891 b10 = (getbyte(s,i) << 16) | (getbyte(s,i+1) << 8) | getbyte(s,i+2);
892 x.push(alpha.charAt(b10 >> 18));
893 x.push(alpha.charAt((b10 >> 12) & 0x3F));
894 x.push(alpha.charAt((b10 >> 6) & 0x3f));
895 x.push(alpha.charAt(b10 & 0x3f));
896 }
897 switch (s.length - imax) {
898 case 1:
899 b10 = getbyte(s,i) << 16;
900 x.push(alpha.charAt(b10 >> 18) + alpha.charAt((b10 >> 12) & 0x3F) +
901 padchar + padchar);
902 break;
903 case 2:
904 b10 = (getbyte(s,i) << 16) | (getbyte(s,i+1) << 8);
905 x.push(alpha.charAt(b10 >> 18) + alpha.charAt((b10 >> 12) & 0x3F) +
906 alpha.charAt((b10 >> 6) & 0x3f) + padchar);
907 break;
908 }
909 return x.join('');
910 }
911
912
913
914 function getLastCommit()
915 {
916 var urlHead = '';
917 if(sessionStarted){ urlHead = "https://api.github.com/repos/"+userName+"/"+githubRepo+"/git/refs/heads/"+branchName;}
918 else{
919 // TODO: get url of the original repo.
920 return;
921 }
922
923 $.ajax({
924 beforeSend: function (xhr) {
925 if (userB64 != ""){ xhr.setRequestHeader ("Authorization", userB64); }
926 },
927 type: "GET",
928 url: urlHead,
929 dataType:"json",
930 async: false,
931 success: function(success)
932 {
933 shaLastCommit = success.object.sha;
934 }
935 });
936 }
937
938 function getBaseTree()
939 {
940 $.ajax({
941 beforeSend: function (xhr) {
942 if (userB64 != ""){ xhr.setRequestHeader ("Authorization", userB64); }
943 },
944 type: "GET",
945 url: "https://api.github.com/repos/"+userName+"/"+githubRepo+"/git/commits/" + shaLastCommit,
946 dataType:"json",
947 async: false,
948 success: function(success)
949 {
950 shaBaseTree = success.tree.sha;
951 if (state){ setBlob(); }
952 else{ return; }
953 },
954 error: function(){
955 return;
956 }
957 });
958 }
959
960 function setNewTree()
961 {
962 $.ajax({
963 beforeSend: function (xhr) { xhr.setRequestHeader ("Authorization", userB64); },
964 type: "POST",
965 url: "https://api.github.com/repos/"+userName+"/"+githubRepo+"/git/trees",
966 async: false,
967 data:'{ "base_tree" : "'+shaBaseTree+'", '+
968 '"tree":[{ '+
969 '"path":"'+ pathFile +'",'+
970 '"mode":"100644",'+
971 '"type":"blob",'+
972 '"sha": "'+ shaBlob +'"'+
973 '}] '+
974 '}',
975 success: function(success)
976 { // si l'appel a bien fonctionné
977 shaNewTree = JSON.parse(success).sha;
978 setNewCommit();
979 },
980 error: function(){
981 return;
982 }
983 });
984 }
985
986 function setNewCommit()
987 {
988 $.ajax({
989 beforeSend: function (xhr) { xhr.setRequestHeader ("Authorization", userB64); },
990 type: "POST",
991 url: "https://api.github.com/repos/"+userName+"/"+githubRepo+"/git/commits",
992 async: false,
993 data:'{ "message" : "'+ commitMessage +'", '+
994 '"parents" :"'+shaLastCommit+'",'+
995 '"tree": "'+shaNewTree+'"'+
996 '}',
997 success: function(success)
998 {
999 shaNewCommit = JSON.parse(success).sha;
1000 commit();
1001 },
1002 error: function(){
1003 return;
1004 }
1005 });
1006 }
1007
1008 //Create a commit
1009 function commit()
1010 {
1011 $.ajax({
1012 beforeSend: function (xhr) { xhr.setRequestHeader ("Authorization", userB64); },
1013 type: "POST",
1014 url: "https://api.github.com/repos/"+userName+"/"+githubRepo+"/git/refs/heads/"+branchName,
1015 data:'{ "sha" : "'+shaNewCommit+'", '+
1016 '"force" :"true"'+
1017 '}',
1018 success: function(success) { displayMessage('Commit created successfully', 40, 40); },
1019 error:function(error){ displayMessage('Error ' + JSON.parse(error).object.message, 40, 40); }
1020 });
1021 }
1022
1023 // Create a blob
1024 function setBlob()
1025 {
1026 $.ajax({
1027 beforeSend: function (xhr) { xhr.setRequestHeader ("Authorization", userB64); },
1028 type: "POST",
1029 url: "https://api.github.com/repos/"+userName+"/"+githubRepo+"/git/blobs",
1030 async: false,
1031 data:'{ "content" : "'+text.replace(/\r?\n/g, '\\n').replace(/\t/g, '\\t').replace(/\"/g,'\\"')+'", '+
1032 '"encoding" :"utf-8"'+
1033 '}',
1034 success: function(success)
1035 {
1036 shaBlob = JSON.parse(success).sha;
1037 setNewTree();
1038 },
1039 error:function(error){
1040 displayMessage('Error : Problem parsing JSON', 40, 40);
1041 return;
1042 }
1043 });
1044 }
1045
1046 // Display file content
1047 function getFileContent(urlFile, newComment)
1048 {
1049 $.ajax({
1050 beforeSend: function (xhr) {
1051 xhr.setRequestHeader ("Accept", "application/vnd.github-blob.raw");
1052 if (userB64 != ""){ xhr.setRequestHeader ("Authorization", userB64); }
1053 },
1054 type: "GET",
1055 url: urlFile,
1056 async:false,
1057 success: function(success)
1058 {
1059 state = true;
1060 replaceComment(newComment, success);
1061 }
1062 });
1063 }
1064
1065 function replaceComment(newComment, fileContent){
1066 var arrayNew = newComment.split('\n');
1067 var lNew = arrayNew.length;
1068 text = "";
1069 var lines = fileContent.split("\n");
1070 for (var i = 0; i < lines.length; i++) {
1071 if(i == commentLineStart){
1072 if(addNewComment){
1073 for(var indexLine=0; indexLine < lines[i+1].length; indexxLine++){
1074 if(lines[i+1].substr(indexLine,1) == "\t" || lines[i+1].substr(indexLine,1) == "#"){ text += lines[i+1].substr(indexLine,1); }
1075 else{ break;}
1076 }
1077 text += lines[i] + "\n";
1078 }
1079 // We change the comment
1080 for(var j = 0; j < lNew; j++){
1081 if(commentType == 1){ text += "\t# " + arrayNew[j] + "\n"; }
1082 else{
1083 if(arrayNew[j] == ""){ text += "#"+"\n"; }
1084 else{ text += "# " + arrayNew[j] + "\n"; }
1085 }
1086 }
1087 }
1088 else if(i < commentLineStart || i >= commentLineEnd){
1089 if(i == lines.length-1){ text += lines[i]; }
1090 else{ text += lines[i] + "\n"; }
1091 }
1092 }
1093 if(addNewComment){
1094 addNewComment = false;
1095 }
1096 }
1097
1098 function getCommentLastCommit(path){
1099 var urlRaw;
1100 getLastCommit();
1101 if(shaLastCommit != ""){
1102 if (checkCookie()) { urlRaw="https://rawgithub.com/"+ userName +"/"+ repoName +"/" + shaLastCommit + "/" + path; }
1103 else{ urlRaw="https://rawgithub.com/StefanLage/"+ $('#repoName').attr('name') +"/" + shaLastCommit + "/" + path; }
1104
1105 $.ajax({
1106 type: "GET",
1107 url: urlRaw,
1108 async: false,
1109 success: function(success)
1110 {
1111 currentfileContent = success;
1112 }
1113 });
1114 }
1115 }
1116
1117 function displayMessage(msg, widthDiv, margModal){
1118 spinner.stop();
1119 $('#modal').hide();
1120 $('#btnCreateBranch').css('margin-left',widthDiv + '%');
1121 $('#txtQuestion').text(msg);
1122 $('#btnCreateBranch').text("Ok");
1123 $('#btnCancelBranch').hide();
1124 $('#modalQuestion').css({'left' : margModal + '%'})
1125 $('#modalQuestion').show();
1126 $('#modalQuestion').show().prepend('<a class="close"><img src="resources/icons/close.png" class="btnCloseQuestion" title="Close" alt="Close" /></a>');
1127 $('body').append('<div id="fade"></div>');
1128 $('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn();
1129 }
1130
1131 function displaySpinner(){
1132 spinner.spin(targetSpinner);
1133 $("#waitCommit").show();
1134 }
1135
1136 // Check if the repo already exist
1137 function isRepoExisting(){
1138 $.ajax({
1139 beforeSend: function (xhr) {
1140 if (userB64 != "") { xhr.setRequestHeader ("Authorization", userB64); }
1141 },
1142 type: "GET",
1143 url: "https://api.github.com/repos/"+userName+"/"+githubRepo,
1144 async:false,
1145 dataType:'json',
1146 success: function(){ repoExist = true; },
1147 error: function()
1148 {
1149 displayMessage('Repo not found !', 35, 45);
1150 repoExist = false;
1151 }
1152 });
1153 }
1154
1155 // Check if the branch already exist
1156 function isBranchExisting(){
1157 $.ajax({
1158 beforeSend: function (xhr) {
1159 if (userB64 != "") { xhr.setRequestHeader ("Authorization", userB64); }
1160 },
1161 type: "GET",
1162 url: "https://api.github.com/repos/"+userName+"/"+githubRepo+"/git/refs/heads/"+branchName,
1163 async:false,
1164 dataType:'json',
1165 success: function(){ branchExist = true; },
1166 error: function()
1167 {
1168 branchExist = false;
1169 editComment -= 1;
1170 $('#modal').hide();
1171 $('#txtQuestion').text("Are you sure you want to create that branch ?");
1172 $('#btnCancelBranch').show();
1173 $('#btnCreateBranch').text("Yes");
1174 $('#modalQuestion').show();
1175 $('#modalQuestion').show().prepend('<a class="close"><img src="resources/icons/close.png" class="btnCloseQuestion" title="Close" alt="Close" /></a>');
1176 $('body').append('<div id="fade"></div>');
1177 $('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn();
1178 }
1179 });
1180 }
1181
1182 function getMasterSha()
1183 {
1184 $.ajax({
1185 beforeSend: function (xhr) {
1186 if (userB64 != ""){ xhr.setRequestHeader ("Authorization", userB64); }
1187 },
1188 type: "GET",
1189 url: "https://api.github.com/repos/"+userName+"/"+githubRepo+"/git/refs/heads/master",
1190 dataType:"json",
1191 async: false,
1192 success: function(success) { shaMaster = success.object.sha; }
1193 });
1194 }
1195
1196 function createBranch(){
1197
1198 getMasterSha();
1199
1200 $.ajax({
1201 beforeSend: function (xhr) { xhr.setRequestHeader ("Authorization", userB64); },
1202 type: "POST",
1203 url: "https://api.github.com/repos/"+userName+"/"+githubRepo+"/git/refs",
1204 data:'{ "ref" : "refs/heads/'+branchName+'",'+
1205 '"sha" : "'+shaMaster+'"'+
1206 '}',
1207 success: function(){ return; },
1208 error: function(){
1209 editComment -= 1;
1210 displayMessage('Impossible to create the new branch : ' + branchName, 40, 40);
1211 }
1212 });
1213 }
1214
1215 $.fn.spin = function(opts) {
1216 this.each(function() {
1217 var $this = $(this),
1218 data = $this.data();
1219
1220 if (data.spinner) {
1221 data.spinner.stop();
1222 delete data.spinner;
1223 }
1224 if (opts !== false) {
1225 data.spinner = new Spinner($.extend({color: $this.css('color')}, opts)).spin(this);
1226 }
1227 });
1228 return this;
1229 };
1230
1231 function reloadComment(){
1232 $.when(getCommentLastCommit($('pre[class=text_label]').attr('tag'))).done(function(){
1233 $('pre[class=text_label]').each(function(){ getCommentOfFunction($(this)); });
1234 });
1235 }
1236
1237 function getCommentOfFunction(element){
1238 var textC = "";
1239 var numL = element.attr("title");
1240 if(numL != null){
1241 commentLineStart = numL.split('-')[0] - 1;
1242 commentLineEnd = (commentLineStart + element.text().split('\n').length) - 1;
1243 var lines = currentfileContent.split("\n");
1244 for (var i = 0; i < lines.length; i++) {
1245 if(i >= commentLineStart-1 && i <= commentLineEnd){
1246 if (lines[i].substr(1,1) == "#"){ textC += lines[i].substr(3,lines[i].length) + "\n";}
1247 else if(lines[i].substr(0,1) == '#'){ textC += lines[i].substr(2,lines[i].length) + "\n"; }
1248 }
1249 }
1250 if (textC != ""){ element.text(textC); }
1251 }
1252 }
1253
1254 // Get list of branches
1255 function getListBranches()
1256 {
1257 cleanListBranches();
1258 $.ajax({
1259 beforeSend: function (xhr) {
1260 if ($("#login").val() != ""){ xhr.setRequestHeader ("Authorization", userB64); }
1261 },
1262 type: "GET",
1263 url: "https://api.github.com/repos/"+userName+"/"+githubRepo+"/branches",
1264 async:false,
1265 dataType:'json',
1266 success: function(success)
1267 {
1268 for(var branch in success) {
1269 var selected = '';
1270 if(branchName == success[branch].name){
1271 selected = 'selected';
1272 }
1273 $('#dropBranches').append('<option value="" '+ selected +'>' + success[branch].name + '</option>');
1274 }
1275 }
1276 });
1277 }
1278
1279 // Delete all option in the list
1280 function cleanListBranches(){
1281 $('#dropBranches').children("option").remove();
1282 }
1283
1284 function closeAllCommentInEdtiting(){
1285 $('a[id=cancelBtn]').each(function(){
1286 closeEditing($(this));
1287 });
1288 }
1289
1290 function closeEditing(tag){
1291 if(editComment > 0){ editComment -= 1; }
1292 // Hide itself
1293 tag.hide();
1294 // Hide commitBtn
1295 tag.next().hide();
1296 // Hide Textarea
1297 tag.prev().hide();
1298 // Show comment
1299 tag.prev().prev().show();
1300 }