canvas.js 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919
  1. /* Contains all the Javascript logic of the canvas and its main features: save, export and share */
  2. $(document).ready(function() {
  3. /* ================================================
  4. Miscellaneous
  5. ================================================= */
  6. // Declare the currently loaded tags belonging to the user
  7. var tags;
  8. // Fixes bug when added item field zooms on tag click
  9. var tagWindowIsOpen = false;
  10. // This piece of code is for making the column-count and column-gap CSS to work in Firefox
  11. /*
  12. document.getElementById("7-5-col-layout").style.MozColumnCount = "7";
  13. document.getElementById("2-col-layout").style.MozColumnCount = "2";
  14. */
  15. // Prevent pressing ENTER on Project Title from submitting the form
  16. $('.proj_title').keydown(function(event){
  17. if(event.keyCode == 13) {
  18. event.preventDefault();
  19. return false;
  20. }
  21. });
  22. /* ================================================
  23. Rearrange fields numerically if 1 column is displayed
  24. ================================================= */
  25. // Declarations
  26. var groupOneLayout = $("#7-5-col-layout");
  27. var groupTwoLayout = $("#4-col-layout");
  28. var field01 = $("#panel_01");
  29. var field03 = $("#panel_03");
  30. var field04 = $("#panel_04");
  31. var field09 = $("#panel_09");
  32. var field05 = $("#panel_05");
  33. var field06 = $("#panel_06");
  34. var field02 = $("#panel_02");
  35. var field07 = $("#panel_07");
  36. var field08 = $("#panel_08");
  37. var isRearranged = false;
  38. // Rearrange the fields to suit mobile
  39. function rearrangeFields() {
  40. field01.detach();
  41. field03.detach();
  42. field04.detach();
  43. field09.detach();
  44. field05.detach();
  45. field06.detach();
  46. field02.detach();
  47. field07.detach();
  48. field08.detach();
  49. groupOneLayout.append(field01);
  50. groupOneLayout.append(field02);
  51. groupOneLayout.append(field03);
  52. groupOneLayout.append(field04);
  53. groupOneLayout.append(field05);
  54. groupOneLayout.append(field06);
  55. groupOneLayout.append(field07);
  56. groupOneLayout.append(field08);
  57. groupOneLayout.append(field09);
  58. }
  59. // Rearrange the fields according to their original order
  60. function rearrangeFieldsOriginal() {
  61. field01.detach();
  62. field02.detach();
  63. field03.detach();
  64. field04.detach();
  65. field05.detach();
  66. field06.detach();
  67. field07.detach();
  68. field08.detach();
  69. field09.detach();
  70. groupOneLayout.append(field01);
  71. groupOneLayout.append(field03);
  72. groupOneLayout.append(field04);
  73. groupOneLayout.append(field09);
  74. groupOneLayout.append(field05);
  75. groupOneLayout.append(field06);
  76. groupOneLayout.append(field02);
  77. groupTwoLayout.append(field07);
  78. groupTwoLayout.append(field08);
  79. }
  80. // If the web page is opened on a mobile
  81. if ($(window).width() <= 499) {
  82. rearrangeFields();
  83. }
  84. // When resizing the window
  85. $(window).on("resize", function() {
  86. if (isRearranged === false && $(window).width() <= 499) {
  87. rearrangeFields();
  88. isRearranged = true;
  89. }
  90. else if(isRearranged === true && $(window).width() >= 500) {
  91. rearrangeFieldsOriginal();
  92. isRearranged = false;
  93. }
  94. });
  95. /* ================================================
  96. "Jump to" functions
  97. ================================================= */
  98. var hasScrolledDown = false;
  99. function showFixedJumpedTo() {
  100. // Add classes
  101. $("div.jump-to-click-area").addClass("jump-to-click-area-toggle");
  102. $("div.jump-to").addClass("jump-to-toggle");
  103. $("div.jump-to-list").addClass("jump-to-list-toggle");
  104. $("img.jump-to-img").addClass("jump-to-img-toggle");
  105. // If the user clicks on a link and scrolls up the page, hide list
  106. $("div.jump-to-list").hide();
  107. }
  108. function showInitialJumpedTo() {
  109. // Toggle classes
  110. $("div.jump-to-click-area").removeClass("jump-to-click-area-toggle");
  111. $("div.jump-to").removeClass("jump-to-toggle");
  112. $("div.jump-to-list").removeClass("jump-to-list-toggle");
  113. $("img.jump-to-img").removeClass("jump-to-img-toggle");
  114. // If the user clicks on a link and scrolls up the page, toggle list
  115. $("div.jump-to-list").show();
  116. hasScrolledDown = false;
  117. }
  118. // When the user scrolls down, change "position" to "fixed"
  119. $(window).scroll(function() {
  120. // If the web page is opened on a mobile
  121. if($(window).width() <= 499) {
  122. // Declarations
  123. var scrollPosition = $(window).scrollTop();
  124. var jumpToPosition = $("div.jump-to").offset().top;
  125. // If the user has scrolled down to "Jump To..."
  126. if(hasScrolledDown === false && scrollPosition >= jumpToPosition) {
  127. showFixedJumpedTo();
  128. // Update scroll position
  129. $(window).scrollTop($("div.saved-tags").offset().top - 300);
  130. hasScrolledDown = true;
  131. }
  132. // If the user has scrolled up to the top
  133. else if(hasScrolledDown === true && scrollPosition === 0) {
  134. showInitialJumpedTo();
  135. }
  136. }
  137. // If the web page is not open on a mobile
  138. else {
  139. showInitialJumpedTo();
  140. }
  141. });
  142. // If the user clicks on "Jump to", show menu
  143. $("div.jump-to-click-area").on("click", function() {
  144. // Toggle the menu
  145. $("div.jump-to div div").slideToggle(300);
  146. // Rotate arrow
  147. // $("div.jump-to span.jump-to-arrow").toggleClass("rotate-arrow-180");
  148. // $("div.jump-to span.jump-to-arrow").toggleClass("rotate-arrow-0");
  149. $("img.jump-to-img").toggleClass("jump-to-arrow-90");
  150. $("img.jump-to-img").toggleClass("jump-to-arrow-0");
  151. return false;
  152. });
  153. // If the user clicks on a menu item
  154. $("div.jump-to ul a").on("click", function() {
  155. // Declarations
  156. var chosenLiIndex = $(this).parent().index();
  157. var chosenFieldPosition;
  158. var scrollPositionNew;
  159. // Detect the scroll position of the chosen field
  160. // If the user has chosen the list item 0
  161. if(chosenLiIndex === 0) {
  162. chosenFieldPosition = $("div.saved-tags").offset().top;
  163. }
  164. // If the user has chosen the list item 1-9
  165. else if(chosenLiIndex >= 1 && chosenLiIndex <= 9) {
  166. chosenFieldPosition = $("div.field_0" + chosenLiIndex).offset().top;
  167. }
  168. // If the user has chosen the list item 10 or higher
  169. else {
  170. chosenFieldPosition = $("div.field_" + chosenLiIndex).offset().top;
  171. }
  172. // If the user hasn't scrolled down
  173. if(hasScrolledDown === false) {
  174. console.log(chosenLiIndex);
  175. // Set the new scroll position
  176. scrollPositionNew = chosenFieldPosition - $("div.jump-to").height() - 89;
  177. // Add classes
  178. showFixedJumpedTo();
  179. // Update scroll position
  180. hasScrolledDown = true;
  181. }
  182. // If the user has scrolled down to "Jump To..."
  183. else {
  184. // Set the new scroll position
  185. scrollPositionNew = chosenFieldPosition - 57;
  186. // Toggle the menu
  187. $("div.jump-to-list").slideToggle(300);
  188. // Rotate arrow
  189. // $("div.jump-to span.jump-to-arrow").toggleClass("rotate-arrow-90");
  190. // $("div.jump-to span.jump-to-arrow").toggleClass("rotate-arrow-0");
  191. $("img.jump-to-img").toggleClass("jump-to-arrow-90");
  192. $("img.jump-to-img").toggleClass("jump-to-arrow-0");
  193. }
  194. // Apply the new scroll position
  195. $(window).scrollTop(scrollPositionNew);
  196. return false;
  197. });
  198. /* ================================================
  199. Show tooltip for every category
  200. ================================================= */
  201. $("a[data-toggle='tooltip']").tooltip({container: "body"});
  202. $("a[data-toggle='tooltip']").on("click", function() {
  203. return false;
  204. });
  205. /* ================================================
  206. Remove all tags from all fields
  207. ================================================= */
  208. // Remove all tags from all fields
  209. function removeTags() {
  210. // AJAX
  211. $.ajax({
  212. type: "POST",
  213. url: "php/get-tags.php",
  214. dataType: "JSON",
  215. data: {
  216. "username": username
  217. },
  218. timeout: 5000,
  219. success: function(returnData) {
  220. // Declarations
  221. var loopCounter = 0;
  222. tags = returnData;
  223. // For every added item
  224. $("li.added_item .expandable").each(function() {
  225. var thisDiv = $(this); // Delete the declaration (because it's ugly!)
  226. // For every tag in the database that belongs to the active user
  227. for(t in tags) {
  228. // If the current tag exists in the textarea
  229. if(thisDiv.html().indexOf("</a>") != -1) {
  230. // Delete the tag
  231. var text = thisDiv.html();
  232. text = thisDiv.text().replace("<a class='tag'>" + tags[loopCounter] + "</a>", tags[loopCounter]);
  233. thisDiv.html(text);
  234. }
  235. loopCounter++;
  236. }
  237. });
  238. if(tags.length === 0) {
  239. $("div.saved-tags p").html("You haven't added any tags yet.");
  240. }
  241. },
  242. error: function(xhr) {
  243. console.log(xhr.statusText);
  244. }
  245. });
  246. /*
  247. // The code below is much better than the code above, because no database connection is being called, but the "You haven't added any tags yet" text is not being reset
  248. // Declarations
  249. var loopCounter = 0;
  250. // For every added item
  251. $("li.added_item .expandable").each(function() {
  252. var thisDiv = $(this); // Delete the declaration (because it's ugly)
  253. // For every tag that belongs to the active user
  254. for(t in tags) {
  255. // If the current tag exists in the textarea
  256. if(thisDiv.html().indexOf("</a>") != -1) {
  257. // Delete the tag
  258. var text = thisDiv.html();
  259. text = thisDiv.text().replace("<a class='tag'>" + tags[loopCounter] + "</a>", tags[loopCounter]);
  260. thisDiv.html(text);
  261. }
  262. loopCounter++;
  263. }
  264. });
  265. console.log(tags);
  266. console.log(tags.length);
  267. if(tags.length === 0) {
  268. $("div.saved-tags p").html("You haven't added any tags yet.");
  269. }
  270. */
  271. }
  272. /* ================================================
  273. Get the user's tags from the database and apply them on the canvas
  274. ================================================= */
  275. // Apply tags (Incoming parameter is an array with every tag from the database belonging to the active user)
  276. function updateTags() {
  277. // Apply tags on the canvas
  278. /*
  279. IMPORTANT! A timer was needed in order to solve several bugs related to tags not being applied on the canvas.
  280. Should this still become an issue later on, try increasing the amount of milliseconds.
  281. */
  282. window.setTimeout(function() {
  283. // For every added item
  284. $("li.added_item .expandable").each(function() {
  285. // Declarations
  286. // var instanceCounter;
  287. var loopCounter = 0;
  288. var text = $(this).text();
  289. // For every tag in the database that belongs to the active user
  290. for(t in tags) {
  291. // Apply the tag for every instance of the current term
  292. // instanceCounter = text.indexOf(tags[loopCounter]);
  293. // while(instanceCounter > -1) {
  294. text = text.replace(tags[loopCounter], "<a class='tag' contenteditable='false'>" + tags[loopCounter] + "</a>");
  295. // instanceCounter = text.indexOf(tags[loopCounter], instanceCounter + 1);
  296. // }
  297. loopCounter++;
  298. }
  299. $(this).html(text);
  300. });
  301. // Show the tag window on tag click
  302. showTagWindowOnTagClick();
  303. }, 100);
  304. // Populate "Saved Tags"
  305. var loopCounter = 0;
  306. var savedTags = $("div.saved-tags p");
  307. savedTags.html("");
  308. for(t in tags) {
  309. if(savedTags.html() === "You haven't added any tags yet.") {
  310. savedTags.html("");
  311. }
  312. savedTags.append("<a href='#' class='tag'>" + tags[loopCounter] + "</a>").append("&nbsp;&nbsp; ");
  313. loopCounter++;
  314. }
  315. }
  316. // Get the tags from the database
  317. function getTags() {
  318. // Declarations
  319. var username = $("input[name='username']").val();
  320. // AJAX
  321. $.ajax({
  322. type: "POST",
  323. url: "php/get-tags.php",
  324. dataType: "JSON",
  325. data: {
  326. "username": username
  327. },
  328. timeout: 5000,
  329. success: function(returnData) {
  330. if(returnData.length > 0) {
  331. // Assign returnData to the tags variable
  332. tags = returnData;
  333. // Update tags on the canvas
  334. updateTags();
  335. }
  336. },
  337. error: function(xhr) {
  338. console.log(xhr.statusText);
  339. }
  340. });
  341. }
  342. /* ================================================
  343. Load tags if the user is logged in
  344. ================================================= */
  345. if($("input[name='name']").val() != "") {
  346. getTags();
  347. }
  348. /* ================================================
  349. Tag window functions
  350. ================================================= */
  351. // Declarations
  352. // var textarea = $("div#tag-window textarea#tag-description");
  353. var textareaHasBeenChanged = false;
  354. var tag;
  355. var tagIsNew = false;
  356. var username = $("input[name='username']").val();
  357. // Check if the tag is new
  358. function checkIfTagIsNew() {
  359. // Declarations
  360. var tagToAJAX = tag;
  361. // AJAX
  362. $.ajax({
  363. type: "POST",
  364. url: "php/check-if-tag-exists.php",
  365. dataType: "text",
  366. data: {
  367. "tag": tagToAJAX,
  368. "username": username
  369. },
  370. timeout: 5000,
  371. success: function(returnData) {
  372. // If the current tag does not exist in the database
  373. if(returnData === "") {
  374. // Hide "Delete tag" button
  375. $("div#tag-window button#delete-tag").css("display", "none");
  376. // Hide "Similar tags"
  377. $("div#tag-window h2.similar-tags").css("display", "none");
  378. // The tag is new
  379. tagIsNew = true;
  380. }
  381. // If the current tag exists in the database
  382. else {
  383. // Show "Delete tag" button
  384. $("div#tag-window button#delete-tag").css("display", "inline");
  385. // Show "Similar tags"
  386. $("div#tag-window h2.similar-tags").css("display", "block");
  387. }
  388. },
  389. error: function(xhr) {
  390. console.log(xhr.statusText);
  391. }
  392. });
  393. }
  394. // Updating the remaining characters information
  395. function updateRemainingCharacters() {
  396. // Declarations
  397. var length = $("div#tag-window textarea#tag-description").val().length; // Retrieving from "Please enter a description..."
  398. var maxLength = 200;
  399. /*
  400. var length;
  401. if(description != "") {
  402. length = description;
  403. }
  404. else {
  405. length = $("div#tag-window textarea#tag-description").val().length;
  406. }
  407. */
  408. // Update length
  409. length = maxLength - length;
  410. // Show the remaining characters
  411. $("div#tag-window span.chars").text(length);
  412. }
  413. // Get the description for the selected tag
  414. function getDescriptionForSelectedTag() {
  415. // Declarations
  416. var tagToAJAX = tag;
  417. // AJAX
  418. $.ajax({
  419. type: "POST",
  420. url: "php/get-description-for-selected-tag.php",
  421. dataType: "text",
  422. data: {
  423. "tag": tagToAJAX,
  424. "username": username
  425. },
  426. timeout: 5000,
  427. success: function(returnData) {
  428. if(returnData != "") {
  429. // Update description field with the description for the selected tag
  430. $("div#tag-window textarea#tag-description").val(returnData);
  431. // Update remaining characters
  432. updateRemainingCharacters();
  433. }
  434. textareaHasBeenChanged = true;
  435. },
  436. error: function(xhr) {
  437. console.log(xhr.statusText);
  438. }
  439. });
  440. }
  441. // Get similar tags by other users
  442. function getSimilarTags() {
  443. // Declarations
  444. var tagToAJAX = tag;
  445. // AJAX
  446. $.ajax({
  447. type: "POST",
  448. url: "php/get-similar-tags.php",
  449. dataType: "JSON",
  450. data: {
  451. "tag": tagToAJAX,
  452. "username": username
  453. },
  454. timeout: 5000,
  455. success: function(returnData) {
  456. // Reset similar tags if similar tags are to be showed again
  457. $("p.similar-tags-tag").remove();
  458. $("p.similar-tags-description").remove();
  459. $("p.similar-tags-username").remove();
  460. // Declarations
  461. var htmlToAppend = "";
  462. // If similar tags exist
  463. if(returnData.length > 0) {
  464. // Declarations
  465. var index = 0;
  466. // While there still are tags to append
  467. while(index < returnData.length) {
  468. htmlToAppend += "<p class='similar-tags-tag'><a class='tag'>" + returnData[index]["tag"] + "</a></p>"
  469. + "<p class='similar-tags-description'>" + returnData[index]["description"] + "</p>"
  470. + "<p class='similar-tags-username'>by <a href='#'>" + returnData[index]["username"] + "</a></p>";
  471. index++;
  472. }
  473. // Append tags
  474. $("div#tag-window h2.similar-tags").after(htmlToAppend);
  475. $("p.similar-tags-description-none").css("display", "none");
  476. // Update tags on the canvas
  477. // updateTags();
  478. }
  479. else {
  480. // If the tag isn't a new tag
  481. if(tagIsNew === false) {
  482. // Show the message saying that there are no similar tags to show
  483. $("p.similar-tags-description-none").css("display", "block");
  484. }
  485. }
  486. },
  487. error: function(xhr) {
  488. console.log(xhr.statusText);
  489. }
  490. });
  491. }
  492. // Close the tag window
  493. function closeTagWindow() {
  494. tagWindowIsOpen = false;
  495. $("div#shadow").css("display", "none");
  496. $("div#tag-window").css("display", "none");
  497. }
  498. // Show the tag window
  499. function showTagWindow() {
  500. // Show the tag window
  501. $("div#shadow").css("display", "block");
  502. $("div#tag-window").css("display", "block");
  503. // Move the window to the centre of the screen
  504. /*
  505. The code below should be working, but the height of the second selector seems completely wrong!
  506. var middle = (document.body.clientHeight / 2) - ($("div#tag-window").height() / 2);
  507. $("div#tag-window").css("top", middle);
  508. */
  509. // Check if the tag is new
  510. checkIfTagIsNew();
  511. // Get the description for the selected tag
  512. getDescriptionForSelectedTag();
  513. // Get tags by other users from the database
  514. getSimilarTags();
  515. // Update remaining characters in case description is loaded
  516. updateRemainingCharacters();
  517. // If a description hasn't been entered
  518. if($("div#tag-window textarea#tag-description") !== "Please enter a description..." && textareaHasBeenChanged !== true) {
  519. // Reset the remaining characters information
  520. $("div#tag-window span.chars").text("200");
  521. }
  522. }
  523. // If the user presses a key in the description textarea
  524. $("div#tag-window textarea#tag-description").on("keyup", function() {
  525. // Update remaining characters
  526. updateRemainingCharacters();
  527. });
  528. // If the user clicks on the "Save tag" button
  529. $("div#tag-window #save-tag").on("click", function() {
  530. // Declarations
  531. var description = $("div#tag-window textarea#tag-description").val();
  532. var tagToAJAX = tag;
  533. // If a description has been entered
  534. if(description != "" && description != "Please enter a description...") {
  535. // AJAX
  536. $.ajax({
  537. timeout: 5000,
  538. dataType: "text",
  539. type: "post",
  540. data: {
  541. "tag": tagToAJAX,
  542. "description": description,
  543. "username": username
  544. },
  545. url: "php/save-tag.php",
  546. success: function() {
  547. textareaHasBeenChanged = true;
  548. // Get the user's tags from the database and apply them on the canvas
  549. getTags();
  550. },
  551. error: function(xhr) {
  552. console.log(xhr.statusText);
  553. }
  554. });
  555. // Close the tag window
  556. closeTagWindow();
  557. }
  558. tagIsNew = false;
  559. });
  560. // If the user clicks on the "Close" button
  561. $("div#tag-window button.close").on("click", function() {
  562. // Close the tag window
  563. closeTagWindow();
  564. });
  565. // If the user clicks on the "Delete tag" button
  566. $("div#tag-window #delete-tag").on("click", function() {
  567. // Declarations
  568. var tagToAJAX = tag;
  569. // AJAX
  570. $.ajax({
  571. timeout: 5000,
  572. dataType: "text",
  573. type: "post",
  574. data: {
  575. "tag": tagToAJAX,
  576. "username": username
  577. },
  578. url: "php/delete-tag.php",
  579. success: function() {
  580. // Remove all tags from all fields
  581. removeTags();
  582. // Get the user's tags from the database and apply them on the canvas
  583. getTags();
  584. },
  585. error: function(xhr) {
  586. console.log(xhr.statusText);
  587. }
  588. });
  589. // Close the tag window
  590. closeTagWindow();
  591. });
  592. // If the user focuses in the textarea
  593. $("div#tag-window textarea#tag-description").on("focusin", function() {
  594. // Declarations
  595. var description = $("div#tag-window textarea#tag-description").val();
  596. // If a description hasn't been entered
  597. // if(textareaHasBeenChanged === false) {
  598. if(description === "Please enter a description...") {
  599. // Empty the description textarea
  600. $("div#tag-window textarea#tag-description").val("");
  601. }
  602. });
  603. // If the user focuses out the textarea
  604. $("div#tag-window textarea#tag-description").on("focusout", function() {
  605. // Declarations
  606. var description = $("div#tag-window textarea#tag-description").val();
  607. // If a description hasn't been entered
  608. // if(textareaHasBeenChanged === false) {
  609. if(description === "") {
  610. // Reset the description textarea
  611. $("div#tag-window textarea#tag-description").val("Please enter a description...");
  612. }
  613. });
  614. /* ================================================
  615. If the user clicks on a tag, show the tag window
  616. ================================================= */
  617. // If the user clicks on a tag
  618. function showTagWindowOnTagClick() {
  619. $("a.tag").on("click", function() {
  620. // Declarations
  621. tag = $(this).text();
  622. // If the user is logged in
  623. if($("input[name='username']").val() != "") {
  624. tagWindowIsOpen = true;
  625. // Show the tag window
  626. showTagWindow();
  627. }
  628. else {
  629. // Show a dialog
  630. $("div#shadow").css("display", "block");
  631. $("div#dialog-log-in").css("display", "block");
  632. }
  633. });
  634. }
  635. /*
  636. // Mouse-enabled devices
  637. $("tag").mouseenter(function() {
  638. timer = setTimeout(function() {
  639. showTagWindow(); // showTagWindow needs a parameter!
  640. }, 400);
  641. }).mouseleave(function() {
  642. clearTimeout(timer);
  643. });
  644. // Touch devices
  645. try {
  646. document.createEvent("TouchEvent");
  647. $("a.tag").on("click", showTagWindow()); // showTagWindow needs a parameter!
  648. return true;
  649. }
  650. catch(e) {
  651. return false;
  652. }
  653. */
  654. /* ================================================
  655. Save added idea on Enter press
  656. ================================================= */
  657. function saveAddedIdeaOnEnterPress(li) {
  658. $("li.added_item textarea.expandable").on("keydown", function(event) {
  659. if(event.which === 13) {
  660. event.preventDefault();
  661. // Replace textarea with a div
  662. $(this).replaceWith(
  663. "<div class='expandable' name='" + $(this).attr("name") + "'>" + $(this).val() + "</div>"
  664. );
  665. // Update tags on the canvas
  666. // window.setTimeout(updateTags(), 100);
  667. updateTags();
  668. // Zoom out animation
  669. li.find("div").addClass("zoom-out");
  670. li.find("div").css("background-color", "rgba(255, 255, 255, 0.75)");
  671. li.find("div").css("-ms-transform", "scale(1)");
  672. li.find("div").css("-webkit-transform", "scale(1)");
  673. li.find("div").css("transform", "scale(1)");
  674. toggleTextElementOnFocus();
  675. }
  676. });
  677. }
  678. /* ================================================
  679. Toggle textarea.expandable/div.expandable on edit
  680. ================================================= */
  681. function toggleTextElementOnFocus() {
  682. // If the user clicks on the added idea
  683. $("li.added_item .expandable").on("click", function() {
  684. if(tagWindowIsOpen === false) {
  685. var li = $(this).parent();
  686. // Replace div with a textarea
  687. $(this).replaceWith(
  688. "<textarea maxlength='100' class='expandable' rows='3' data-limit-rows='true' data-autoresize name='" + $(this).attr("name") + "'>" + $(this).text() + "</textarea>"
  689. );
  690. // Focus immediately on click instead of having to click on the element a second time
  691. li.find("textarea").focus();
  692. // Zoom in animation
  693. li.find("textarea").addClass("zoom-in");
  694. li.find("textarea").css("background-color", "rgba(255, 255, 255, 1)");
  695. li.find("textarea").css("-ms-transform", "scale(1.03)");
  696. li.find("textarea").css("-webkit-transform", "scale(1.03)");
  697. li.find("textarea").css("transform", "scale(1.03)");
  698. // Save added idea on Enter press
  699. saveAddedIdeaOnEnterPress(li);
  700. // Replace textarea with a div
  701. $("li.added_item textarea.expandable").on("focusout", function() {
  702. // Replace textarea with a div
  703. $(this).replaceWith(
  704. "<div class='expandable' name='" + $(this).attr("name") + "'>" + $(this).val() + "</div>"
  705. );
  706. // Update tags on the canvas
  707. // window.setTimeout(updateTags(), 100);
  708. updateTags();
  709. // Zoom out animation
  710. li.find("div").addClass("zoom-out");
  711. li.find("div").css("background-color", "rgba(255, 255, 255, 0.75)");
  712. li.find("div").css("-ms-transform", "scale(1)");
  713. li.find("div").css("-webkit-transform", "scale(1)");
  714. li.find("div").css("transform", "scale(1)");
  715. toggleTextElementOnFocus();
  716. });
  717. }
  718. });
  719. }
  720. /*
  721. // ================================================
  722. If the user types a new character in the added idea field, add tag if a term could be found
  723. ================================================= //
  724. // 8an33j24
  725. function applyTagOnTypeMatch() {
  726. $("li.added_item .expandable").on("focusin", function() {
  727. // If the user presses a key in the description textarea
  728. $("li.added_item .expandable").on("keyup", function() {
  729. if(event.which !== 9 && // Tab
  730. event.which !== 16 && // Shift
  731. event.which !== 37 && // Left
  732. event.which !== 38 && // Up
  733. event.which !== 39 && // Right
  734. event.which !== 40) { // Down
  735. // Declarations
  736. var bugCounter = 0;
  737. var loopCounter = 0;
  738. var tagLinkToSearch;
  739. var tagLinkHits;
  740. var tagTextToSearch;
  741. var tagTextHits;
  742. var text = $(this).html();
  743. // Fix the bug that triggers the event twice
  744. if(!bugCounter > 0) {
  745. // console.log("tagTextHits: " + tagTextHits);
  746. // console.log("tagLinkHits: " + tagLinkHits);
  747. // For every tag that belongs to the active user
  748. for(t in tags) {
  749. if($(this).html().indexOf(tags[loopCounter]) != -1) {
  750. // Search for the tag inside the added idea as a link
  751. tagLinkToSearch = text.match(tags[loopCounter] + "</a>"); // match() can only count to one instance (67hi9nt3)
  752. // Search for the tag inside the added idea as plain text
  753. tagTextToSearch = text.match(tags[loopCounter]); // match() can only count to one instance (67hi9nt3)
  754. // If the tag exists inside the added idea as a link
  755. if(tagLinkToSearch !== null) {
  756. // tagLinkHits = 1
  757. tagLinkHits = tagLinkToSearch.length;
  758. }
  759. else {
  760. // tagLinkHits = 0
  761. tagLinkHits = 0;
  762. }
  763. // If the tag exists inside the added idea as plain text
  764. if(tagTextToSearch !== null) {
  765. // tagTextHits = 1
  766. tagTextHits = tagTextToSearch.length;
  767. }
  768. else {
  769. // tagTextHits = 0
  770. tagTextHits = 0;
  771. }
  772. // If there are more instances of the tag as plain text than the tag as links, and there is a maximum of 1 instances of the tag as plain text
  773. // Change "tagTextHits <= 1" to "tagLinkHits === 0"
  774. if(tagTextHits > tagLinkHits && tagLinkHits === 0) {
  775. // Apply the tag
  776. text = text.replace(tags[loopCounter], "<a class='tag' contenteditable='false'>" + tags[loopCounter] + "</a>");
  777. $(this).html(text);
  778. // Restore caret position // u78krf3t
  779. }
  780. }
  781. loopCounter++;
  782. }
  783. }
  784. bugCounter++;
  785. }
  786. });
  787. });
  788. };
  789. */
  790. /* ----------------------------------------------
  791. Limiting the number of characters the user is allowed to type
  792. ----------------------------------------------- */
  793. var maxLength = 100;
  794. $('.card').on('keyup', '.new_item', function() {
  795. var length = $(this).val().length;
  796. length = maxLength - length;
  797. // show the characters remaining only on this field
  798. $(this).closest('.user-input').find('.chars').text(length);
  799. });
  800. function limitLengthOnInput() {
  801. // Limit text on key press
  802. $("li.added_item .expandable").on("keypress", function(event) {
  803. // Declarations
  804. var numberOfTags = $(this).children().filter("a").length;
  805. var textLength = $(this).html().length;
  806. // Subtract 43 from textLength per tag (the tag HTML is 43 characters)
  807. $(this).each(function() {
  808. textLength -= 43 * numberOfTags;
  809. });
  810. if(textLength === 100) { // Windows menu/Right cmd
  811. event.preventDefault();
  812. }
  813. });
  814. // 28jek79t
  815. // Limit text on paste
  816. /*
  817. var pastedTextOriginal;
  818. $("li.added_item .expandable").on("paste", function(event) {
  819. pastedTextOriginal = event.originalEvent.clipboardData.getData("Text");
  820. if($(this).html().length + pastedTextOriginal > 100) {
  821. console.log("Too long!");
  822. event.preventDefault();
  823. // var caretPosition = the text position
  824. // Insert the text after caretPosition
  825. }
  826. // return false;
  827. });
  828. */
  829. }
  830. /* ================================================
  831. If the user closes a dialog
  832. ================================================= */
  833. $("div.dialog button").on("click", function() {
  834. $("div#shadow").css("display", "none");
  835. $("div.dialog").css("display", "none");
  836. });
  837. /* ================================================
  838. If the user clicks on the "Tag selected term" link
  839. ================================================= */
  840. // Declaration
  841. var selection = "";
  842. // var newRange = "";
  843. // Initiate tag
  844. tag = "";
  845. // Update the tag variable
  846. document.onselectionchange = function() {
  847. // if($("textarea").is(":focus")) {
  848. if($("li.added_item .expandable").is(":focus")) {
  849. selection = window.getSelection().toString();
  850. tag = selection.trim();
  851. }
  852. }
  853. // If the user clicks on the "Tag selected term" link
  854. $("p.tag-selected-term a").on("click", function() {
  855. // If the tag isn't empty
  856. if(tag != "") {
  857. // Show the tag window
  858. showTagWindow();
  859. }
  860. else {
  861. // Show a dialog
  862. $("div#shadow").css("display", "block");
  863. $("div#dialog-select-term").css("display", "block");
  864. }
  865. // Prevent the current view to jump to the top of the screen
  866. return false;
  867. });
  868. // If the user moves the focus from the added idea, reset variables
  869. $("li.added_item .expandable").on("focusout", function() {
  870. selection = "";
  871. tag = "";
  872. });
  873. /* ================================================
  874. Serialize Form to JSON
  875. ================================================= */
  876. $.fn.serializeObject = function() {
  877. var o = {};
  878. var a = this.serializeArray();
  879. $.each(a, function() {
  880. if (o[this.name]) {
  881. if (!o[this.name].push) {
  882. o[this.name] = [o[this.name]];
  883. }
  884. o[this.name].push(this.value || '');
  885. } else {
  886. o[this.name] = this.value || '';
  887. }
  888. });
  889. return o;
  890. };
  891. /* ================================================
  892. Getting the current date
  893. ================================================= */
  894. var fullDate = new Date();
  895. var twoDigitMonth = fullDate.getMonth() + "";
  896. if (twoDigitMonth.length == 1) twoDigitMonth = "0" + twoDigitMonth;
  897. var twoDigitDate = fullDate.getDate() + "";
  898. if (twoDigitDate.length == 1) twoDigitDate = "0" + twoDigitDate;
  899. var currentDate = fullDate.getFullYear() + "-" + twoDigitMonth + "-" + twoDigitDate;
  900. // set the currebt date in the date input field
  901. $('.proj_date').val(currentDate);
  902. /* ================================================
  903. USER LOGS OUT (dropdown menu)
  904. ================================================= */
  905. $('.user-profile').on('click', '#logout', function() {
  906. var url = 'php/logout.php';
  907. $.post(url, function(data, status) {
  908. if (data == 200) {
  909. $('.user-profile').hide();
  910. window.location.href="https://www.ethicscanvas.org";
  911. }
  912. });
  913. });
  914. /* ================================================
  915. When the page loads, Import the chosen canvas if the user has picked one from the dashbord,
  916. otherwise load an empty canvas
  917. ================================================= */
  918. // if a canvas is chosen by the user to be loaded
  919. if (current_canvas_id !== '') {
  920. var url = 'json/' + current_canvas_id + '.json';
  921. // var url= 'json/test_canvas.json';
  922. // get the saved ISON object in the sendJSON.text file
  923. $.getJSON(url, function(returnedObj) {
  924. // Display the json data in the html
  925. var itemListHTML = '';
  926. // iterate through the object
  927. $.each(returnedObj, function(key, value) {
  928. // project name and tem field
  929. if (key === 'field_00[]') {
  930. $('.form-header').find('input.proj_title').val(value[
  931. 0]);
  932. $('.form-header').find('input.proj_date').val(value[1]);
  933. }
  934. else if (key !== 'new_item') {
  935. if ($.type(value) === "array") {
  936. $.each(value, function(i, itm) {
  937. /** FIX DUPLICATIONs in the canvas when importing
  938. /* Importing will override the canvas content
  939. clear the canvas by giving en emty content to the ul list (remove previous list items) */
  940. $('.canvas-form').find('.card').filter('.' + key.substr(0, 8)).find('ul.item_list').html('');
  941. /* Create a list item with each value item
  942. and give it text area with the name attribute as the "key" (right field name) */
  943. itemListHTML +=
  944. // '<li class="added_item"><span class="handle glyphicon glyphicon-move"></span><textarea maxlength="100" class="expandable" rows="3" data-limit-rows="true" data-autoresize name="' + key + '">' + itm + '</textarea><span class="remove glyphicon glyphicon-remove-circle"></span></li>';
  945. '<li class="added_item"><div class="expandable" name="' + key + '">' + itm + '</div><span class="handle glyphicon glyphicon-list"></span><span class="move-up glyphicon glyphicon-chevron-up"></span><span class="move-down glyphicon glyphicon-chevron-down"></span><span class="remove glyphicon glyphicon-remove-circle"></span></li>';
  946. });
  947. }
  948. else { // a single value string
  949. itemListHTML +=
  950. // '<li class="added_item"><span class="handle glyphicon glyphicon-move"></span><textarea maxlength="100" class="expandable" rows="3" data-limit-rows="true" data-autoresize name="' + key + '">' + value + '</textarea><span class="remove glyphicon glyphicon-remove-circle"></span></li>';
  951. '<li class="added_item"><div class="expandable" name="' + key + '">' + value + '</div><span class="handle glyphicon glyphicon-list"></span><span class="move-up glyphicon glyphicon-chevron-up"></span><span class="move-down glyphicon glyphicon-chevron-down"></span><span class="remove glyphicon glyphicon-remove-circle"></span></li>';
  952. }
  953. /* Append the created list items/textatreas to the right field based on the "key"*/
  954. /* the str.substr(start,length)
  955. is used to remove the [] from the end of the "key"name (for each field. also the name attributes accociated with each fiels) so that we can select the right class (right field) and append the created lists to the right field
  956. so field names/key/name attribute will tuen into class names: ex: field_1[] becomes field_1
  957. */
  958. // find the field by its class names besed on the current key name
  959. // append the created list of item values to that right field
  960. $('.canvas-form').find('.card').filter('.' + key.substr(0, 8)).find('ul.item_list').append(itemListHTML);
  961. /*$('form').find('.card').filter('.field_1').find('ul.item_list').append(itemListHTML); */
  962. /* !! Empty the item list after each count of "key" so that the previous item lists from the other fields (associated with the previous key) don't get added up to the item list of other fields */
  963. itemListHTML = '';
  964. }
  965. });
  966. });
  967. // Toggle textarea.expandable/div.expandable on edit
  968. toggleTextElementOnFocus();
  969. // Get the user's tags from the database and apply them on the canvas
  970. getTags();
  971. // Show "Tag selected term" link
  972. if($(this).parent().parent().parent().prev().prev().children().length > 0) {
  973. $(this).parent().parent().parent().prev().css("display", "block");
  974. }
  975. // Fix the heights after importing
  976. // fixHeights();
  977. }
  978. /* ================================================
  979. Toggle the introduction text in fields
  980. ================================================= */
  981. //$(selector).toggle(speed,easing,callback)
  982. $('.card').on('click', '.intro-toggle', function() {
  983. var $TogglingText = $($(this).closest('.card').find('.intro'));
  984. var $Toggler = $($(this).closest('.card').find('.intro-toggle'));
  985. $TogglingText.toggle('slow', function() {
  986. // Do this when toggling:
  987. // the boolean .is(':visible') of the current toggle state
  988. if ($TogglingText.is(':visible')) {
  989. // change the text of the toggle
  990. $Toggler.find('.intro-toggle-text').text('Hide description');
  991. // change the icon of the toggle
  992. $Toggler.find('.intro-toggle-icon').switchClass("glyphicon-plus-sign", "glyphicon-minus-sign", 1000, "easeInOutQuad");
  993. }
  994. else {
  995. $Toggler.find('.intro-toggle-text').text('Show description');
  996. $Toggler.find('.intro-toggle-icon').switchClass("glyphicon-minus-sign", "glyphicon-plus-sign", 1000, "easeInOutQuad");
  997. }
  998. });
  999. });
  1000. /* ================================================
  1001. Auto expand user input textareas
  1002. ================================================= */
  1003. /* Works for textareas already exsting in the html when the page loads -> User input
  1004. $.each($('textarea[data-autoresize]'), function() {
  1005. var offset = this.offsetHeight - this.clientHeight;
  1006. var resizeTextarea = function(el) {
  1007. $(el).css('height', 'auto').css('height', el.scrollHeight + offset);
  1008. };
  1009. $(this).on('keyup input', function() {
  1010. resizeTextarea(this);
  1011. }).removeAttr('data-autoresize');
  1012. });
  1013. /* ================================================
  1014. Limiting the number of lines in textareas
  1015. ================================================= */
  1016. // <textarea data-limit-rows="true" cols="60" rows="8"></textarea>
  1017. /*
  1018. $('.card').on('keypress', 'textarea[data-limit-rows=true]', function(event) {
  1019. var textarea = $(this),
  1020. text = textarea.val(),
  1021. // match() -> Searches a string for a match against a regular expression, and returns the matches, as an Array object.
  1022. numberOfLines = (text.match(/\n/g) || []).length + 1,
  1023. maxRows = parseInt(textarea.attr('rows'));
  1024. // if the number of lines have reached the max rows
  1025. if (numberOfLines === maxRows) {
  1026. return false;
  1027. }
  1028. });
  1029. */
  1030. /* ================================================
  1031. Handling user input, ADD items
  1032. A. Add button
  1033. B. Clicking enter
  1034. ================================================= */
  1035. /* ----------------------------------------------
  1036. add new idea slide effect
  1037. ----------------------------------------------- */
  1038. // When clicking on "add a new idea", Slide down and show the input field for adding a new item (from the begining, it is set to display:hidden with CSS). If clicked again, slide it up. After that, set the textarea in automatic focus
  1039. $('.card').on('click', 'a.add-idea', function(event) {
  1040. // stop the default behavior of the link (jumping back to the start of the page)
  1041. event.preventDefault();
  1042. // set the textarea automatically in focus
  1043. $(this).closest('.card').find('.user-input').slideToggle("slow", function() {
  1044. // When the toggle animation is complete:
  1045. // set the text area in focus
  1046. $(this).closest('.card').find('.new_item').val('');
  1047. $(this).closest('.card').find('.chars').text(maxLength);
  1048. $(this).closest('.card').find('.new_item').focus();
  1049. });
  1050. });
  1051. /* ----------------------------------------------
  1052. A. When we click the add btn to
  1053. add the item to the list
  1054. ----------------------------------------------- */
  1055. // event deligation to handle the present and future elements that are dynamically added
  1056. $('.card').on('click', '.add_btn', function() {
  1057. var new_item = $(this).closest('.card').find('.new_item').val();
  1058. var new_item_height = $(this).closest('.card').find('.new_item').height();
  1059. // number of items are in the list
  1060. var fieldItemCount = $(this).closest('.card').find('ul.item_list').find('li').length;
  1061. // new item added, increment the number of items
  1062. fieldItemCount++;
  1063. // add the input value as a textarea item
  1064. /* create a name attribute in the "field_nr[]" format to be able to tag each new item with the right field attr name (based on the field they are added to). This is to format the json file for each group of dynamically added items. We get the name attribute directly from the id attribute of the ul list in each card (the one we pressed the add button in) */
  1065. // if the new item input exist (is not empty), add the item
  1066. if (new_item) {
  1067. var field_attr = $(this).closest('.card').find('ul.item_list').attr('id') + '[]';
  1068. // The height of the newly added item = the height of the add new idea textarea
  1069. $(this).closest('.card').find('ul.item_list').append(
  1070. // '<li class="added_item"><span class="handle glyphicon glyphicon-move"></span><textarea maxlength="100" class="expandable" rows="3" data-limit-rows="true" data-autoresize name="' + field_attr + '">' + new_item + '</textarea><span class="remove glyphicon glyphicon-remove-circle"></span></li>'
  1071. '<li class="added_item"><div class="expandable" name="' + field_attr + '">' + new_item + '</div><span class="handle glyphicon glyphicon-list"></span><span class="move-up glyphicon glyphicon-chevron-up"></span><span class="move-down glyphicon glyphicon-chevron-down"></span><span class="remove glyphicon glyphicon-remove-circle"></span></li>'
  1072. );
  1073. // Fix the heights only after a new item is added
  1074. // fixHeights();
  1075. }
  1076. // clear the new item the text area value
  1077. $(this).closest('.card').find('.new_item').val('');
  1078. /* When clicking on "add idea", hide the input field for adding a new item (slideUp() doesn't work nicely here)*/
  1079. $(this).closest('.card').find('.user-input').hide("fast", function() {
  1080. // Animation complete.
  1081. });
  1082. // Limit the text in the idea field if it reaches the max length
  1083. limitLengthOnInput();
  1084. // Apply event listener to the added idea handling the application of tags should the user writes one of the terms in it
  1085. // applyTagOnTypeMatch();
  1086. // Toggle textarea.expandable/div.expandable on edit
  1087. toggleTextElementOnFocus();
  1088. // Remove all tags from all fields
  1089. removeTags();
  1090. // Get the user's tags from the database and apply them on the canvas
  1091. getTags();
  1092. // Show "Tag selected term" link
  1093. if($(this).parent().parent().prev().prev().children().length > 0) {
  1094. $(this).parent().parent().prev().css("display", "block");
  1095. }
  1096. });
  1097. /* ----------------------------------------------
  1098. B. Clicking enter in the add idea textarea,
  1099. will add the new item to the card
  1100. ----------------------------------------------- */
  1101. $('.card').on('keypress', 'textarea[data-limit-rows=true]', function(event) {
  1102. var textarea = $(this);
  1103. var text = textarea.val();
  1104. /* The jQuery event.which -->
  1105. Returns which keyboard key was pressed: */
  1106. // if the enter is pressed, event.which === 13
  1107. if (event.which === 13 && !$("li.added_item .expandable").is(":focus")) {
  1108. var new_item = $(this).closest('.card').find('.new_item').val();
  1109. var new_item_height = $(this).closest('.card').find('.new_item').height();
  1110. // number of items are in the list
  1111. var fieldItemCount = $(this).closest('.card').find('ul.item_list')
  1112. .find('li').length;
  1113. // new item added, increment the number of items
  1114. fieldItemCount++;
  1115. // add the input value as a textarea item
  1116. /* create a name attribute in the "field_nr[]" format to be able to tag each new item with the right field attr name (based on the field they are added to). This is to format the json file for each group of dynamically added items. We get the name attribute directly from the id attribute of the ul list in each card (the one we pressed the add button in) */
  1117. // if the new item input exist (is not empty), add the item
  1118. if (new_item) {
  1119. var field_attr = $(this).closest('.card').find('ul.item_list').attr(
  1120. 'id') + '[]';
  1121. // The height of the newly added item = the height of the add new idea textarea
  1122. $(this).closest('.card').find('ul.item_list').append(
  1123. // '<li class="added_item"><span class="handle glyphicon glyphicon-move"></span><textarea maxlength="100" class="expandable" rows="3" data-limit-rows="true" data-autoresize name="' + field_attr + '">' + new_item + '</textarea><span class="remove glyphicon glyphicon-remove-circle"></span></li>');
  1124. '<li class="added_item"><div class="expandable" name="' + field_attr + '">' + new_item + '</div><span class="handle glyphicon glyphicon-list"></span><span class="move-up glyphicon glyphicon-chevron-up"></span><span class="move-down glyphicon glyphicon-chevron-down"></span><span class="remove glyphicon glyphicon-remove-circle"></span></li>'
  1125. );
  1126. // Fix the heights only after a new item is added
  1127. // fixHeights();
  1128. }
  1129. // clear the new item the text area value
  1130. $(this).closest('.card').find('.new_item').val('');
  1131. /* When clicking on "add idea", hide the input field for adding a new item (slideUp() doesn't work nicely here)*/
  1132. $(this).closest('.card').find('.user-input').hide("fast", function() {
  1133. // Animation complete.
  1134. });
  1135. // Limit the text in the idea field if it reaches the max length
  1136. limitLengthOnInput();
  1137. // Apply event listener to the added idea handling the application of tags should the user writes one of the terms in it
  1138. // applyTagOnTypeMatch();
  1139. // Toggle textarea.expandable/div.expandable on edit
  1140. toggleTextElementOnFocus();
  1141. // Remove all tags from all fields
  1142. removeTags();
  1143. // Get the user's tags from the database and apply them on the canvas
  1144. getTags();
  1145. // Show "Tag selected term" link
  1146. if($(this).parent().parent().parent().prev().prev().children().length > 0) {
  1147. $(this).parent().parent().parent().prev().css("display", "block");
  1148. }
  1149. }
  1150. });
  1151. /* ================================================
  1152. Moving ideas to a different category
  1153. ================================================= */
  1154. // Declarations
  1155. // var categoryUl = $("div#move-window ul");
  1156. var categoryDestination;
  1157. var categoryLis = $("div#move-window ul").html();
  1158. var categoryOrigin;
  1159. var ideaLi;
  1160. var linkLi;
  1161. var linkText;
  1162. // Remove the link to the current category, as the idea cannot be moved to its own category where it already is
  1163. function removeLinkToOriginCategory(text) {
  1164. // If the number of the category is between 10-99
  1165. if(text.substring(6, 7) != "0") {
  1166. categoryOrigin = text.substring(6, 9) - 1;
  1167. }
  1168. // If the number of the category is between 0-9
  1169. else {
  1170. categoryOrigin = text.substring(7, 9) - 1;
  1171. }
  1172. // Remove "a" tag
  1173. linkLi = $("div#move-window ul li").get(categoryOrigin);
  1174. linkText = $("div#move-window ul a").get(categoryOrigin).innerHTML;
  1175. linkLi.innerHTML = linkText;
  1176. }
  1177. // When the user clicks on the "Move" icon, show the move window
  1178. $('.card').on('click', 'span.handle', function() {
  1179. // Show the move window
  1180. $("div#shadow").css("display", "block");
  1181. $("div#move-window").css("display", "block");
  1182. // Assign the idea that is going to be moved
  1183. ideaLi = $(this).parent();
  1184. // Remove the link to the current category, as the idea cannot be moved to its own category where it already is
  1185. removeLinkToOriginCategory($(this).parent().parent().attr("id"));
  1186. });
  1187. // Close the move window
  1188. function closeMoveWindow() {
  1189. // Close the move window
  1190. $("div#shadow").css("display", "none");
  1191. $("div#move-window").css("display", "none");
  1192. }
  1193. // When the user clicks on the "Close" button
  1194. $("div#move-window button.close").on("click", function() {
  1195. // Close the move window
  1196. closeMoveWindow();
  1197. });
  1198. // When the user clicks on a category, move the idea
  1199. function moveIdeaOnClick() {
  1200. $("div#move-window ul a").on("click", function() {
  1201. // If the number of the category is between 10-99
  1202. if($(this).parent().text().trim().substring(1, 2) != ".") {
  1203. categoryDestination = $(this).parent().text().trim().substring(0, 2);
  1204. }
  1205. // If the number of the category is between 0-9
  1206. else {
  1207. categoryDestination = $(this).parent().text().trim().substring(0, 1);
  1208. }
  1209. // Move the idea
  1210. // If the number of the category is between 10-99
  1211. if(categoryDestination > 9) {
  1212. $("ul#field_" + categoryDestination).append(ideaLi);
  1213. // $("ul#field_0" + (categoryOrigin + 1)).parent().find("p.tag-selected-term").css("display", "none");
  1214. }
  1215. // If the number of the category is between 0-9
  1216. else {
  1217. $("ul#field_0" + categoryDestination).append(ideaLi);
  1218. // $("ul#field_0" + (categoryOrigin + 1)).parent().find("p.tag-selected-term").css("display", "none");
  1219. }
  1220. // Close the move window
  1221. closeMoveWindow();
  1222. // Restore links in the move window
  1223. if($("div#move-window li").length > $("div#move-window a").length) {
  1224. $("div#move-window ul").children().remove()
  1225. $("div#move-window ul").append(categoryLis);
  1226. moveIdeaOnClick();
  1227. }
  1228. // Hide "Tag selected term" link in the origin category if there are no ideas left
  1229. if($("ul#field_0" + (categoryOrigin + 1)).children().length === 0) {
  1230. // If the number of the category is between 10-99
  1231. if((categoryOrigin + 1) > 9) {
  1232. $("ul#field_" + (categoryOrigin + 1)).parent().find("p.tag-selected-term").css("display", "none");
  1233. }
  1234. // If the number of the category is between 0-9
  1235. else {
  1236. $("ul#field_0" + (categoryOrigin + 1)).parent().find("p.tag-selected-term").css("display", "none");
  1237. }
  1238. }
  1239. // Show "Tag selected term" link in the destination category
  1240. // If the number of the category is between 10-99
  1241. if((categoryOrigin + 1) > 9) {
  1242. $("ul#field_" + categoryDestination).parent().find("p.tag-selected-term").css("display", "block");
  1243. }
  1244. // If the number of the category is between 0-9
  1245. else {
  1246. $("ul#field_0" + categoryDestination).parent().find("p.tag-selected-term").css("display", "block");
  1247. }
  1248. });
  1249. }
  1250. moveIdeaOnClick();
  1251. /* ================================================
  1252. Moving ideas up
  1253. ================================================= */
  1254. // When the user clicks on the "Up" button
  1255. $('.card').on('click', 'span.move-up', function() {
  1256. // Declarations
  1257. var ideaLiCurrent = $(this).parent();
  1258. var ideaLiPrevious = $(this).parent().prev();
  1259. // Move the idea
  1260. if(ideaLiPrevious.is("li")) {
  1261. ideaLiCurrent.detach();
  1262. ideaLiPrevious.before(ideaLiCurrent);
  1263. }
  1264. });
  1265. /* ================================================
  1266. Moving ideas down
  1267. ================================================= */
  1268. // When the user clicks on the "Down" button
  1269. $('.card').on('click', 'span.move-down', function() {
  1270. // Declarations
  1271. var ideaLiCurrent = $(this).parent();
  1272. var ideaLiNext = $(this).parent().next();
  1273. // Move the idea
  1274. if(ideaLiNext.is("li")) {
  1275. ideaLiCurrent.detach();
  1276. ideaLiNext.after(ideaLiCurrent);
  1277. }
  1278. });
  1279. /* ================================================
  1280. Deleting ideas
  1281. ================================================= */
  1282. // when the cross beside the textarea is clicked (span.remove)
  1283. // remove that list item
  1284. $('.card').on('click', 'span.remove', function() {
  1285. // If there are no ideas left, hide "Tag selected term" link
  1286. if($(this).prev().parent().parent().children().length === 1) {
  1287. $(this).prev().parent().parent().next().css("display", "none");
  1288. }
  1289. // Remove the list item
  1290. $(this).closest('li').remove();
  1291. });
  1292. /* ================================================
  1293. Sortable field ideas
  1294. ================================================= */
  1295. // make items sortable in their fields and between fields
  1296. /*
  1297. $('.sortable').sortable({
  1298. connectWith: '.connectedList',
  1299. placeholder: "sort-placeholder",
  1300. // revert: true
  1301. zIndex: 300 // Or greater than any other relative/absolute/fixed elements and droppables
  1302. });
  1303. */
  1304. /* ================================================
  1305. Sorting and Dragging events
  1306. ================================================= */
  1307. /* sortstart
  1308. sortover
  1309. sortstop */
  1310. // Every textarea in a item needs to get the right name attribute once they have been dropped in another field (so it ends up in the right place in the json file)
  1311. /*
  1312. // Dragging starts
  1313. $(".sortable").on("sortstart", function(event, ui) {
  1314. // WHEN WE SORT CARDS, $(this) ---> the "begining" ul with the class of .sortable
  1315. });
  1316. // Dragging ends: item dropped
  1317. $(".sortable").on("sortstop", function(event, ui) {
  1318. // get the id of the field ul (to set the name attribute of textareas)
  1319. // # mouseleave is the right event for when we release and leave a card mouseup doesn't work properly in this case
  1320. $('.card').on('mouseleave', 'li', function() {
  1321. //$(selector).attr(attribute,value)
  1322. var fieldAttr = $(this).closest('ul.item_list').attr('id');
  1323. // $(this).find('textarea').attr('name', fieldAttr + '[]');
  1324. $(this).find('li.added_item .expandable').attr('name', fieldAttr + '[]');
  1325. });
  1326. });
  1327. */
  1328. /* ================================================
  1329. SAVING THE CANVAS:
  1330. CLICK ON #EXPORT JSON# form button
  1331. ================================================= */
  1332. /* ----------------------------------------------
  1333. When the user clicks on the SAVE CANVAS button
  1334. ----------------------------------------------- */
  1335. $('.canvas-form').on('click', '.json_exp', function() {
  1336. /* ----------------------------------------------
  1337. A: saving the canvas
  1338. as a registered user
  1339. ----------------------------------------------- */
  1340. // php variables are retieved in the header of the canvas index.php as js variables -->
  1341. var name_save_canvas = $('.form-header').find('.proj_title').val();
  1342. var date_save_canvas = $('.form-header').find('.proj_date').val();
  1343. var save_canvas_obj = {
  1344. 'email_save_canvas': email_save_canvas,
  1345. 'name_save_canvas': name_save_canvas,
  1346. 'date_save_canvas': date_save_canvas
  1347. };
  1348. var save_canvas = $.param(save_canvas_obj);
  1349. /* Post the JSON stringified object to the php file
  1350. (the php script will save it in a .json file )*/
  1351. var save_reg_url = "php/save-canvas.php";
  1352. $.post(save_reg_url, { save_canvas: save_canvas }, function(data, status) {
  1353. //the returned data is successful, is the $canvas_id
  1354. var canvas_id = data;
  1355. // send this canvas_id with the next ajax requestedto the php/canvas.php file and use it as the name of the json file to be saved
  1356. // Give the user feedback that the canvas is saved
  1357. if (data !== 400 || data !== 401) {
  1358. if ($('.imp-exp-btn ').find(".save-canvas-feedback") !== null) {
  1359. $('.imp-exp-btn ').find(".save-canvas-feedback").remove();
  1360. }
  1361. $('.canvas-form').find('.imp-exp-btn ').append('<div class="save-canvas-feedback"><p><span class="glyphicon glyphicon-ok" aria-hidden="true"></span>Your canvas is saved in your dashbord</p></div>');
  1362. // remove the canvas is saves message as soon as user changes the canvas
  1363. // $('.canvas-form').on("change keyup", 'textarea', function() {
  1364. $('.canvas-form').on("change keyup", '.expandable', function() {
  1365. $('.imp-exp-btn ').find(".save-canvas-feedback").remove();
  1366. });
  1367. } else {
  1368. $('.canvas-form').find('.imp-exp-btn ').append('<div class="save-canvas-feedback-fail"><p>Oh! We could not save your canvas. Please try again or contact us at hello@ethicscanvas.org</p></div>');
  1369. }
  1370. // For the second AJAX request:
  1371. /* ----------------------------------------------
  1372. B: Exporing the form data json to a file
  1373. and save it on the server
  1374. ----------------------------------------------- */
  1375. // $('#result').text(JSON.stringify($('.canvas-form').serializeObject()));
  1376. // Make the JSON object into a JSON string
  1377. var JSONstrObj = JSON.stringify($('.canvas-form').serializeObject());
  1378. var url = "php/canvas.php";
  1379. /* Post the JSON stringified object to the php file
  1380. (the php script will save it in a .json file )*/
  1381. // also, send the canvas_id and use it for naming the file
  1382. $.post(url, {
  1383. JSONstrObj: JSONstrObj,
  1384. canvas_id: canvas_id
  1385. }, function(data, status) {
  1386. console.log(
  1387. 'Response from php when sending the form json object: \n' +
  1388. 'data:' + data + '\n status: ' + status);
  1389. }).fail(function(jqXHR) {
  1390. console.log("Error " + jqXHR.status + ' ' + jqXHR.statustext);
  1391. });
  1392. }).fail(function(jqXHR) {
  1393. console.log("Error " + jqXHR.status + ' ' + jqXHR.statustext);
  1394. });
  1395. // Prevent the card item list from reseting itself after clicking on the export button (submission). Because the type of the button is submit
  1396. return false;
  1397. });
  1398. /* ================================================
  1399. HANDLING CLICK ON : Share This Canvas BUTTON
  1400. ================================================= */
  1401. $('.canvas-form').on('click', '.share_canvas', function() {
  1402. $('.share_canvas_email').slideDown(1000, function() {
  1403. // SAVE THE PDF AS file
  1404. $.post('mpdf/canvas-pdf-save.php', function(data, status) { }); // save pdf as file
  1405. });
  1406. });
  1407. $('.canvas-form').on('click', '.share_canvas_send', function() {
  1408. var share_email = $('.share_canvas_email').find('input').serialize();
  1409. // This sends a serialized array share_email to the php file. Example: the value of this array will be: share-canvas-email=eternalflame.f%40gmail.com
  1410. $.post('php/share-canvas.php', {
  1411. share_email: share_email
  1412. }, function(data, status) {
  1413. if (data == 200) { // canvas successfully shared
  1414. $('.canvas-form').find('.imp-exp-btn ').append('<div class="save-canvas-feedback"><p><span class="glyphicon glyphicon-ok" aria-hidden="true"></span>Your canvas has been shared by email</p></div>')
  1415. }
  1416. else {
  1417. $('.canvas-form').find('.imp-exp-btn ').append('<div class="save-canvas-feedback"><p><span class="glyphicon glyphicon-ok" aria-hidden="true"></span>Your canvas could not be shared by email</p></div>')
  1418. }
  1419. });
  1420. // slide up the .share_canvas_email area
  1421. $('.share_canvas_email').slideUp();
  1422. });
  1423. /* ================================================
  1424. Controlling the height of divs dynamically
  1425. ================================================= */
  1426. // Call this function after adding a new item and importing
  1427. // $( window ).width(); ->Returns width of browser viewport
  1428. /*
  1429. function fixHeights() {
  1430. // Returns width of browser viewport
  1431. var screenSize = $(window).width();
  1432. //the longest card of the group 1 .masonry-layout7-5
  1433. var longest_1 = $('.masonry-layout7-5').height();
  1434. //the longest card of the group 2 .masonry-layout7-5
  1435. var longest_2 = $('.masonry-layout4').height();
  1436. // --- 5 COL Range ----
  1437. if (screenSize >= 1139) {
  1438. // inforcing a fixed height ".height(longest_1/2)" will create some layout issues when we try to add new items the add item area will go outside the box and the heights don't increase naturally
  1439. // card group 1:
  1440. // $('.field_05,.field_11, .field_07').css('min-height', longest_1 - longest_1 * 5 / 100);
  1441. // $('.field_06,.field_08, .field_12').css('min-height', longest_1 + longest_1 * 5 / 100);
  1442. // $('.field_01, .field_02').css('min-height', longest_1 * 2 + longest_1 * 1 / 100);
  1443. // card group 2:
  1444. // $('.field_03, .field_09, .field_10, .field_04').css('min-height', longest_2 * 2 - longest_2 * 20 / 100);
  1445. $('.field_05,.field_11, .field_07').css('min-height', longest_1 - longest_1 * 20 / 100);
  1446. $('.field_06,.field_08, .field_12').css('min-height', longest_1 - longest_1 * 20 / 100);
  1447. $('.field_01, .field_02').css('min-height', longest_1 + longest_1 * 40 / 100);
  1448. // card group 2:
  1449. $('.field_03, .field_09, .field_10, .field_04').css('min-height', longest_2 - longest_2 * 10 / 100);
  1450. }
  1451. // 4 COL Range //
  1452. else if (screenSize >= 977 && screenSize <= 1138) {
  1453. // card group 1:
  1454. // row 1
  1455. $('.field_01,.field_06, .field_12,.field_08 ').css('min-height', longest_1 + longest_2 * 20 / 100);
  1456. // row 2
  1457. $('.field_05,.field_11, .field_07,.field_02 ').css('min-height', longest_1 + longest_2 * 20 / 100);
  1458. // card group 2:
  1459. // row 3
  1460. $('.field_03, .field_09, .field_10, .field_04').css('min-height', longest_2 * 2 - longest_2 * 20 / 100);
  1461. } else if (screenSize >= 920 && screenSize <= 976) {
  1462. // card group 1:
  1463. // row 1
  1464. $('.field_01,.field_06, .field_12,.field_08 ').css('min-height', longest_1 + longest_2 * 20 / 100);
  1465. // row 2
  1466. $('.field_05,.field_11, .field_07,.field_02 ').css('min-height', longest_1 + longest_2 * 20 / 100);
  1467. // card group 2:
  1468. // row 3
  1469. $('.field_03, .field_09, .field_10, .field_04').css('min-height', longest_2 * 2 - longest_2 * 20 / 100);
  1470. } else if (screenSize >= 485 && screenSize <= 919) {
  1471. // else if (500 <= screenSize < 920) {
  1472. // card group 1:
  1473. $('.field_01,.field_06, .field_12,.field_08 ').css('min-height', longest_1 * 80 / 100);
  1474. $('.field_05,.field_11, .field_07,.field_02 ').css('min-height', longest_1 * 80 / 100);
  1475. // card group 2:
  1476. $('.field_03, .field_09, .field_10, .field_04').css('min-height', longest_2 * 80 / 100);
  1477. // --- 1 COL Range ----
  1478. } else {
  1479. // card group 1:
  1480. $('.field_01,.field_06, .field_12,.field_08 ').css('min-height', longest_1 * 20 / 100);
  1481. $('.field_05,.field_11, .field_07,.field_02 ').css('min-height', longest_1 * 20 / 100);
  1482. // card group 2:
  1483. $('.field_03, .field_09, .field_10, .field_04').css('min-height', longest_2 * 20 / 100);
  1484. }
  1485. }
  1486. function fixHeights() {
  1487. // Returns width of browser viewport
  1488. var screenSize = $(window).width();
  1489. var field01 = $("div.field_01");
  1490. var field02 = $("div.field_02");
  1491. var field03 = $("div.field_03");
  1492. var field04 = $("div.field_04");
  1493. var field05 = $("div.field_05");
  1494. var field06 = $("div.field_06");
  1495. var field07 = $("div.field_07");
  1496. var field08 = $("div.field_08");
  1497. var field09 = $("div.field_09");
  1498. // Set the height of every field
  1499. var heightOfField01 = field01.height();
  1500. var heightOfField03 = field03.height();
  1501. var heightOfField04 = field04.height();
  1502. var heightOfField03And04 = field03.height() + field04.height();
  1503. var heightOfField09 = field09.height();
  1504. var heightOfField05 = field05.height();
  1505. var heightOfField06 = field06.height();
  1506. var heightOfField05And06 = field05.height() + field06.height();
  1507. var heightOfField02 = field02.height();
  1508. // --- 5 COL Range ---
  1509. if (screenSize >= 935) {
  1510. var longestInGroup1 = Math.max(heightOfField01, heightOfField03, heightOfField04, heightOfField03And04, heightOfField09, heightOfField05, heightOfField06, heightOfField05And06, heightOfField02);
  1511. console.log(longestInGroup1);
  1512. // Field group 1
  1513. switch(longestInGroup1) {
  1514. case heightOfField01:
  1515. $(".field_04").css("min-height", longestInGroup1 + 10);
  1516. $(".field_09").css("min-height", longestInGroup1 + 448);
  1517. $(".field_06").css("min-height", longestInGroup1 + 10);
  1518. $(".field_02").css("min-height", longestInGroup1 + 448);
  1519. break;
  1520. case heightOfField03:
  1521. // Code goes here
  1522. break;
  1523. case heightOfField04:
  1524. // Code goes here
  1525. break;
  1526. case heightOfField03And04:
  1527. // Code goes here
  1528. break;
  1529. case heightOfField09:
  1530. // Code goes here
  1531. break;
  1532. case heightOfField05:
  1533. // Code goes here
  1534. break;
  1535. case heightOfField06:
  1536. // Code goes here
  1537. break;
  1538. case heightOfField05And06:
  1539. // Code goes here
  1540. break;
  1541. case heightOfField02:
  1542. // Code goes here
  1543. break;
  1544. default:
  1545. break;
  1546. }
  1547. }
  1548. // --- 4 COL Range ---
  1549. else if (screenSize >= 935 && screenSize <= 991) {
  1550. // Field group 1
  1551. // Code goes here
  1552. // Field group 2
  1553. // Code goes here
  1554. }
  1555. else if (screenSize >= 992 && screenSize <= 1153) {
  1556. // Field group 1
  1557. // Code goes here
  1558. // Field group 2
  1559. // Code goes here
  1560. }
  1561. // --- 2 COL Range ---
  1562. else if (screenSize >= 500 && screenSize <= 934) {
  1563. // Field group 1
  1564. // Code goes here
  1565. // Field group 2
  1566. // Code goes here
  1567. }
  1568. // --- 2-5 COL Range ---
  1569. if (screenSize >= 500) {
  1570. var longestInGroup2;
  1571. // Field group 2
  1572. // Determine the longest Field in group 2
  1573. if(field07.height() < field08.height()) {
  1574. longestInGroup2 = field08;
  1575. }
  1576. else {
  1577. longestInGroup2 = field07;
  1578. }
  1579. if(longestInGroup2 === field07) {
  1580. $(".field_08").css("min-height", longestInGroup2.height() + 10);
  1581. }
  1582. else {
  1583. $(".field_07").css("min-height", longestInGroup2.height() + 10);
  1584. }
  1585. }
  1586. // --- 1 COL Range ---
  1587. // Field group 1
  1588. // Code goes here
  1589. // Field group 2
  1590. // Code goes here
  1591. }
  1592. */
  1593. /*
  1594. new ResizeSensor($(".field_01, .field_02, .field_03, .field_04, .field_05, .field_06, .field_07, .field_08, .field_09"), function() {
  1595. // fixHeights();
  1596. });
  1597. */
  1598. });