ni_nitdoc: github login box is now generated by JS
[nit.git] / share / nitdoc / scripts / github.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 originalFileContent = '';
9 var addNewComment = false;
10 var commentLineStart;
11 var commentLineEnd;
12
13 // SHA GitHub
14 var shaLastCommit = "";
15 var shaBaseTree;
16 var shaNewTree;
17 var shaNewCommit;
18 var shaBlob;
19 var shaMaster;
20 var repoExist = false;
21 var branchExist = false;
22 var githubRepo;
23 var loginProcess = false;
24 var signedOff = '';
25 var userEmail = '';
26 var commitMessage = '';
27 var numComment = '';
28 var showcomment = false;
29
30 // Spinner vars
31 var opts = {
32 lines: 11, // The number of lines to draw
33 length: 7, // The length of each line
34 width: 4, // The line thickness
35 radius: 10, // The radius of the inner circle
36 corners: 1, // Corner roundness (0..1)
37 rotate: 0, // The rotation offset
38 color: '#FFF', // #rgb or #rrggbb
39 speed: 1, // Rounds per second
40 trail: 60, // Afterglow percentage
41 shadow: false, // Whether to render a shadow
42 hwaccel: false, // Whether to use hardware acceleration
43 className: 'spinner', // The CSS class to assign to the spinner
44 zIndex: 99999, // The z-index (defaults to 2000000000)
45 top: '300', // Top position relative to parent in px
46 left: 'auto' // Left position relative to parent in px
47 };
48 var targetSpinner = document.getElementById('waitCommit');
49 var spinner = new Spinner(opts).spin(targetSpinner);
50
51 // Check if a comment is editing
52 window.onbeforeunload = function() {
53 if(editComment > 0){
54 return 'Are you sure you want to leave this page?';
55 }
56 };
57
58 $(document).ready(function() {
59 createLoginBox();
60 // Hide edit tags
61 $('textarea').hide();
62 $('a[id=commitBtn]').hide();
63 $('a[id=cancelBtn]').hide();
64 // Display Login modal
65 $("#logGitHub").click(function(){ toggleLoginBox(); });
66 // Update display
67 updateDisplaying();
68 // If cookie existing the session is opened
69 if(sessionStarted){ userB64 = "Basic " + getUserPass("logginNitdoc"); }
70
71 // Sign In an github user or Log out him
72 $("#signIn").click(function(){
73 if(!sessionStarted){
74 if($('#loginGit').val() == "" || $('#passwordGit').val() == ""){ displayMessage('Please informed login/password field!', 40, 45); }
75 else
76 {
77 userName = $('#loginGit').val();
78 password = $('#passwordGit').val();
79 githubRepo = $('#repositoryGit').val();
80 branchName = $('#branchGit').val();
81 userB64 = "Basic " + base64.encode(userName+':'+password);
82 if(checkSignIn()){
83 // Check if repo exist
84 isRepoExisting();
85 if(repoExist){
86 $.when(isBranchExisting()).done(function(){
87 loginProcess = true;
88 if(branchExist){
89 setCookie("logginNitdoc", base64.encode(userName+':'+password+':'+githubRepo+':'+branchName), 1);
90 $('#loginGit').val("");
91 $('#passwordGit').val("");
92 reloadComment();
93 }
94 });
95 }
96 }
97 }
98 }
99 else
100 {
101 // Delete cookie and reset settings
102 del_cookie("logginNitdoc");
103 closeAllCommentInEdtiting();
104 }
105 toggleLoginBox();
106 });
107
108 // Activate edit mode
109 $('pre[class=text_label]').click(function(){
110 // the customer is loggued ?
111 if(!sessionStarted || userName == ""){
112 // No => nothing happen
113 return;
114 }
115 else{
116 numComment = $(this).attr('title');
117 var arrayNew = $(this).text().split('\n');
118 var lNew = arrayNew.length - 1;
119 var adapt = "";
120
121 for (var i = 0; i < lNew; i++) {
122 adapt += arrayNew[i];
123 if(i < lNew-1){ adapt += "\n"; }
124 }
125 editComment += 1;
126 getCommentOfFunction($(this));
127 // hide comment
128 $(this).hide();
129 // Show edit box
130 $(this).next().show();
131 // Show cancel button
132 $(this).next().next().show();
133 // Show commit button
134 $(this).next().next().next().show();
135 // Add text in edit box
136 if($(this).next().val() == "" || $(this).next().val() != adapt){ $(this).next().val(adapt); }
137 // Resize edit box
138 $(this).next().height($(this).next().prop("scrollHeight"));
139 resizeTextarea($(this).next());
140 // Select it
141 $(this).next().select();
142 preElement = $(this);
143 }
144 });
145
146 // Disable the edit mode
147 $('a[id=cancelBtn]').click(function(){
148 $(this).parent().prev().children('#lblDiffCommit').text("");
149 showcomment = false;
150 closeEditing($(this));
151 });
152
153 // Display commit form
154 $('a[id=commitBtn]').click(function(){
155 updateComment = $(this).prev().prev().val();
156 commentType = $(this).prev().prev().prev().attr('type');
157
158 if(updateComment == ""){ displayMessage('The comment field is empty!', 40, 45); }
159 else{
160 if(!sessionStarted){
161 displayMessage("You need to be loggued before commit something", 45, 40);
162 toggleLoginBox();
163 return;
164 }
165
166 // Create the commit message
167 commitMessage = 'Wikidoc: modified comment in ' + $(this).parent().prev().prev().html().split(' ')[1];
168 $('#commitMessage').text(commitMessage);
169 $('#commitMessage').css({'display': 'block'});
170 pathFile = $(this).prev().prev().prev().attr('tag');
171 $('#modal').show().prepend('<a class="close"><img src="resources/icons/close.png" class="btn_close" title="Close" alt="Close" /></a>');
172 $('body').append('<div id="fade"></div>');
173 $('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn();
174 }
175 });
176
177 // Close commit form
178 $('.btn_close').click(function(){
179 $(this).hide();
180 $(this).next().hide();
181 if(editComment > 0){ editComment -= 1; }
182 $('#chkSignedOff').attr('checked', false);
183 removeSignedOff();
184 });
185
186 //Close Popups and Fade Layer
187 $('body').on('click', 'a.close, #fade', function() {
188 if(editComment > 0){ editComment -= 1; }
189 $('#fade , #modal').fadeOut(function() {
190 $('#fade, a.close').remove();
191 });
192 $('#modalQuestion').hide();
193 $('#chkSignedOff').attr('checked', false);
194 removeSignedOff();
195 });
196
197 $('#loginAction').click(function(){
198 var text;
199 var url;
200 var line;
201 // Look if the customer is logged
202 if(!sessionStarted){
203 displayMessage("You need to be loggued before commit something", 100, 40);
204 $('.popover').show();
205 return;
206 }
207 else{ userB64 = "Basic " + getUserPass("logginNitdoc"); }
208 // Check if repo exist
209 isRepoExisting();
210 if(repoExist){
211 isBranchExisting();
212 if(branchExist){
213 editComment -= 1;
214 commitMessage = $('#commitMessage').val().replace(/\r?\n/g, '\\n').replace(/\t/g, '\\t').replace(/\"/g,'\\"');
215 if(commitMessage == ""){ commitMessage = "New commit";}
216 if(sessionStarted){
217 if ($.trim(updateComment) == ''){ this.value = (this.defaultValue ? this.defaultValue : ''); }
218 else{
219 displaySpinner();
220 startCommitProcess();
221 }
222 }
223 $('#modal, #modalQuestion').fadeOut(function() {
224 $('#login').val("");
225 $('#password').val("");
226 $('textarea').hide();
227 $('textarea').prev().show();
228 });
229 $('a[id=cancelBtn]').hide();
230 $('a[id=commitBtn]').hide();
231 $('a[id=lblDiffCommit]').text("");
232 showcomment = false;
233 // Re-load all comment
234 reloadComment();
235 }
236 }
237 else{ editComment -= 1; }
238 $('#chkSignedOff').attr('checked', false);
239 });
240
241 // Cancel creating branch
242 $('#btnCancelBranch').click(function(){
243 editComment -= 1;
244 $('#modalQuestion').hide();
245 $('#fade , #modal').fadeOut(function() { $('#fade, a.close').remove(); });
246 return;
247 });
248
249 // Create new branch and continu
250 $('#btnCreateBranch').click(function(){
251 $('#modalQuestion').hide();
252 if($('#btnCreateBranch').text() != 'Ok'){
253 // Create the branch
254 createBranch();
255 commitMessage = $('#commitMessage').val().replace(/\r?\n/g, '\\n').replace(/\t/g, '\\t').replace(/\"/g,'\\"');
256 if(commitMessage == ""){ commitMessage = "New commit"; }
257 if(userB64 != ""){
258 if(loginProcess){
259 setCookie("logginNitdoc", base64.encode(userName+':'+password+':'+githubRepo+':'+branchName), 1);
260 $('#loginGit').val("");
261 $('#passwordGit').val("");
262 loginProcess = false;
263 toggleLoginBox();
264 }
265 else{
266 if ($.trim(updateComment) == ''){ this.value = (this.defaultValue ? this.defaultValue : ''); }
267 else{ startCommitProcess(); }
268 }
269 }
270 }
271 else
272 {
273 $('#fade , #modalQuestion, #modal').fadeOut(function() { $('#fade, a.close').remove(); });
274 }
275 });
276
277 $('a[class=newComment]').click(function(){
278 addNewComment = true;
279 editComment += 1;
280 // hide comment
281 $(this).hide();
282 // Show edit box
283 $(this).next().show();
284 // Show cancel button
285 $(this).next().next().show();
286 // Show commit button
287 $(this).next().next().next().show();
288 // Resize edit box
289 $(this).next().height($(this).next().prop("scrollHeight"));
290 resizeTextarea($(this).next());
291 // Select it
292 $(this).next().select();
293 preElement = $(this);
294 });
295
296 $("#dropBranches").change(function () {
297 $("#dropBranches option:selected").each(function () {
298 if(branchName != $(this).text()){
299 branchName = $(this).text();
300 }
301 });
302 $.when(updateCookie(userName, password, githubRepo, branchName)).done(function(){
303 closeAllCommentInEdtiting();
304 reloadComment();
305 });
306 });
307
308 $("pre").hover(
309 function () {
310 if(sessionStarted == true){
311 $(this).css({'cursor' : 'hand'});
312 }
313 else{
314 $(this).css({'cursor' : ''});
315 }
316 },
317 function () {
318 if(sessionStarted == true){
319 $(this).css({'cursor' : 'pointer'});
320 }
321 else{
322 $(this).css({'cursor' : ''});
323 }
324 }
325 );
326
327 $('#chkSignedOff').click(function(){
328 if($(this).is(':checked')){ addSignedOff(); }
329 else{ removeSignedOff(); }
330 })
331
332 $('a[id=lblDiffCommit]').click(function(){
333 showComment($(this));
334 });
335 });
336
337 // Init process to commit the new comment
338 function startCommitProcess()
339 {
340 if($('#chkSignedOff').is(':checked')){
341 var numL = preElement.attr("title");
342 commentLineStart = numL.split('-')[0] - 1;
343 if(addNewComment) { commentLineStart++; }
344 commentLineEnd = (commentLineStart + preElement.text().split('\n').length) - 1;
345 state = true;
346 replaceComment(updateComment, currentfileContent);
347 getLastCommit();
348 getBaseTree();
349 editComment = false;
350 }
351 else{
352 displayMessage('Please sign this commit', 40, 40);
353 }
354 }
355
356 function updateDisplaying(){
357 if (checkCookie())
358 {
359 userB64 = "Basic " + getUserPass("logginNitdoc");
360 $('#loginGit').hide();
361 $('#passwordGit').hide();
362 $('#lbpasswordGit').hide();
363 $('#lbloginGit').hide();
364 $('#repositoryGit').hide();
365 $('#lbrepositoryGit').hide();
366 $('#lbbranchGit').hide();
367 $('#branchGit').hide();
368 $('#listBranches').show();
369 $('#divGitHubRepoDisplay').show();
370 $("#liGitHub").attr("class", "current");
371 $("#imgGitHub").attr("src", "resources/icons/github-icon-w.png");
372 $('#nickName').text(userName);
373 $('#githubAccount').attr("href", "https://github.com/"+userName);
374 $('#logginMessage').css({'display' : 'block'});
375 $('#logginMessage').css({'text-align' : 'center'});
376 $('.popover').css({'height' : '190px'});
377 $('#signIn').text("Sign out");
378 $('#githubRepoDisplay').text(githubRepo);
379 sessionStarted = true;
380 reloadComment();
381 }
382 else
383 {
384 sessionStarted = false;
385 $('#logginMessage').css({'display' : 'none'});
386 $("#liGitHub").attr("class", "");
387 $("#imgGitHub").attr("src", "resources/icons/github-icon.png");
388 $('#loginGit').val("");
389 $('#passwordGit').val("");
390 $('#nickName').text("");
391 $('.popover').css({'height' : '325px'});
392 $('#logginMessage').css({'display' : 'none'});
393 $('#repositoryGit').val($('#repoName').attr('name'));
394 $('#branchGit').val('wikidoc');
395 $('#signIn').text("Sign In");
396 $('#loginGit').show();
397 $('#passwordGit').show();
398 $('#lbpasswordGit').show();
399 $('#lbloginGit').show();
400 $('#repositoryGit').show();
401 $('#lbrepositoryGit').show();
402 $('#lbbranchGit').show();
403 $('#branchGit').show();
404 $('#listBranches').hide();
405 $('#divGitHubRepoDisplay').hide();
406 }
407 }
408
409 function setCookie(c_name, value, exdays)
410 {
411 var exdate=new Date();
412 exdate.setDate(exdate.getDate() + exdays);
413 var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
414 document.cookie=c_name + "=" + c_value;
415 }
416
417 function del_cookie(c_name)
418 {
419 document.cookie = c_name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
420 }
421
422 function updateCookie(user, pwd, repo, branch){
423 if(checkCookie()){
424 branchName = branch;
425 setCookie("logginNitdoc", base64.encode(user+':'+pwd+':'+repo+':'+branch), 1);
426 }
427 }
428
429 function getCookie(c_name)
430 {
431 var c_value = document.cookie;
432 var c_start = c_value.indexOf(" " + c_name + "=");
433 if (c_start == -1) { c_start = c_value.indexOf(c_name + "="); }
434 if (c_start == -1) { c_value = null; }
435 else
436 {
437 c_start = c_value.indexOf("=", c_start) + 1;
438 var c_end = c_value.indexOf(";", c_start);
439 if (c_end == -1) { c_end = c_value.length; }
440 c_value = unescape(c_value.substring(c_start,c_end));
441 }
442 return c_value;
443 }
444
445 function getUserPass(c_name){
446 var cookie = base64.decode(getCookie(c_name));
447 return base64.encode(cookie.split(':')[0] + ':' + cookie.split(':')[1]);
448 }
449
450 function checkCookie()
451 {
452 var cookie=getCookie("logginNitdoc");
453 if (cookie!=null && cookie!="")
454 {
455 cookie = base64.decode(cookie);
456 userName = cookie.split(':')[0];
457 password = cookie.split(':')[1];
458 githubRepo = cookie.split(':')[2];
459 branchName = cookie.split(':')[3];
460 return true;
461 }
462 else { return false; }
463 }
464
465 function getLastCommit()
466 {
467 var urlHead = '';
468 if(sessionStarted){ urlHead = "https://api.github.com/repos/"+userName+"/"+githubRepo+"/git/refs/heads/"+branchName;}
469 else{
470 // TODO: get url of the original repo.
471 return;
472 }
473
474 $.ajax({
475 beforeSend: function (xhr) {
476 if (userB64 != ""){ xhr.setRequestHeader ("Authorization", userB64); }
477 },
478 type: "GET",
479 url: urlHead,
480 dataType:"json",
481 async: false,
482 success: function(success)
483 {
484 shaLastCommit = success.object.sha;
485 }
486 });
487 }
488
489 function getBaseTree()
490 {
491 $.ajax({
492 beforeSend: function (xhr) {
493 if (userB64 != ""){ xhr.setRequestHeader ("Authorization", userB64); }
494 },
495 type: "GET",
496 url: "https://api.github.com/repos/"+userName+"/"+githubRepo+"/git/commits/" + shaLastCommit,
497 dataType:"json",
498 async: false,
499 success: function(success)
500 {
501 shaBaseTree = success.tree.sha;
502 if (state){ setBlob(); }
503 else{ return; }
504 },
505 error: function(){
506 return;
507 }
508 });
509 }
510
511 function setNewTree()
512 {
513 $.ajax({
514 beforeSend: function (xhr) { xhr.setRequestHeader ("Authorization", userB64); },
515 type: "POST",
516 url: "https://api.github.com/repos/"+userName+"/"+githubRepo+"/git/trees",
517 async: false,
518 dataType:'json',
519 data:'{ "base_tree" : "'+shaBaseTree+'", '+
520 '"tree":[{ '+
521 '"path":"'+ pathFile +'",'+
522 '"mode":"100644",'+
523 '"type":"blob",'+
524 '"sha": "'+ shaBlob +'"'+
525 '}] '+
526 '}',
527 success: function(success)
528 { // si l'appel a bien fonctionné
529 shaNewTree = success.sha;
530 setNewCommit();
531 },
532 error: function(){
533 return;
534 }
535 });
536 }
537
538 function setNewCommit()
539 {
540 addSignedOff();
541 $.ajax({
542 beforeSend: function (xhr) { xhr.setRequestHeader ("Authorization", userB64); },
543 type: "POST",
544 url: "https://api.github.com/repos/"+userName+"/"+githubRepo+"/git/commits",
545 async: false,
546 dataType:'json',
547 data:'{ "message" : "'+ commitMessage +'", '+
548 '"parents" :"'+shaLastCommit+'",'+
549 '"tree": "'+shaNewTree+'"'+
550 '}',
551 success: function(success)
552 {
553 shaNewCommit = success.sha;
554 commit();
555 },
556 error: function(){
557 return;
558 }
559 });
560 }
561
562 //Create a commit
563 function commit()
564 {
565 $.ajax({
566 beforeSend: function (xhr) { xhr.setRequestHeader ("Authorization", userB64); },
567 type: "POST",
568 url: "https://api.github.com/repos/"+userName+"/"+githubRepo+"/git/refs/heads/"+branchName,
569 dataType:'json',
570 data:'{ "sha" : "'+shaNewCommit+'", '+
571 '"force" :"true"'+
572 '}',
573 success: function(success) { displayMessage('Commit created successfully', 40, 40); },
574 error:function(error){ displayMessage('Error ' + error.object.message, 40, 40); }
575 });
576 }
577
578 // Create a blob
579 function setBlob()
580 {
581 $.ajax({
582 beforeSend: function (xhr) { xhr.setRequestHeader ("Authorization", userB64); },
583 type: "POST",
584 url: "https://api.github.com/repos/"+userName+"/"+githubRepo+"/git/blobs",
585 async: false,
586 dataType:'json',
587 data:'{ "content" : "'+text.replace(/\r?\n/g, '\\n').replace(/\t/g, '\\t').replace(/\"/g,'\\"')+'", '+
588 '"encoding" :"utf-8"'+
589 '}',
590 success: function(success)
591 {
592 shaBlob = success.sha;
593 setNewTree();
594 },
595 error:function(error){
596 displayMessage('Error : Problem parsing JSON', 40, 40);
597 return;
598 }
599 });
600 }
601
602 // Display file content
603 function getFileContent(urlFile, newComment)
604 {
605 $.ajax({
606 beforeSend: function (xhr) {
607 xhr.setRequestHeader ("Accept", "application/vnd.github-blob.raw");
608 if (userB64 != ""){ xhr.setRequestHeader ("Authorization", userB64); }
609 },
610 type: "GET",
611 url: urlFile,
612 async:false,
613 success: function(success)
614 {
615 state = true;
616 replaceComment(newComment, success);
617 }
618 });
619 }
620
621 function replaceComment(newComment, fileContent){
622 var arrayNew = newComment.split('\n');
623 var lNew = arrayNew.length;
624 text = "";
625 var lines = fileContent.split("\n");
626 for (var i = 0; i < lines.length; i++) {
627 if(i == commentLineStart){
628 if(addNewComment){
629 for(var indexLine=0; indexLine < lines[i+1].length; indexxLine++){
630 if(lines[i+1].substr(indexLine,1) == "\t" || lines[i+1].substr(indexLine,1) == "#"){ text += lines[i+1].substr(indexLine,1); }
631 else{ break;}
632 }
633 text += lines[i] + "\n";
634 }
635 // We change the comment
636 for(var j = 0; j < lNew; j++){
637 if(commentType == 1){ text += "\t# " + arrayNew[j] + "\n"; }
638 else{
639 if(arrayNew[j] == ""){ text += "#"+"\n"; }
640 else{ text += "# " + arrayNew[j] + "\n"; }
641 }
642 }
643 }
644 else if(i < commentLineStart || i >= commentLineEnd){
645 if(i == lines.length-1){ text += lines[i]; }
646 else{ text += lines[i] + "\n"; }
647 }
648 }
649 if(addNewComment){
650 addNewComment = false;
651 }
652 }
653
654 function getCommentLastCommit(path, origin){
655 var urlRaw;
656 var bkBranch = '';
657 if(origin){// We want to get the original file
658 bkBranch = branchName;
659 branchName = "master";
660 }
661 getLastCommit();
662 if(shaLastCommit != ""){
663 if (checkCookie()) {
664 urlRaw="https://rawgithub.com/"+ userName +"/"+ githubRepo +"/" + shaLastCommit + "/" + path;
665 $.ajax({
666 type: "GET",
667 url: urlRaw,
668 async: false,
669 success: function(success)
670 {
671 if(origin){ originalFileContent = success; }
672 else{ currentfileContent = success; }
673 }
674 });
675 }
676 }
677 if(origin){ branchName = bkBranch; }
678 }
679
680 function displayMessage(msg, widthDiv, margModal){
681 spinner.stop();
682 $('#modal').hide();
683 $('#btnCancelBranch').hide();
684 $('#modalQuestion').show().prepend('<a class="close"><img src="resources/icons/close.png" class="btnCloseQuestion" title="Close" alt="Close" /></a>');
685 $('#txtQuestion').text(msg);
686 $('#btnCreateBranch').text("Ok");
687 var xModal = $('#modalQuestion').css('width').split('px')[0];
688 var yModal = $('#modalQuestion').css('height').split('px')[0];
689 var x = $(document).width/2 - xModal/2;
690 var y = $(document).height/2 - yModal/2;
691 var xBtnBranch = $('#btnCreateBranch').css('width').split('px')[0];
692 $('#modalQuestion').css({'left' : x, 'top' : y});
693 $('#modalQuestion').show();
694 $('#btnCreateBranch').css('margin-left', xModal/2 - xBtnBranch);
695 $('body').append('<div id="fade"></div>');
696 $('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn();
697 }
698
699 function displaySpinner(){
700 spinner.spin(targetSpinner);
701 $("#waitCommit").show();
702 }
703
704 // Check if the repo already exist
705 function isRepoExisting(){
706 $.ajax({
707 beforeSend: function (xhr) {
708 if (userB64 != "") { xhr.setRequestHeader ("Authorization", userB64); }
709 },
710 type: "GET",
711 url: "https://api.github.com/repos/"+userName+"/"+githubRepo,
712 async:false,
713 dataType:'json',
714 success: function(){ repoExist = true; },
715 error: function()
716 {
717 displayMessage('Repo not found !', 35, 45);
718 repoExist = false;
719 }
720 });
721 }
722
723 // Check if the branch already exist
724 function isBranchExisting(){
725 $.ajax({
726 beforeSend: function (xhr) {
727 if (userB64 != "") { xhr.setRequestHeader ("Authorization", userB64); }
728 },
729 type: "GET",
730 url: "https://api.github.com/repos/"+userName+"/"+githubRepo+"/git/refs/heads/"+branchName,
731 async:false,
732 dataType:'json',
733 success: function(){ branchExist = true; },
734 error: function()
735 {
736 branchExist = false;
737 editComment -= 1;
738 $('#modal').hide();
739 $('#txtQuestion').text("Are you sure you want to create that branch ?");
740 $('#btnCancelBranch').show();
741 $('#btnCreateBranch').text("Yes");
742 $('#modalQuestion').show();
743 $('#modalQuestion').show().prepend('<a class="close"><img src="resources/icons/close.png" class="btnCloseQuestion" title="Close" alt="Close" /></a>');
744 $('body').append('<div id="fade"></div>');
745 $('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn();
746 }
747 });
748 }
749
750 function getMasterSha()
751 {
752 $.ajax({
753 beforeSend: function (xhr) {
754 if (userB64 != ""){ xhr.setRequestHeader ("Authorization", userB64); }
755 },
756 type: "GET",
757 url: "https://api.github.com/repos/"+userName+"/"+githubRepo+"/git/refs/heads/master",
758 dataType:"json",
759 async: false,
760 success: function(success) { shaMaster = success.object.sha; }
761 });
762 }
763
764 function createBranch(){
765
766 getMasterSha();
767
768 $.ajax({
769 beforeSend: function (xhr) { xhr.setRequestHeader ("Authorization", userB64); },
770 type: "POST",
771 url: "https://api.github.com/repos/"+userName+"/"+githubRepo+"/git/refs",
772 data:'{ "ref" : "refs/heads/'+branchName+'",'+
773 '"sha" : "'+shaMaster+'"'+
774 '}',
775 success: function(){ return; },
776 error: function(){
777 editComment -= 1;
778 displayMessage('Impossible to create the new branch : ' + branchName, 40, 40);
779 }
780 });
781 }
782
783 $.fn.spin = function(opts) {
784 this.each(function() {
785 var $this = $(this),
786 data = $this.data();
787
788 if (data.spinner) {
789 data.spinner.stop();
790 delete data.spinner;
791 }
792 if (opts !== false) {
793 data.spinner = new Spinner($.extend({color: $this.css('color')}, opts)).spin(this);
794 }
795 });
796 return this;
797 };
798
799 function reloadComment(){
800 var path = $('pre[class=text_label]').attr('tag');
801 $.when(getCommentLastCommit(path, false)).done(function(){
802 if(sessionStarted){ getCommentLastCommit(path, true); }
803 $('pre[class=text_label]').each(function(){ getCommentOfFunction($(this)); });
804 });
805 }
806
807 function getCommentOfFunction(element){
808 var textC = "";
809 var numL = element.attr("title");
810 if(numL != null){
811 commentLineStart = numL-1;
812 commentLineEnd = element.attr('name').split(numL)[1].split('-')[1]-1;
813 var lines = currentfileContent.split("\n");
814 for (var i = 0; i < lines.length; i++) {
815 if(i >= commentLineStart-1 && i <= commentLineEnd+1){
816 if (lines[i].substr(1,1) == "#"){ textC += lines[i].substr(3,lines[i].length) + "\n";}
817 else if(lines[i].substr(0,1) == '#'){ textC += lines[i].substr(2,lines[i].length) + "\n"; }
818 }
819 }
820 if(textC != element.text){element.text(textC);}
821 if (textC != "" && editComment > 0){
822 var originContent = originalFileContent.split("\n");
823 var origin = '';
824 var lblDiff = element.parent().prev().children('#lblDiffCommit');
825 var preSave = element.parent().children('#preSave');
826 for (var i = 0; i < originContent.length; i++) {
827 if(i >= commentLineStart-1 && i <= commentLineEnd+1){
828 if (originContent[i].substr(1,1) == "#"){ origin += originContent[i].substr(3,originContent[i].length) + "\n";}
829 else if(originContent[i].substr(0,1) == '#'){ origin += originContent[i].substr(2,originContent[i].length) + "\n"; }
830 }
831 }
832 if(textC != origin && numL == numComment){
833 // The comment is different compare to the original
834 if(showcomment == false){ lblDiff.text("Show original comment"); }
835 preSave.text(origin);
836 }
837 else if (numL == numComment){ lblDiff.text(""); }
838 }
839 }
840 }
841
842 // Get list of branches
843 function getListBranches()
844 {
845 cleanListBranches();
846 $.ajax({
847 beforeSend: function (xhr) {
848 if ($("#login").val() != ""){ xhr.setRequestHeader ("Authorization", userB64); }
849 },
850 type: "GET",
851 url: "https://api.github.com/repos/"+userName+"/"+githubRepo+"/branches",
852 async:false,
853 dataType:'json',
854 success: function(success)
855 {
856 for(var branch in success) {
857 var selected = '';
858 if(branchName == success[branch].name){
859 selected = 'selected';
860 }
861 $('#dropBranches').append('<option value="" '+ selected +'>' + success[branch].name + '</option>');
862 }
863 }
864 });
865 }
866
867 // Delete all option in the list
868 function cleanListBranches(){
869 $('#dropBranches').children("option").remove();
870 }
871
872 function closeAllCommentInEdtiting(){
873 $('a[id=cancelBtn]').each(function(){
874 closeEditing($(this));
875 });
876 }
877
878 function closeEditing(tag){
879 if(editComment > 0){ editComment -= 1; }
880 // Hide itself
881 tag.hide();
882 // Hide commitBtn
883 tag.next().hide();
884 // Hide Textarea
885 tag.prev().hide();
886 // Show comment
887 tag.prev().prev().show();
888 }
889
890 function checkSignIn(){
891 var response = false;
892 $.ajax({
893 beforeSend: function (xhr) {
894 if ($("#login").val() != ""){ xhr.setRequestHeader ("Authorization", userB64); }
895 },
896 type: "GET",
897 url: "https://api.github.com/repos/"+userName+"/"+githubRepo,
898 async:false,
899 dataType:'json',
900 success: function(success)
901 {
902 getUserInfo();
903 response = true;
904 displayMessage('You are now logged in');
905 },
906 error: function()
907 {
908 displayMessage('Error : Wrong username or password');
909 response = false;
910 }
911 });
912 return response;
913 }
914
915 function getUserInfo(){
916 $.ajax({
917 beforeSend: function (xhr) {
918 if ($("#login").val() != ""){ xhr.setRequestHeader ("Authorization", userB64); }
919 },
920 type: "GET",
921 url: "https://api.github.com/user/emails",
922 async:false,
923 dataType:'json',
924 success: function(success)
925 {
926 userEmail = success;
927 }
928 });
929 }
930
931 function getSignedOff(){
932 $.ajax({
933 beforeSend: function (xhr) {
934 if ($("#login").val() != ""){ xhr.setRequestHeader ("Authorization", userB64); }
935 },
936 type: "GET",
937 url: "https://api.github.com/users/"+userName,
938 async:false,
939 dataType:'json',
940 success: function(success)
941 {
942 signedOff = success.name;
943 }
944 });
945 }
946
947 function addSignedOff(){
948 $.when(getUserInfo()).done(function(){
949 $.when(getSignedOff()).done(function(){
950 $('#commitMessage').val($('#commitMessage').val() + "\n\nSigned-off-by: "+signedOff+" <"+userEmail+">");
951 });
952 });
953 resizeTextarea($('#commitMessage'));
954 }
955
956 function removeSignedOff(){
957 $('#commitMessage').val(commitMessage);
958 resizeTextarea($('#commitMessage'));
959 }
960
961 function resizeTextarea(element){
962 var nLines = element.val().split('\n').length + 1;
963 element.attr('rows', nLines);
964 }
965
966 function showComment(element){
967 // Display the original comment
968 if (showcomment == true){
969 showcomment = false;
970 element.text("Show original comment");
971 }
972 else{
973 // Show the comment updated in user's repo
974 showcomment = true;
975 element.text("Comment changed in "+githubRepo+" / "+branchName);
976 }
977 var parent = element.parent().next(".description");
978 var textarea = parent.children('#fileContent');
979 var text = textarea.val();
980 var preSave = parent.children('#preSave');
981 textarea.val(preSave.text());
982 preSave.text(text);
983 // Resize edit box
984 textarea.height(textarea.prop("scrollHeight"));
985 resizeTextarea(textarea);
986 }
987
988 /* GitHub login box management */
989
990 function createLoginBox() {
991 $("nav.main ul").append(
992 "<li id='liGitHub'>" +
993 " <a class='btn' id='logGitHub'>" +
994 " <img id='imgGitHub' src='resources/icons/github-icon.png' alt='GitHub'/>" +
995 " </a>" +
996 " <div class='popover bottom' style='display: none;'>" +
997 " <div class='arrow'>&nbsp;</div>" +
998 " <div class='githubTitle'>" +
999 " <h3>Github Sign In</h3>" +
1000 " </div>" +
1001 " <div>" +
1002 " <label id='lbloginGit'>Username</label>" +
1003 " <input id='loginGit' name='login' type='text'/>" +
1004 " <label id='logginMessage'>Hello " +
1005 " <a id='githubAccount'><strong id='nickName'></strong></a>" +
1006 " </label>" +
1007 " </div>" +
1008 " <div>" +
1009 " <label id='lbpasswordGit'>Password</label>" +
1010 " <input id='passwordGit' name='password' type='password'/>" +
1011 " <div id='listBranches'>" +
1012 " <label id='lbBranches'>Branch</label>" +
1013 " <select class='dropdown' id='dropBranches' name='dropBranches' tabindex='1'></select>" +
1014 " </div>" +
1015 " </div>" +
1016 " <div>" +
1017 " <label id='lbrepositoryGit'>Repository</label>" +
1018 " <input id='repositoryGit' name='repository' type='text'/>" +
1019 " </div>" +
1020 " <div>" +
1021 " <label id='lbbranchGit'>Branch</label>" +
1022 " <input id='branchGit' name='branch' type='text'/>" +
1023 " </div>" +
1024 " <div>" +
1025 " <a id='signIn'>Sign In</a>" +
1026 " </div>" +
1027 " </div>" +
1028 " </div>" +
1029 "</li>"
1030 );
1031 }
1032
1033 function toggleLoginBox(){
1034 if ($('.popover').is(':hidden')) {
1035 if(sessionStarted){ getListBranches(); }
1036 $('.popover').show();
1037 } else {
1038 $('.popover').hide();
1039 }
1040 updateDisplaying();
1041 }