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