canvas.js 78 KB

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