canvas.js 93 KB

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