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