nitdoc: Adding a way to switch of branch
[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 }
444 displayLogginModal();
445 });
446
447 // Activate edit mode
448 $('pre[class=text_label]').click(function(){
449 // the customer is loggued ?
450 if(!sessionStarted || userName == ""){
451 // No => nothing happen
452 return;
453 }
454 else{
455 var arrayNew = $(this).text().split('\n');
456 var lNew = arrayNew.length - 1;
457 var adapt = "";
458
459 for (var i = 0; i < lNew; i++) {
460 adapt += arrayNew[i];
461 if(i < lNew-1){ adapt += "\n"; }
462 }
463 editComment += 1;
464 // hide comment
465 $(this).hide();
466 // Show edit box
467 $(this).next().show();
468 // Show cancel button
469 $(this).next().next().show();
470 // Show commit button
471 $(this).next().next().next().show();
472 // Add text in edit box
473 if($(this).next().val() == "" || $(this).next().val() != adapt){ $(this).next().val(adapt); }
474 // Resize edit box
475 $(this).next().height($(this).next().prop("scrollHeight"));
476 // Select it
477 $(this).next().select();
478 preElement = $(this);
479 }
480 });
481
482 // Disable the edit mode
483 $('a[id=cancelBtn]').click(function(){
484 if(editComment > 0){ editComment -= 1; }
485 // Hide itself
486 $(this).hide();
487 // Hide commitBtn
488 $(this).next().hide();
489 // Hide Textarea
490 $(this).prev().hide();
491 // Show comment
492 $(this).prev().prev().show();
493 });
494
495 // Display commit form
496 $('a[id=commitBtn]').click(function(){
497 updateComment = $(this).prev().prev().val();
498 commentType = $(this).prev().prev().prev().attr('type');
499
500 if(updateComment == ""){ displayMessage('The comment field is empty!', 40, 45); }
501 else{
502 if(!sessionStarted){
503 displayMessage("You need to be loggued before commit something", 45, 40);
504 displayLogginModal();
505 return;
506 }
507 $('#commitMessage').val('New commit');
508 pathFile = $(this).prev().prev().prev().attr('tag');
509 $('#modal').show().prepend('<a class="close"><img src="resources/icons/close.png" class="btn_close" title="Close" alt="Close" /></a>');
510 $('body').append('<div id="fade"></div>');
511 $('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn();
512 }
513 });
514
515 // Close commit form
516 $('.btn_close').click(function(){
517 $(this).hide();
518 $(this).next().hide();
519 if(editComment > 0){ editComment -= 1; }
520 });
521
522 //Close Popups and Fade Layer
523 $('body').on('click', 'a.close, #fade', function() {
524 if(editComment > 0){ editComment -= 1; }
525 $('#fade , #modal').fadeOut(function() {
526 $('#fade, a.close').remove();
527 });
528 $('#modalQuestion').hide();
529 });
530
531 $('#loginAction').click(function(){
532 var text;
533 var url;
534 var line;
535 // Look if the customer is logged
536 if(!sessionStarted){
537 displayMessage("You need to be loggued before commit something", 100, 40);
538 $('.popover').show();
539 return;
540 }
541 else{ userB64 = "Basic " + getUserPass("logginNitdoc"); }
542 githubRepo = repoName;
543 // Check if repo exist
544 isRepoExisting();
545 if(repoExist){
546 isBranchExisting();
547 if(branchExist){
548 editComment -= 1;
549 commitMessage = $('#commitMessage').val();
550 if(commitMessage == ""){ commitMessage = "New commit";}
551 if(sessionStarted){
552 if ($.trim(updateComment) == ''){ this.value = (this.defaultValue ? this.defaultValue : ''); }
553 else{
554 displaySpinner();
555 startCommitProcess();
556 }
557 }
558 $('#modal, #modalQuestion').fadeOut(function() {
559 $('#login').val("");
560 $('#password').val("");
561 $('textarea').hide();
562 $('textarea').prev().show();
563 });
564 $('a[id=cancelBtn]').hide();
565 $('a[id=commitBtn]').hide();
566 // Re-load all comment
567 reloadComment();
568 }
569 }
570 else{ editComment -= 1; }
571 });
572
573 // Cancel creating branch
574 $('#btnCancelBranch').click(function(){
575 editComment -= 1;
576 $('#modalQuestion').hide();
577 $('#fade , #modal').fadeOut(function() { $('#fade, a.close').remove(); });
578 return;
579 });
580
581 // Create new branch and continu
582 $('#btnCreateBranch').click(function(){
583 $('#modalQuestion').hide();
584 if($('#btnCreateBranch').text() != 'Ok'){
585 // Create the branch
586 createBranch();
587 commitMessage = $('#commitMessage').val();
588 if(commitMessage == ""){ commitMessage = "New commit"; }
589 if(userB64 != ""){
590 if ($.trim(updateComment) == ''){ this.value = (this.defaultValue ? this.defaultValue : ''); }
591 else{ startCommitProcess(); }
592 }
593 }
594 else
595 {
596 $('#fade , #modalQuestion, #modal').fadeOut(function() { $('#fade, a.close').remove(); });
597 }
598 });
599
600 $('a[class=newComment]').click(function(){
601 addNewComment = true;
602 editComment += 1;
603 // hide comment
604 $(this).hide();
605 // Show edit box
606 $(this).next().show();
607 // Show cancel button
608 $(this).next().next().show();
609 // Show commit button
610 $(this).next().next().next().show();
611 // Resize edit box
612 $(this).next().height($(this).next().prop("scrollHeight"));
613 // Select it
614 $(this).next().select();
615 preElement = $(this);
616 });
617
618 $("#dropBranches").change(function () {
619 $("#dropBranches option:selected").each(function () {
620 if(branchName != $(this).text()){
621 branchName = $(this).text();
622 }
623 });
624 $.when(updateCookie(userName, password, repoName, branchName)).done(function(){
625 reloadComment();
626 });
627 });
628 });
629
630 /* Parse current URL and return anchor name */
631 function currentAnchor() {
632 var index = document.location.hash.indexOf("#");
633 if (index >= 0) {
634 return document.location.hash.substring(index + 1);
635 }
636 return null;
637 }
638
639 /* Prealod filters field using search query */
640 function preloadFilters() {
641 // Parse URL and get query string
642 var search = currentAnchor();
643
644 if(search == null || search.indexOf("q=") == -1)
645 return;
646
647 search = search.substring(2, search.length);
648
649 if(search == "" || search == "undefined")
650 return;
651
652 $(":text").val(search);
653 $(".filter :text")
654 .removeClass("notUsed")
655 .trigger("keyup");
656
657 }
658
659 /* Hightlight the spoted block */
660 function highlightBlock(a) {
661 if(a == undefined) {
662 return;
663 }
664
665 $(".highlighted").removeClass("highlighted");
666
667 var target = $("#" + a);
668
669 if(target.is("article")) {
670 target.parent().addClass("highlighted");
671 }
672
673 target.addClass("highlighted");
674 target.show();
675 }
676
677 // Init process to commit the new comment
678 function startCommitProcess()
679 {
680 var numL = preElement.attr("title");
681 commentLineStart = numL.split('-')[0] - 1;
682 if(addNewComment) { commentLineStart++; }
683 commentLineEnd = (commentLineStart + preElement.text().split('\n').length) - 1;
684 state = true;
685 replaceComment(updateComment, currentfileContent);
686 getLastCommit();
687 getBaseTree();
688 editComment = false;
689 }
690
691 function displayLogginModal(){
692 if ($('.popover').is(':hidden')) {
693 if(sessionStarted){ getListBranches(); }
694 $('.popover').show();
695 }
696 else { $('.popover').hide(); }
697 updateDisplaying();
698 }
699
700 function updateDisplaying(){
701 if (checkCookie())
702 {
703 userB64 = "Basic " + getUserPass("logginNitdoc");
704 $('#loginGit').hide();
705 $('#passwordGit').hide();
706 $('#lbpasswordGit').hide();
707 $('#lbloginGit').hide();
708 $('#repositoryGit').hide();
709 $('#lbrepositoryGit').hide();
710 $('#lbbranchGit').hide();
711 $('#branchGit').hide();
712 $('#listBranches').show();
713 $("#liGitHub").attr("class", "current");
714 $("#imgGitHub").attr("src", "resources/icons/github-icon-w.png");
715 $('#nickName').text(userName);
716 $('#githubAccount').attr("href", "https://github.com/"+userName);
717 $('#logginMessage').css({'display' : 'block'});
718 $('#logginMessage').css({'text-align' : 'center'});
719 $('.popover').css({'height' : '120px'});
720 $('#signIn').text("Sign out");
721 sessionStarted = true;
722 reloadComment();
723 }
724 else
725 {
726 sessionStarted = false;
727 $('#logginMessage').css({'display' : 'none'});
728 $("#liGitHub").attr("class", "");
729 $("#imgGitHub").attr("src", "resources/icons/github-icon.png");
730 $('#loginGit').val("");
731 $('#passwordGit').val("");
732 $('#nickName').text("");
733 $('.popover').css({'height' : '280px'});
734 $('#logginMessage').css({'display' : 'none'});
735 $('#repositoryGit').val($('#repoName').attr('name'));
736 $('#branchGit').val('wikidoc');
737 $('#signIn').text("Sign In");
738 $('#loginGit').show();
739 $('#passwordGit').show();
740 $('#lbpasswordGit').show();
741 $('#lbloginGit').show();
742 $('#repositoryGit').show();
743 $('#lbrepositoryGit').show();
744 $('#lbbranchGit').show();
745 $('#branchGit').show();
746 $('#listBranches').hide();
747 }
748 }
749
750 function setCookie(c_name, value, exdays)
751 {
752 var exdate=new Date();
753 exdate.setDate(exdate.getDate() + exdays);
754 var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
755 document.cookie=c_name + "=" + c_value;
756 }
757
758 function del_cookie(c_name)
759 {
760 document.cookie = c_name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
761 }
762
763 function updateCookie(user, pwd, repo, branch){
764 if(checkCookie()){
765 branchName = branch;
766 setCookie("logginNitdoc", base64.encode(user+':'+pwd+':'+repo+':'+branch), 1);
767 }
768 }
769
770 function getCookie(c_name)
771 {
772 var c_value = document.cookie;
773 var c_start = c_value.indexOf(" " + c_name + "=");
774 if (c_start == -1) { c_start = c_value.indexOf(c_name + "="); }
775 if (c_start == -1) { c_value = null; }
776 else
777 {
778 c_start = c_value.indexOf("=", c_start) + 1;
779 var c_end = c_value.indexOf(";", c_start);
780 if (c_end == -1) { c_end = c_value.length; }
781 c_value = unescape(c_value.substring(c_start,c_end));
782 }
783 return c_value;
784 }
785
786 function getUserPass(c_name){
787 var cookie = base64.decode(getCookie(c_name));
788 return base64.encode(cookie.split(':')[0] + ':' + cookie.split(':')[1]);
789 }
790
791 function checkCookie()
792 {
793 var cookie=getCookie("logginNitdoc");
794 if (cookie!=null && cookie!="")
795 {
796 cookie = base64.decode(cookie);
797 userName = cookie.split(':')[0];
798 password = cookie.split(':')[1];
799 repoName = cookie.split(':')[2];
800 branchName = cookie.split(':')[3];
801 return true;
802 }
803 else { return false; }
804 }
805
806
807 /*
808 * Base64
809 */
810 base64 = {};
811 base64.PADCHAR = '=';
812 base64.ALPHA = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
813 base64.getbyte64 = function(s,i) {
814 // This is oddly fast, except on Chrome/V8.
815 // Minimal or no improvement in performance by using a
816 // object with properties mapping chars to value (eg. 'A': 0)
817 var idx = base64.ALPHA.indexOf(s.charAt(i));
818 if (idx == -1) {
819 throw "Cannot decode base64";
820 }
821 return idx;
822 }
823
824 base64.decode = function(s) {
825 // convert to string
826 s = "" + s;
827 var getbyte64 = base64.getbyte64;
828 var pads, i, b10;
829 var imax = s.length
830 if (imax == 0) {
831 return s;
832 }
833
834 if (imax % 4 != 0) {
835 throw "Cannot decode base64";
836 }
837
838 pads = 0
839 if (s.charAt(imax -1) == base64.PADCHAR) {
840 pads = 1;
841 if (s.charAt(imax -2) == base64.PADCHAR) {
842 pads = 2;
843 }
844 // either way, we want to ignore this last block
845 imax -= 4;
846 }
847
848 var x = [];
849 for (i = 0; i < imax; i += 4) {
850 b10 = (getbyte64(s,i) << 18) | (getbyte64(s,i+1) << 12) |
851 (getbyte64(s,i+2) << 6) | getbyte64(s,i+3);
852 x.push(String.fromCharCode(b10 >> 16, (b10 >> 8) & 0xff, b10 & 0xff));
853 }
854
855 switch (pads) {
856 case 1:
857 b10 = (getbyte64(s,i) << 18) | (getbyte64(s,i+1) << 12) | (getbyte64(s,i+2) << 6)
858 x.push(String.fromCharCode(b10 >> 16, (b10 >> 8) & 0xff));
859 break;
860 case 2:
861 b10 = (getbyte64(s,i) << 18) | (getbyte64(s,i+1) << 12);
862 x.push(String.fromCharCode(b10 >> 16));
863 break;
864 }
865 return x.join('');
866 }
867
868 base64.getbyte = function(s,i) {
869 var x = s.charCodeAt(i);
870 if (x > 255) {
871 throw "INVALID_CHARACTER_ERR: DOM Exception 5";
872 }
873 return x;
874 }
875
876
877 base64.encode = function(s) {
878 if (arguments.length != 1) {
879 throw "SyntaxError: Not enough arguments";
880 }
881 var padchar = base64.PADCHAR;
882 var alpha = base64.ALPHA;
883 var getbyte = base64.getbyte;
884
885 var i, b10;
886 var x = [];
887
888 // convert to string
889 s = "" + s;
890
891 var imax = s.length - s.length % 3;
892
893 if (s.length == 0) {
894 return s;
895 }
896 for (i = 0; i < imax; i += 3) {
897 b10 = (getbyte(s,i) << 16) | (getbyte(s,i+1) << 8) | getbyte(s,i+2);
898 x.push(alpha.charAt(b10 >> 18));
899 x.push(alpha.charAt((b10 >> 12) & 0x3F));
900 x.push(alpha.charAt((b10 >> 6) & 0x3f));
901 x.push(alpha.charAt(b10 & 0x3f));
902 }
903 switch (s.length - imax) {
904 case 1:
905 b10 = getbyte(s,i) << 16;
906 x.push(alpha.charAt(b10 >> 18) + alpha.charAt((b10 >> 12) & 0x3F) +
907 padchar + padchar);
908 break;
909 case 2:
910 b10 = (getbyte(s,i) << 16) | (getbyte(s,i+1) << 8);
911 x.push(alpha.charAt(b10 >> 18) + alpha.charAt((b10 >> 12) & 0x3F) +
912 alpha.charAt((b10 >> 6) & 0x3f) + padchar);
913 break;
914 }
915 return x.join('');
916 }
917
918
919
920 function getLastCommit()
921 {
922 var urlHead = '';
923 if(sessionStarted){ urlHead = "https://api.github.com/repos/"+userName+"/"+githubRepo+"/git/refs/heads/"+branchName;}
924 else{
925 // TODO: get url of the original repo.
926 return;
927 }
928
929 $.ajax({
930 beforeSend: function (xhr) {
931 if (userB64 != ""){ xhr.setRequestHeader ("Authorization", userB64); }
932 },
933 type: "GET",
934 url: urlHead,
935 dataType:"json",
936 async: false,
937 success: function(success)
938 {
939 shaLastCommit = success.object.sha;
940 }
941 });
942 }
943
944 function getBaseTree()
945 {
946 $.ajax({
947 beforeSend: function (xhr) {
948 if (userB64 != ""){ xhr.setRequestHeader ("Authorization", userB64); }
949 },
950 type: "GET",
951 url: "https://api.github.com/repos/"+userName+"/"+githubRepo+"/git/commits/" + shaLastCommit,
952 dataType:"json",
953 async: false,
954 success: function(success)
955 {
956 shaBaseTree = success.tree.sha;
957 if (state){ setBlob(); }
958 else{ return; }
959 },
960 error: function(){
961 return;
962 }
963 });
964 }
965
966 function setNewTree()
967 {
968 $.ajax({
969 beforeSend: function (xhr) { xhr.setRequestHeader ("Authorization", userB64); },
970 type: "POST",
971 url: "https://api.github.com/repos/"+userName+"/"+githubRepo+"/git/trees",
972 async: false,
973 data:'{ "base_tree" : "'+shaBaseTree+'", '+
974 '"tree":[{ '+
975 '"path":"'+ pathFile +'",'+
976 '"mode":"100644",'+
977 '"type":"blob",'+
978 '"sha": "'+ shaBlob +'"'+
979 '}] '+
980 '}',
981 success: function(success)
982 { // si l'appel a bien fonctionné
983 shaNewTree = JSON.parse(success).sha;
984 setNewCommit();
985 },
986 error: function(){
987 return;
988 }
989 });
990 }
991
992 function setNewCommit()
993 {
994 $.ajax({
995 beforeSend: function (xhr) { xhr.setRequestHeader ("Authorization", userB64); },
996 type: "POST",
997 url: "https://api.github.com/repos/"+userName+"/"+githubRepo+"/git/commits",
998 async: false,
999 data:'{ "message" : "'+ commitMessage +'", '+
1000 '"parents" :"'+shaLastCommit+'",'+
1001 '"tree": "'+shaNewTree+'"'+
1002 '}',
1003 success: function(success)
1004 {
1005 shaNewCommit = JSON.parse(success).sha;
1006 commit();
1007 },
1008 error: function(){
1009 return;
1010 }
1011 });
1012 }
1013
1014 //Create a commit
1015 function commit()
1016 {
1017 $.ajax({
1018 beforeSend: function (xhr) { xhr.setRequestHeader ("Authorization", userB64); },
1019 type: "POST",
1020 url: "https://api.github.com/repos/"+userName+"/"+githubRepo+"/git/refs/heads/"+branchName,
1021 data:'{ "sha" : "'+shaNewCommit+'", '+
1022 '"force" :"true"'+
1023 '}',
1024 success: function(success) { displayMessage('Commit created successfully', 40, 40); },
1025 error:function(error){ displayMessage('Error ' + JSON.parse(error).object.message, 40, 40); }
1026 });
1027 }
1028
1029 // Create a blob
1030 function setBlob()
1031 {
1032 $.ajax({
1033 beforeSend: function (xhr) { xhr.setRequestHeader ("Authorization", userB64); },
1034 type: "POST",
1035 url: "https://api.github.com/repos/"+userName+"/"+githubRepo+"/git/blobs",
1036 async: false,
1037 data:'{ "content" : "'+text.replace(/\r?\n/g, '\\n').replace(/\t/g, '\\t').replace(/\"/g,'\\"')+'", '+
1038 '"encoding" :"utf-8"'+
1039 '}',
1040 success: function(success)
1041 {
1042 shaBlob = JSON.parse(success).sha;
1043 setNewTree();
1044 },
1045 error:function(error){
1046 displayMessage('Error : Problem parsing JSON', 40, 40);
1047 return;
1048 }
1049 });
1050 }
1051
1052 // Display file content
1053 function getFileContent(urlFile, newComment)
1054 {
1055 $.ajax({
1056 beforeSend: function (xhr) {
1057 xhr.setRequestHeader ("Accept", "application/vnd.github-blob.raw");
1058 if (userB64 != ""){ xhr.setRequestHeader ("Authorization", userB64); }
1059 },
1060 type: "GET",
1061 url: urlFile,
1062 async:false,
1063 success: function(success)
1064 {
1065 state = true;
1066 replaceComment(newComment, success);
1067 }
1068 });
1069 }
1070
1071 function replaceComment(newComment, fileContent){
1072 var arrayNew = newComment.split('\n');
1073 var lNew = arrayNew.length;
1074 text = "";
1075 var lines = fileContent.split("\n");
1076 for (var i = 0; i < lines.length; i++) {
1077 if(i == commentLineStart){
1078 if(addNewComment){
1079 for(var indexLine=0; indexLine < lines[i+1].length; indexxLine++){
1080 if(lines[i+1].substr(indexLine,1) == "\t" || lines[i+1].substr(indexLine,1) == "#"){ text += lines[i+1].substr(indexLine,1); }
1081 else{ break;}
1082 }
1083 text += lines[i] + "\n";
1084 }
1085 // We change the comment
1086 for(var j = 0; j < lNew; j++){
1087 if(commentType == 1){ text += "\t# " + arrayNew[j] + "\n"; }
1088 else{
1089 if(arrayNew[j] == ""){ text += "#"+"\n"; }
1090 else{ text += "# " + arrayNew[j] + "\n"; }
1091 }
1092 }
1093 }
1094 else if(i < commentLineStart || i >= commentLineEnd){
1095 if(i == lines.length-1){ text += lines[i]; }
1096 else{ text += lines[i] + "\n"; }
1097 }
1098 }
1099 if(addNewComment){
1100 addNewComment = false;
1101 }
1102 }
1103
1104 function getCommentLastCommit(path){
1105 var urlRaw;
1106 getLastCommit();
1107 if(shaLastCommit != ""){
1108 if (checkCookie()) { urlRaw="https://rawgithub.com/"+ userName +"/"+ repoName +"/" + shaLastCommit + "/" + path; }
1109 else{ urlRaw="https://rawgithub.com/StefanLage/"+ $('#repoName').attr('name') +"/" + shaLastCommit + "/" + path; }
1110
1111 $.ajax({
1112 type: "GET",
1113 url: urlRaw,
1114 async: false,
1115 success: function(success)
1116 {
1117 currentfileContent = success;
1118 }
1119 });
1120 }
1121 }
1122
1123 function displayMessage(msg, widthDiv, margModal){
1124 spinner.stop();
1125 $('#modal').hide();
1126 $('#btnCreateBranch').css('margin-left',widthDiv + '%');
1127 $('#txtQuestion').text(msg);
1128 $('#btnCreateBranch').text("Ok");
1129 $('#btnCancelBranch').hide();
1130 $('#modalQuestion').css({'left' : margModal + '%'})
1131 $('#modalQuestion').show();
1132 $('#modalQuestion').show().prepend('<a class="close"><img src="resources/icons/close.png" class="btnCloseQuestion" title="Close" alt="Close" /></a>');
1133 $('body').append('<div id="fade"></div>');
1134 $('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn();
1135 }
1136
1137 function displaySpinner(){
1138 spinner.spin(targetSpinner);
1139 $("#waitCommit").show();
1140 }
1141
1142 // Check if the repo already exist
1143 function isRepoExisting(){
1144 $.ajax({
1145 beforeSend: function (xhr) {
1146 if (userB64 != "") { xhr.setRequestHeader ("Authorization", userB64); }
1147 },
1148 type: "GET",
1149 url: "https://api.github.com/repos/"+userName+"/"+githubRepo,
1150 async:false,
1151 dataType:'json',
1152 success: function(){ repoExist = true; },
1153 error: function()
1154 {
1155 displayMessage('Repo not found !', 35, 45);
1156 repoExist = false;
1157 }
1158 });
1159 }
1160
1161 // Check if the branch already exist
1162 function isBranchExisting(){
1163 $.ajax({
1164 beforeSend: function (xhr) {
1165 if (userB64 != "") { xhr.setRequestHeader ("Authorization", userB64); }
1166 },
1167 type: "GET",
1168 url: "https://api.github.com/repos/"+userName+"/"+githubRepo+"/git/refs/heads/"+branchName,
1169 async:false,
1170 dataType:'json',
1171 success: function(){ branchExist = true; },
1172 error: function()
1173 {
1174 branchExist = false;
1175 editComment -= 1;
1176 $('#modal').hide();
1177 $('#txtQuestion').text("Are you sure you want to create that branch ?");
1178 $('#btnCancelBranch').show();
1179 $('#btnCreateBranch').text("Yes");
1180 $('#modalQuestion').show();
1181 $('#modalQuestion').show().prepend('<a class="close"><img src="resources/icons/close.png" class="btnCloseQuestion" title="Close" alt="Close" /></a>');
1182 $('body').append('<div id="fade"></div>');
1183 $('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn();
1184 }
1185 });
1186 }
1187
1188 function getMasterSha()
1189 {
1190 $.ajax({
1191 beforeSend: function (xhr) {
1192 if (userB64 != ""){ xhr.setRequestHeader ("Authorization", userB64); }
1193 },
1194 type: "GET",
1195 url: "https://api.github.com/repos/"+userName+"/"+githubRepo+"/git/refs/heads/master",
1196 dataType:"json",
1197 async: false,
1198 success: function(success) { shaMaster = success.object.sha; }
1199 });
1200 }
1201
1202 function createBranch(){
1203
1204 getMasterSha();
1205
1206 $.ajax({
1207 beforeSend: function (xhr) { xhr.setRequestHeader ("Authorization", userB64); },
1208 type: "POST",
1209 url: "https://api.github.com/repos/"+userName+"/"+githubRepo+"/git/refs",
1210 data:'{ "ref" : "refs/heads/'+branchName+'",'+
1211 '"sha" : "'+shaMaster+'"'+
1212 '}',
1213 success: function(){ return; },
1214 error: function(){
1215 editComment -= 1;
1216 displayMessage('Impossible to create the new branch : ' + branchName, 40, 40);
1217 }
1218 });
1219 }
1220
1221 $.fn.spin = function(opts) {
1222 this.each(function() {
1223 var $this = $(this),
1224 data = $this.data();
1225
1226 if (data.spinner) {
1227 data.spinner.stop();
1228 delete data.spinner;
1229 }
1230 if (opts !== false) {
1231 data.spinner = new Spinner($.extend({color: $this.css('color')}, opts)).spin(this);
1232 }
1233 });
1234 return this;
1235 };
1236
1237 function reloadComment(){
1238 $.when(getCommentLastCommit($('pre[class=text_label]').attr('tag'))).done(function(){
1239 $('pre[class=text_label]').each(function(){ getCommentOfFunction($(this)); });
1240 });
1241 }
1242
1243 function getCommentOfFunction(element){
1244 var textC = "";
1245 var numL = element.attr("title");
1246 if(numL != null){
1247 commentLineStart = numL.split('-')[0] - 1;
1248 commentLineEnd = (commentLineStart + element.text().split('\n').length) - 1;
1249 var lines = currentfileContent.split("\n");
1250 for (var i = 0; i < lines.length; i++) {
1251 if(i >= commentLineStart-1 && i <= commentLineEnd){
1252 if (lines[i].substr(1,1) == "#"){ textC += lines[i].substr(3,lines[i].length) + "\n";}
1253 else if(lines[i].substr(0,1) == '#'){ textC += lines[i].substr(2,lines[i].length) + "\n"; }
1254 }
1255 }
1256 if (textC != ""){ element.text(textC); }
1257 }
1258 }
1259
1260 // Get list of branches
1261 function getListBranches()
1262 {
1263 cleanListBranches();
1264 $.ajax({
1265 beforeSend: function (xhr) {
1266 if ($("#login").val() != ""){ xhr.setRequestHeader ("Authorization", userB64); }
1267 },
1268 type: "GET",
1269 url: "https://api.github.com/repos/"+userName+"/"+githubRepo+"/branches",
1270 async:false,
1271 dataType:'json',
1272 success: function(success)
1273 {
1274 for(var branch in success) {
1275 var selected = '';
1276 if(branchName == success[branch].name){
1277 selected = 'selected';
1278 }
1279 $('#dropBranches').append('<option value="" '+ selected +'>' + success[branch].name + '</option>');
1280 }
1281 }
1282 });
1283 }
1284
1285 // Delete all option in the list
1286 function cleanListBranches(){
1287 $('#dropBranches').children("option").remove();
1288 }