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