/* Contains all the Javascript logic of the canvas and its main features: save, export and share */
$(document).ready(function() {
/* ================================================
Miscellaneous
================================================= */
// Declare the currently loaded tags belonging to the user
var tags = [];
// Declare canvas id
var canvasId = $("input[name='canvas_id']").val();
// Declare current user
var username = $("input[name='username']").val();
// Total number of collaborators
var numberOfCollaborators = 0;
// Fixes bug when added item field zooms on tag click
var tagWindowIsOpen = false;
// This piece of code is for making the column-count and column-gap CSS to work in Firefox
/*
document.getElementById("7-5-col-layout").style.MozColumnCount = "7";
document.getElementById("2-col-layout").style.MozColumnCount = "2";
*/
// Prevent pressing ENTER on Project Title from submitting the form
$('.proj_title').keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
});
/* ================================================
Generate canvas id
================================================= */
// Generate a random string of a specific length to be used as canvas_id
if(canvasId === "") {
var i = 0;
var length = 10;
var characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var charactersLength = characters.length;
var randomString = "";
var minimum = 0;
var maximum = charactersLength - 1;
for (i = 0; i < length; i++) {
randomString += characters[Math.floor(Math.random() * (maximum - minimum + 1)) + minimum];
}
// Save canvas ID
canvasId = randomString;
$("input[name='canvas_id']").val(randomString);
}
/* ================================================
Rearrange fields numerically if 1 column is displayed
================================================= */
// Declarations
var groupOneLayout = $("#7-5-col-layout");
var groupTwoLayout = $("#4-col-layout");
var field01 = $("#panel_01");
var field03 = $("#panel_03");
var field04 = $("#panel_04");
var field09 = $("#panel_09");
var field05 = $("#panel_05");
var field06 = $("#panel_06");
var field02 = $("#panel_02");
var field07 = $("#panel_07");
var field08 = $("#panel_08");
// var field10 = $("#panel_10");
var isRearranged = false;
// Rearrange the fields to suit mobile
function rearrangeFields() {
field01.detach();
field03.detach();
field04.detach();
field09.detach();
field05.detach();
field06.detach();
field02.detach();
field07.detach();
field08.detach();
// field10.detach();
groupOneLayout.append(field01);
groupOneLayout.append(field02);
groupOneLayout.append(field03);
groupOneLayout.append(field04);
groupOneLayout.append(field05);
groupOneLayout.append(field06);
groupOneLayout.append(field07);
groupOneLayout.append(field08);
groupOneLayout.append(field09);
// groupOneLayout.append(field10);
}
// Rearrange the fields according to their original order
function rearrangeFieldsOriginal() {
field01.detach();
field02.detach();
field03.detach();
field04.detach();
field05.detach();
field06.detach();
field07.detach();
field08.detach();
field09.detach();
// field10.detach();
groupOneLayout.append(field01);
groupOneLayout.append(field03);
groupOneLayout.append(field04);
groupOneLayout.append(field09);
groupOneLayout.append(field05);
groupOneLayout.append(field06);
groupOneLayout.append(field02);
groupTwoLayout.append(field07);
groupTwoLayout.append(field08);
// groupTwoLayout.append(field10);
}
// If the web page is opened on a mobile
if ($(window).width() <= 499) {
rearrangeFields();
}
// When resizing the window
$(window).on("resize", function() {
if (isRearranged === false && $(window).width() <= 499) {
rearrangeFields();
isRearranged = true;
}
else if(isRearranged === true && $(window).width() >= 500) {
rearrangeFieldsOriginal();
isRearranged = false;
}
});
/* ================================================
Collaborators window
================================================= */
// If the user clicks on the "Collaborators" button, show the collaborators window
$("div#collaborators button").on("click", function() {
// Show the collaborators window
$("div#shadow").css("display", "block");
$("div#collaborators-window").css("display", "block");
});
// Close the collaborators window
function closeCollaboratorsWindow() {
// Close the collaborators window
$("div#shadow").css("display", "none");
$("div#collaborators-window").css("display", "none");
}
// If the user clicks on the "Close" button
$("div#collaborators-window button.close").on("click", function() {
// Close the collaborators window
closeCollaboratorsWindow();
$("div#collaborators-window input[type='email']").val("Please enter an email address...");
$("div#username-already-exists").hide();
$("div#enter-valid-email").hide();
});
// If the user clicks on the "Remove" button
function removeCollaboratorOnClick() {
// If the user clicks on the "Remove" button
$("div#collaborators-window td:nth-child(4) span").on("click", function() {
// Remove the collaborator
var collaborator = $(this).parent().prev().text();
var currentRow = $(this).parent().parent();
// AJAX
$.ajax({
timeout: 5000,
dataType: "text",
type: "post",
data: {
"canvas_id": canvasId,
"username": username,
"collaborator": collaborator
},
url: "php/remove-collaborator.php",
success: function() {
currentRow.remove();
numberOfCollaborators--;
},
error: function(xhr) {
console.log(xhr.statusText);
}
});
});
}
// Show only active collaborators or show all
function updateCollaboratorsView() {
// If the user only wants to see active collaborators
if($("input[name='show-only-active']").is(":checked")) {
// For every collaborator
$("div#collaborators-window tr").each(function() {
// If this collaborator is offline
if($(this).find("td:nth-child(1)").html() === "") {
// Hide this collaborator
$(this).css("display", "none");
}
});
/*
// Show empty row if no collaborator is active
if($("div#collaborators-window tr").not(":hidden").length === 1) {
$("div#collaborators-window table").append("
| | | |
");
}
*/
}
// If the user wants to see all active collaborators
else {
// For every collaborator
$("div#collaborators-window tr").each(function() {
// Show this collaborator
$(this).css("display", "table-row");
});
}
}
// If the user checks the "Show only active collaborators" checkbox
$("input[name='show-only-active']").on("change", function() {
updateCollaboratorsView();
});
// If the user enters the text field
$("div#collaborators-window input[type='email']").on("focusin", function() {
if($(this).val() === "Please enter an email address...") {
$(this).val("");
$(this).css("color", "rgb(51, 51, 51)");
}
});
// If the user leaves the text field
$("div#collaborators-window input[type='email']").on("focusout", function() {
if($(this).val() === "") {
$(this).val("Please enter an email address...");
$(this).css("color", "rgb(117, 117, 117)");
}
});
// If the user clicks on "Add collaborator"
$("div#collaborators-window button#add-collaborator").on("click", function() {
// Declarations
var collaborator = $("div#collaborators-window input[type='email']").val();
// AJAX
$.ajax({
timeout: 5000,
dataType: "text",
type: "post",
data: {
"canvas_id": canvasId,
"username": username,
"collaborator": collaborator
},
url: "php/add-collaborator.php",
success: function(returnData) {
$("div#username-already-exists").hide();
$("div#enter-valid-email").hide();
if(returnData == 1) {
$("div#collaborators-window input[type='email']").val("Please enter an email address...");
$("div#collaborators-window input[type='email']").css("color", "rgb(117, 117, 117)");
updateActiveCollaborators();
}
else if(returnData == 2) {
$("div#username-already-exists").show();
}
else {
$("div#enter-valid-email").show();
}
numberOfCollaborators++;
},
error: function(xhr) {
console.log(xhr.statusText);
}
});
});
/* ================================================
Collaborative features
================================================= */
// Update active collaborators
function updateActiveCollaborators() {
// AJAX
$.ajax({
type: "POST",
url: "php/update-active-collaborators.php",
dataType: "JSON",
data: {
"canvas_id": canvasId,
"username": username
},
timeout: 5000,
success: function(returnData) {
// Declarations
var htmlToAppend = "Active | Name | Username | Remove |
";
numberOfCollaborators = returnData.length;
// If the total number of invited collaborators is greater than 0
if(returnData.length > 0) {
// Declarations
var index = 0;
// While there still are collaborators to append
while(index < returnData.length) {
htmlToAppend += "";
if(returnData[index]["active"] === 1) {
htmlToAppend += "";
}
htmlToAppend += " | " + returnData[index]["name"] + " | " + returnData[index]["collaborator"] + " | |
";
index++;
}
// console.log(returnData);
// Append tags
$("div#collaborators-window table").html(htmlToAppend);
// Update the button to open the collaborators window
$("div#collaborators button span").text("Collaborators (" + $("td.collaborators-active span").length + " active)");
// Toggle the text explaining that the canvas is saved automatically
$("p#save-canvas").hide();
$("p#saved-automatically").show();
// If the user clicks on the "Remove" button
removeCollaboratorOnClick();
// Show only active collaborators or show all
updateCollaboratorsView();
}
else {
// Toggle the text explaining that the canvas is saved automatically
$("p#save-canvas").show();
$("p#saved-automatically").hide();
}
},
error: function(xhr) {
console.log(xhr.statusText);
}
});
}
updateActiveCollaborators();
window.setInterval(function() {
updateActiveCollaborators();
}, 7000);
/* ================================================
"Jump to" functions
================================================= */
var hasScrolledDown = false;
function showFixedJumpedTo() {
// Add classes
$("div.jump-to-click-area").addClass("jump-to-click-area-toggle");
$("div.jump-to").addClass("jump-to-toggle");
$("div.jump-to-list").addClass("jump-to-list-toggle");
$("img.jump-to-img").addClass("jump-to-img-toggle");
// If the user clicks on a link and scrolls up the page, hide list
$("div.jump-to-list").hide();
}
function showInitialJumpedTo() {
// Toggle classes
$("div.jump-to-click-area").removeClass("jump-to-click-area-toggle");
$("div.jump-to").removeClass("jump-to-toggle");
$("div.jump-to-list").removeClass("jump-to-list-toggle");
$("img.jump-to-img").removeClass("jump-to-img-toggle");
// If the user clicks on a link and scrolls up the page, toggle list
$("div.jump-to-list").show();
hasScrolledDown = false;
}
// If the user scrolls down, change "position" to "fixed"
$(window).scroll(function() {
// If the web page is opened on a mobile
if($(window).width() <= 499) {
// Declarations
var scrollPosition = $(window).scrollTop();
var jumpToPosition = $("div.jump-to").offset().top;
// If the user has scrolled down to "Jump To..."
if(hasScrolledDown === false && scrollPosition >= jumpToPosition) {
showFixedJumpedTo();
// Update scroll position
$(window).scrollTop($("div.saved-tags").offset().top - 300);
hasScrolledDown = true;
}
// If the user has scrolled up to the top
else if(hasScrolledDown === true && scrollPosition === 0) {
showInitialJumpedTo();
}
}
// If the web page is not open on a mobile
else {
showInitialJumpedTo();
}
});
// If the user clicks on "Jump to", show menu
$("div.jump-to-click-area").on("click", function() {
// Toggle the menu
$("div.jump-to div div").slideToggle(300);
// Rotate arrow
// $("div.jump-to span.jump-to-arrow").toggleClass("rotate-arrow-180");
// $("div.jump-to span.jump-to-arrow").toggleClass("rotate-arrow-0");
$("img.jump-to-img").toggleClass("jump-to-arrow-90");
$("img.jump-to-img").toggleClass("jump-to-arrow-0");
return false;
});
// If the user clicks on a menu item
$("div.jump-to ul a").on("click", function() {
// Declarations
var chosenLiIndex = $(this).parent().index();
var chosenFieldPosition;
var scrollPositionNew;
// Detect the scroll position of the chosen field
// If the user has chosen the list item 0
if(chosenLiIndex === 0) {
chosenFieldPosition = $("div.saved-tags").offset().top;
}
// If the user has chosen the list item 1-9
else if(chosenLiIndex >= 1 && chosenLiIndex <= 9) {
chosenFieldPosition = $("div.field_0" + chosenLiIndex).offset().top;
}
// If the user has chosen the list item 10 or higher
else {
chosenFieldPosition = $("div.field_" + chosenLiIndex).offset().top;
}
// If the user hasn't scrolled down
if(hasScrolledDown === false) {
console.log(chosenLiIndex);
// Set the new scroll position
scrollPositionNew = chosenFieldPosition - $("div.jump-to").height() - 89;
// Add classes
showFixedJumpedTo();
// Update scroll position
hasScrolledDown = true;
}
// If the user has scrolled down to "Jump To..."
else {
// Set the new scroll position
scrollPositionNew = chosenFieldPosition - 58;
// Toggle the menu
$("div.jump-to-list").slideToggle(300);
// Rotate arrow
// $("div.jump-to span.jump-to-arrow").toggleClass("rotate-arrow-90");
// $("div.jump-to span.jump-to-arrow").toggleClass("rotate-arrow-0");
$("img.jump-to-img").toggleClass("jump-to-arrow-90");
$("img.jump-to-img").toggleClass("jump-to-arrow-0");
}
// Apply the new scroll position
$(window).scrollTop(scrollPositionNew);
return false;
});
/* ================================================
Show tooltip for every category
================================================= */
$("a[data-toggle='tooltip']").tooltip({container: "body"});
$("a[data-toggle='tooltip']").on("click", function() {
return false;
});
/* ================================================
Remove all tags from all fields
================================================= */
// Remove all tags from all fields
function removeTags() {
// AJAX
$.ajax({
type: "POST",
url: "php/get-tags.php",
dataType: "JSON",
data: {
"canvas_id": canvasId
},
timeout: 5000,
success: function(returnData) {
// Declarations
var loopCounter = 0;
tags = returnData;
// For every added item
$("li.added_item .expandable").each(function() {
$(this).html($(this).text());
/*
var thisDiv = $(this); // Delete the declaration (because it's ugly!)
// For every tag in the database that belongs to the active user
for(t in tags) {
// If the current tag exists in the textarea
if(thisDiv.html().indexOf("") != -1) { // Why not a while loop?
// Delete the tag
var text = thisDiv.html();
text = thisDiv.text().replace("" + tags[loopCounter] + "", tags[loopCounter]);
thisDiv.html(text);
}
loopCounter++;
}
*/
});
// If no tags have been added, reset text explaining so
if(tags.length === 0) {
$("div.saved-tags p").html("You haven't added any tags yet.");
}
},
error: function(xhr) {
console.log(xhr.statusText);
}
});
/*
// 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
// Declarations
var loopCounter = 0;
// For every added item
$("li.added_item .expandable").each(function() {
var thisDiv = $(this); // Delete the declaration (because it's ugly)
// For every tag that belongs to the active user
for(t in tags) {
// If the current tag exists in the textarea
if(thisDiv.html().indexOf("") != -1) {
// Delete the tag
var text = thisDiv.html();
text = thisDiv.text().replace("" + tags[loopCounter] + "", tags[loopCounter]);
thisDiv.html(text);
}
loopCounter++;
}
});
console.log(tags);
console.log(tags.length);
// If no tags have been added, reset text explaining so
if(tags.length === 0) {
$("div.saved-tags p").html("You haven't added any tags yet.");
}
*/
}
/* ================================================
Get the user's tags from the database and apply them on the canvas
================================================= */
// Apply tags (Incoming parameter is an array with every tag from the database belonging to the active user)
function updateTags() {
// Apply tags on the canvas
/*
IMPORTANT! A timer was needed in order to solve several bugs related to tags not being applied on the canvas.
Should this still become an issue later on, try increasing the amount of milliseconds.
*/
window.setTimeout(function() {
// For every added item
$("li.added_item .expandable").each(function() {
// Declarations
// var instanceCounter;
var loopCounter = 0;
var text = $(this).text();
// instanceCounter = $(text + ":contains('test')").length;
// $('#parentDiv').find(":contains('No Records Found')").length
// console.log(instanceCounter);
// For every tag in the database that belongs to the active user
for(t in tags) {
// instanceCounter = ($(this).text().match(/aaa/g) || []).length;
// Apply the tag for every instance of the current term
// instanceCounter = text.indexOf(tags[loopCounter]);
// while(instanceCounter > -1) {
// text = text.replace(tags[loopCounter], "" + tags[loopCounter] + "");
text = text.replace(tags[loopCounter], "" + tags[loopCounter] + "");
// instanceCounter = text.indexOf(tags[loopCounter], instanceCounter + 1);
// }
loopCounter++;
}
$(this).html(text);
});
// Show the tag window on tag click
showTagWindowOnTagClick();
}, 100);
// Populate "Saved Tags"
var loopCounter = 0;
var savedTags = $("div.saved-tags p");
savedTags.html("");
for(t in tags) {
if(savedTags.html() === "You haven't added any tags yet.") {
savedTags.html("");
}
savedTags.append("" + tags[loopCounter] + "").append(" ");
loopCounter++;
}
}
// Get the tags from the database
function getTags() {
// AJAX
$.ajax({
type: "POST",
url: "php/get-tags.php",
dataType: "JSON",
data: {
"canvas_id": canvasId
},
timeout: 5000,
success: function(returnData) {
if(returnData.length > 0) {
// Assign returnData to the tags variable
tags = returnData;
// Update tags on the canvas
updateTags();
}
},
error: function(xhr) {
console.log(xhr.statusText);
}
});
}
/* ================================================
Load tags if the user is logged in
================================================= */
if($("input[name='name']").val() != "") {
getTags();
}
/* ================================================
Tag window functions
================================================= */
// Declarations
// var textarea = $("div#tag-window textarea#tag-description");
var textareaHasBeenChanged = false;
var tag;
// var tagIsNew = false;
var username = $("input[name='username']").val();
// Check if the tag is new
function hideDeleteTagIfTagIsNew() {
// Declarations
var tagToAJAX = tag;
// AJAX
$.ajax({
type: "POST",
url: "php/check-if-tag-exists.php",
dataType: "text",
data: {
"tag": tagToAJAX,
"canvas_id": canvasId
},
timeout: 5000,
success: function(returnData) {
// If the current tag does not exist in the database
if(returnData === "") {
// Hide "Delete tag" button
$("div#tag-window button#delete-tag").css("display", "none");
// Hide "Similar tags"
// $("div#tag-window h2.similar-tags").css("display", "none");
// The tag is new
// tagIsNew = true;
}
// If the current tag exists in the database
else {
// Show "Delete tag" button
$("div#tag-window button#delete-tag").css("display", "inline");
// Show "Similar tags"
// $("div#tag-window h2.similar-tags").css("display", "block");
}
},
error: function(xhr) {
console.log(xhr.statusText);
}
});
}
// Updating the remaining characters information
function updateRemainingCharacters() {
// Declarations
var length = $("div#tag-window textarea#tag-description").val().length; // Retrieving from "Please enter a description..."
var maxLength = 200;
/*
var length;
if(description != "") {
length = description;
}
else {
length = $("div#tag-window textarea#tag-description").val().length;
}
*/
// Update length
length = maxLength - length;
// Show the remaining characters
$("div#tag-window span.chars").text(length);
}
// Get the description for the selected tag
function getDescriptionForSelectedTag() {
// Declarations
var tagToAJAX = tag;
// AJAX
$.ajax({
type: "POST",
url: "php/get-description-for-selected-tag.php",
dataType: "text",
data: {
"tag": tagToAJAX,
"canvas_id": canvasId
},
timeout: 5000,
success: function(returnData) {
if(returnData != "") {
// Update description field with the description for the selected tag
$("div#tag-window textarea#tag-description").val(returnData);
// Update remaining characters
updateRemainingCharacters();
}
textareaHasBeenChanged = true;
},
error: function(xhr) {
console.log(xhr.statusText);
}
});
}
// Get similar tags by other users
function getSimilarTags() {
// Declarations
var tagToAJAX = tag;
// AJAX
$.ajax({
type: "POST",
url: "php/get-similar-tags.php",
dataType: "JSON",
data: {
"tag": tagToAJAX,
"canvas_id": canvasId
},
timeout: 5000,
success: function(returnData) {
// Reset similar tags if similar tags are to be showed again
$("p.similar-tags-tag").remove();
$("p.similar-tags-description").remove();
$("p.similar-tags-canvas-name").remove();
// Declarations
var htmlToAppend = "";
// If similar tags exist
if(returnData.length > 0) {
// Declarations
var index = 0;
// While there still are tags to append
while(index < returnData.length) {
htmlToAppend += "" + returnData[index]["tag"] + "
"
+ "" + returnData[index]["description"] + "
"
+ "from " + returnData[index]["canvas_name"] + "
";
// "from " + returnData[index]["canvas_name"] + "
";
index++;
}
// Append tags
$("div#tag-window h2.similar-tags").after(htmlToAppend);
$("p.similar-tags-description-none").css("display", "none");
// Update tags on the canvas
// updateTags();
}
else {
// Show the message saying that there are no similar tags to show
$("p.similar-tags-description-none").css("display", "block");
}
},
error: function(xhr) {
console.log(xhr.statusText);
}
});
}
// Close the tag window
function closeTagWindow() {
tagWindowIsOpen = false;
$("div#shadow").css("display", "none");
$("div#tag-window").css("display", "none");
}
// Show the tag window
function showTagWindow() {
// Show the tag window
$("div#shadow").css("display", "block");
$("div#tag-window").css("display", "block");
// Update the header
$("div#tag-window h1").html(" " + tag);
// Move the window to the centre of the screen
/*
The code below should be working, but the height of the second selector seems completely wrong!
var middle = (document.body.clientHeight / 2) - ($("div#tag-window").height() / 2);
$("div#tag-window").css("top", middle);
*/
// Check if the tag is new
hideDeleteTagIfTagIsNew();
// Get the description for the selected tag
getDescriptionForSelectedTag();
// Get tags by other users from the database
// window.setTimeout(getSimilarTags(), 100);
getSimilarTags();
// Update remaining characters in case description is loaded
updateRemainingCharacters();
// If a description hasn't been entered
if($("div#tag-window textarea#tag-description") !== "Please enter a description..." && textareaHasBeenChanged !== true) {
// Reset the remaining characters information
$("div#tag-window span.chars").text("200");
}
}
// If the user presses a key in the description textarea
$("div#tag-window textarea#tag-description").on("keyup", function() {
// Update remaining characters
updateRemainingCharacters();
});
// If the user clicks on the "Save tag" button
$("div#tag-window #save-tag").on("click", function() {
// Declarations
var description = $("div#tag-window textarea#tag-description").val();
var tagToAJAX = tag;
// If a description has been entered
if(description != "" && description != "Please enter a description...") {
// AJAX
$.ajax({
timeout: 5000,
dataType: "text",
type: "post",
data: {
"tag": tagToAJAX,
"description": description,
"canvas_id": canvasId
},
url: "php/save-tag.php",
success: function() {
textareaHasBeenChanged = true;
// Get the user's tags from the database and apply them on the canvas
getTags();
},
error: function(xhr) {
console.log(xhr.statusText);
}
});
// Close the tag window
closeTagWindow();
}
// tagIsNew = false;
});
// If the user clicks on the "Close" button
$("div#tag-window button.close").on("click", function() {
// Close the tag window
closeTagWindow();
});
// If the user clicks on the "Delete tag" button
$("div#tag-window #delete-tag").on("click", function() {
// Declarations
var tagToAJAX = tag;
// AJAX
$.ajax({
timeout: 5000,
dataType: "text",
type: "post",
data: {
"tag": tagToAJAX,
"canvas_id": canvasId
},
url: "php/delete-tag.php",
success: function() {
// Remove all tags from all fields
removeTags();
// Get the user's tags from the database and apply them on the canvas
getTags();
},
error: function(xhr) {
console.log(xhr.statusText);
}
});
// Close the tag window
closeTagWindow();
});
// If the user focuses in the textarea
$("div#tag-window textarea#tag-description").on("focusin", function() {
// Declarations
var description = $("div#tag-window textarea#tag-description").val();
// If a description hasn't been entered
// if(textareaHasBeenChanged === false) {
if(description === "Please enter a description...") {
// Empty the description textarea
$("div#tag-window textarea#tag-description").val("");
}
});
// If the user focuses out the textarea
$("div#tag-window textarea#tag-description").on("focusout", function() {
// Declarations
var description = $("div#tag-window textarea#tag-description").val();
// If a description hasn't been entered
// if(textareaHasBeenChanged === false) {
if(description === "") {
// Reset the description textarea
$("div#tag-window textarea#tag-description").val("Please enter a description...");
}
});
/* ================================================
If the user clicks on a tag, show the tag window
================================================= */
// If the user clicks on a tag
function showTagWindowOnTagClick() {
$("a.tag").on("click", function() {
// Declarations
tag = $(this).text();
// If the user is logged in
if($("input[name='username']").val() != "") {
tagWindowIsOpen = true;
// Show the tag window
showTagWindow();
}
else {
// Show a dialog
$("div#shadow").css("display", "block");
$("div#dialog-log-in").css("display", "block");
}
});
}
/*
// Mouse-enabled devices
$("tag").mouseenter(function() {
timer = setTimeout(function() {
showTagWindow(); // showTagWindow needs a parameter!
}, 400);
}).mouseleave(function() {
clearTimeout(timer);
});
// Touch devices
try {
document.createEvent("TouchEvent");
$("a.tag").on("click", showTagWindow()); // showTagWindow needs a parameter!
return true;
}
catch(e) {
return false;
}
*/
/* ================================================
Save added idea on Enter press
================================================= */
function saveAddedIdeaOnEnterPress(li) {
$("li.added_item textarea.expandable").on("keydown", function(event) {
if(event.which === 13) {
event.preventDefault();
// Declarations
var li = $(this).parent();
var textElement;
var textElementWidth;
// Replace textarea with a div
$(this).replaceWith(
"" + $(this).val() + "
"
);
// Remember the text element
textElement = li.find(".expandable");
// Remember the width of the text element
textElementWidth = textElement.width();
// Update tags on the canvas
// window.setTimeout(updateTags(), 100);
updateTags();
// Zoom out animation
if(textElementWidth >= 0 && textElementWidth <= 250) {
textElement.addClass("zoom-out-regular");
}
else if(textElementWidth >= 251 && textElementWidth <= 500) {
textElement.addClass("zoom-out-less");
}
else if(textElementWidth >= 501) {
textElement.addClass("zoom-out-least");
}
textElement.css("background-color", "rgba(255, 255, 255, 0.75)");
textElement.css("-ms-transform", "scale(1)");
textElement.css("-webkit-transform", "scale(1)");
textElement.css("transform", "scale(1)");
// If no tags have been added, reset text explaining so
if(tags.length === 0) {
$("div.saved-tags p").html("You haven't added any tags yet.");
}
toggleTextElementOnFocus();
}
});
}
/* ================================================
Toggle textarea.expandable/div.expandable on edit
================================================= */
function toggleTextElementOnFocus() {
// If the user clicks on the added ideas
$("li.added_item .expandable").on("click", function() {
if(tagWindowIsOpen === false) {
var li = $(this).parent();
var textElement;
// var textElementHTML;
var textElementWidth;
// Replace div with a textarea
$(this).replaceWith(
""
);
// Remember the text element
textElement = li.find(".expandable");
/*
// Fix the bug that tags still might appear
textElementHTML = textElement.html();
while(textElementHTML.indexOf("") != -1) {
textElementHTML = textElementHTML.replace("", "");
textElementHTML = textElementHTML.replace("", "");
}
textElement.html(textElementHTML);
*/
// Remember the width of the text element
textElementWidth = textElement.width();
// Focus immediately on click instead of having to click on the element a second time
textElement.focus();
// Zoom in animation
if(textElementWidth >= 0 && textElementWidth <= 250) {
textElement.addClass("zoom-in-regular");
textElement.css("background-color", "rgba(255, 255, 255, 1)");
textElement.css("-ms-transform", "scale(1.02)");
textElement.css("-webkit-transform", "scale(1.02)");
textElement.css("transform", "scale(1.02)");
}
else if(textElementWidth >= 251 && textElementWidth <= 600) {
textElement.addClass("zoom-in-less");
textElement.css("background-color", "rgba(255, 255, 255, 1)");
textElement.css("-ms-transform", "scale(1.01)");
textElement.css("-webkit-transform", "scale(1.01)");
textElement.css("transform", "scale(1.01)");
}
else if(textElementWidth >= 601) {
textElement.addClass("zoom-in-least");
textElement.css("background-color", "rgba(255, 255, 255, 1)");
textElement.css("-ms-transform", "scale(1.005)");
textElement.css("-webkit-transform", "scale(1.005)");
textElement.css("transform", "scale(1.005)");
}
// Save added idea on Enter press
saveAddedIdeaOnEnterPress(li);
// Replace textarea with a div
$("li.added_item textarea.expandable").on("focusout", function() {
// Declarations
var li = $(this).parent();
var textElement;
var textElementWidth;
// Replace textarea with a div
$(this).replaceWith(
"" + $(this).val() + "
"
);
// Remember the text element
textElement = li.find(".expandable");
// Remember the width of the text element
textElementWidth = textElement.width();
// Update tags on the canvas
// window.setTimeout(updateTags(), 100);
updateTags();
// Zoom out animation
if(textElementWidth >= 0 && textElementWidth <= 250) {
textElement.addClass("zoom-out-regular");
}
else if(textElementWidth >= 251 && textElementWidth <= 500) {
textElement.addClass("zoom-out-less");
}
else if(textElementWidth >= 501) {
textElement.addClass("zoom-out-least");
}
textElement.css("background-color", "rgba(255, 255, 255, 0.75)");
textElement.css("-ms-transform", "scale(1)");
textElement.css("-webkit-transform", "scale(1)");
textElement.css("transform", "scale(1)");
// If no tags have been added, reset text explaining so
if(tags.length === 0) {
$("div.saved-tags p").html("You haven't added any tags yet.");
}
toggleTextElementOnFocus();
});
}
});
}
/*
// ================================================
If the user types a new character in the added idea field, add tag if a term could be found
================================================= //
// 8an33j24
function applyTagOnTypeMatch() {
$("li.added_item .expandable").on("focusin", function() {
// If the user presses a key in the description textarea
$("li.added_item .expandable").on("keyup", function() {
if(event.which !== 9 && // Tab
event.which !== 16 && // Shift
event.which !== 37 && // Left
event.which !== 38 && // Up
event.which !== 39 && // Right
event.which !== 40) { // Down
// Declarations
var bugCounter = 0;
var loopCounter = 0;
var tagLinkToSearch;
var tagLinkHits;
var tagTextToSearch;
var tagTextHits;
var text = $(this).html();
// Fix the bug that triggers the event twice
if(!bugCounter > 0) {
// console.log("tagTextHits: " + tagTextHits);
// console.log("tagLinkHits: " + tagLinkHits);
// For every tag that belongs to the active user
for(t in tags) {
if($(this).html().indexOf(tags[loopCounter]) != -1) {
// Search for the tag inside the added idea as a link
tagLinkToSearch = text.match(tags[loopCounter] + ""); // match() can only count to one instance (67hi9nt3)
// Search for the tag inside the added idea as plain text
tagTextToSearch = text.match(tags[loopCounter]); // match() can only count to one instance (67hi9nt3)
// If the tag exists inside the added idea as a link
if(tagLinkToSearch !== null) {
// tagLinkHits = 1
tagLinkHits = tagLinkToSearch.length;
}
else {
// tagLinkHits = 0
tagLinkHits = 0;
}
// If the tag exists inside the added idea as plain text
if(tagTextToSearch !== null) {
// tagTextHits = 1
tagTextHits = tagTextToSearch.length;
}
else {
// tagTextHits = 0
tagTextHits = 0;
}
// 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
// Change "tagTextHits <= 1" to "tagLinkHits === 0"
if(tagTextHits > tagLinkHits && tagLinkHits === 0) {
// Apply the tag
text = text.replace(tags[loopCounter], "" + tags[loopCounter] + "");
$(this).html(text);
// Restore caret position // u78krf3t
}
}
loopCounter++;
}
}
bugCounter++;
}
});
});
};
*/
/* ----------------------------------------------
Limiting the number of characters the user is allowed to type
----------------------------------------------- */
var maxLength = 100;
$('.card').on('keyup', '.new_item', function() {
var length = $(this).val().length;
length = maxLength - length;
// show the characters remaining only on this field
$(this).closest('.user-input').find('.chars').text(length);
});
function limitLengthOnInput() {
// Limit text on key press
$("li.added_item .expandable").on("keypress", function(event) {
// Declarations
var numberOfTags = $(this).children().filter("a").length;
var textLength = $(this).html().length;
// Subtract 43 from textLength per tag (the tag HTML is 43 characters)
$(this).each(function() {
textLength -= 43 * numberOfTags;
});
if(textLength === 100) { // Windows menu/Right cmd
event.preventDefault();
}
});
// 28jek79t
// Limit text on paste
/*
var pastedTextOriginal;
$("li.added_item .expandable").on("paste", function(event) {
pastedTextOriginal = event.originalEvent.clipboardData.getData("Text");
if($(this).html().length + pastedTextOriginal > 100) {
console.log("Too long!");
event.preventDefault();
// var caretPosition = the text position
// Insert the text after caretPosition
}
// return false;
});
*/
}
/* ================================================
If the user closes a dialog
================================================= */
$("div.dialog button").on("click", function() {
$("div#shadow").css("display", "none");
$("div.dialog").css("display", "none");
});
/* ================================================
If the user clicks on the "Tag selected term" link
================================================= */
// Declaration
var selection = "";
// var newRange = "";
// Initiate tag
tag = "";
// Update the tag variable
document.onselectionchange = function() {
// if($("textarea").is(":focus")) {
if($("li.added_item .expandable").is(":focus")) {
selection = window.getSelection().toString();
tag = selection.trim();
}
}
// If the user clicks on the "Tag selected term" link
$("p.tag-selected-term a").on("click", function() {
// If the tag isn't empty
if(tag != "") {
// Show the tag window
showTagWindow();
}
else {
// Show a dialog
$("div#shadow").css("display", "block");
$("div#dialog-select-term").css("display", "block");
}
// Prevent the current view to jump to the top of the screen
return false;
});
// If the user moves the focus from the added idea, reset variables
$("li.added_item .expandable").on("focusout", function() {
selection = "";
tag = "";
});
/* ================================================
Serialize Form to JSON
================================================= */
$.fn.serializeObject = function() {
// Declarations
var o = {};
var a = this.serializeArray();
var addedIdeaLists = $(".card ul");
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
}
else {
o[this.name] = this.value || '';
}
});
// Add added ideas to the JSON object manually
$.each(addedIdeaLists, function() {
var field = $(this).attr("id");
var addedItemDivs = $(this).find($(".expandable"));
var addedItemArray = [];
var numberOfAddedItem = addedItemDivs.length;
if(numberOfAddedItem > 1) {
for(var i = 0; i < numberOfAddedItem; i++) {
addedItemArray[i] = addedItemDivs[i].textContent;
}
o[field + "[]"] = addedItemArray;
}
else if(numberOfAddedItem === 1) {
o[field + "[]"] = addedItemDivs[0].textContent;
}
});
return o;
};
/* ================================================
Getting the current date
================================================= */
var fullDate = new Date();
var fourDigitYear = fullDate.getFullYear();
var twoDigitMonth = fullDate.getMonth() + 1 + "";
var twoDigitDate = fullDate.getDate() + "";
if(twoDigitMonth.length == 1) {
twoDigitMonth = "0" + twoDigitMonth;
}
if(twoDigitDate.length == 1) {
twoDigitDate = "0" + twoDigitDate;
}
var currentDate = fourDigitYear + "-" + twoDigitMonth + "-" + twoDigitDate;
// Set the current date in the date input field
// $('.proj_date').val(currentDate);
/* ================================================
USER LOGS OUT (dropdown menu)
================================================= */
$('#user-profile').on('click', '#logout', function() {
var url = 'php/logout.php';
$.post(url, function(data, status) {
if (data == 200) {
$('#user-profile').hide();
$('.invited-members').hide();
window.location.href="https://www.ethicscanvas.org";
}
});
});
/* ================================================
When the page loads, Import the chosen canvas if the user has picked one from the dashboard,
otherwise load an empty canvas
================================================= */
// if a canvas is chosen by the user to be loaded
if (current_canvas_id !== '') {
var url = 'json/' + current_canvas_id + '.json';
// var url= 'json/test_canvas.json';
// get the saved JSON object in the sendJSON.text file
$.getJSON(url, function(returnedObj) {
// Display the json data in the html
var itemListHTML = '';
// iterate through the object
$.each(returnedObj, function(key, value) {
// project name and tem field
if (key === 'field_00[]') {
$('.form-header').find('input.proj_title').val(value[
0]);
$('.form-header').find('input.proj_date').val(value[1]);
}
else if (key !== 'new_item') {
if ($.type(value) === "array") {
$.each(value, function(i, itm) {
/** FIX DUPLICATIONs in the canvas when importing
/* Importing will override the canvas content
clear the canvas by giving en emty content to the ul list (remove previous list items) */
$('.canvas-form').find('.card').filter('.' + key.substr(0, 8)).find('ul.item_list').html('');
/* Create a list item with each value item
and give it text area with the name attribute as the "key" (right field name) */
itemListHTML +=
// '';
'' + itm + '
';
});
}
else { // a single value string
itemListHTML +=
// '';
'' + value + '
';
}
/* Append the created list items/textatreas to the right field based on the "key"*/
/* the str.substr(start,length)
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
so field names/key/name attribute will tuen into class names: ex: field_1[] becomes field_1
*/
// find the field by its class names besed on the current key name
// append the created list of item values to that right field
$('.canvas-form').find('.card').filter('.' + key.substr(0, 8)).find('ul.item_list').append(itemListHTML);
/*$('form').find('.card').filter('.field_1').find('ul.item_list').append(itemListHTML); */
/* !! 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 */
itemListHTML = '';
}
});
});
// Limit the text in the idea field if it reaches the max length
limitLengthOnInput();
// Apply event listener to the added idea handling the application of tags should the user writes one of the terms in it
// applyTagOnTypeMatch();
// Toggle textarea.expandable/div.expandable on focus
window.setTimeout(toggleTextElementOnFocus, 100);
// Show "Tag selected term" link in the destination category
window.setTimeout(function() {
$(".card .item_list").each(function() {
// console.log($(this).find("li"));
if($(this).find("li.added_item").length) {
$(this).next().show();
}
else {
// console.log("Nej!");
}
});
}, 100);
/*
$("div#move-window ul a").on("click", function() {
// If the number of the category is between 10-99
if($(this).parent().text().trim().substring(1, 2) != ".") {
categoryDestination = $(this).parent().text().trim().substring(0, 2);
}
// If the number of the category is between 0-9
else {
categoryDestination = $(this).parent().text().trim().substring(0, 1);
}
// Move the idea
// If the number of the category is between 10-99
if(categoryDestination > 9) {
$("ul#field_" + categoryDestination).append(ideaLi);
// $("ul#field_0" + (categoryOrigin + 1)).parent().find("p.tag-selected-term").css("display", "none");
}
// If the number of the category is between 0-9
else {
$("ul#field_0" + categoryDestination).append(ideaLi);
// $("ul#field_0" + (categoryOrigin + 1)).parent().find("p.tag-selected-term").css("display", "none");
}
// Close the move window
closeMoveWindow();
// Restore links in the move window
if($("div#move-window li").length > $("div#move-window a").length) {
$("div#move-window ul").children().remove()
$("div#move-window ul").append(categoryLis);
moveIdeaOnClick();
}
// Hide "Tag selected term" link in the origin category if there are no ideas left
if($("ul#field_0" + (categoryOrigin + 1)).children().length === 0) {
// If the number of the category is between 10-99
if((categoryOrigin + 1) > 9) {
$("ul#field_" + (categoryOrigin + 1)).parent().find("p.tag-selected-term").css("display", "none");
}
// If the number of the category is between 0-9
else {
$("ul#field_0" + (categoryOrigin + 1)).parent().find("p.tag-selected-term").css("display", "none");
}
}
// Show "Tag selected term" link in the destination category
// If the number of the category is between 10-99
if((categoryOrigin + 1) > 9) {
$("ul#field_" + categoryDestination).parent().find("p.tag-selected-term").css("display", "block");
}
// If the number of the category is between 0-9
else {
$("ul#field_0" + categoryDestination).parent().find("p.tag-selected-term").css("display", "block");
}
*/
// Remove all tags from all fields
// removeTags();
// Get the user's tags from the database and apply them on the canvas
getTags();
// Show "Tag selected term" link
/*
if($(this).parent().parent().parent().prev().prev().children().length > 0) {
$(this).parent().parent().parent().prev().css("display", "block");
}
if($(this).parent().parent().prev().prev().children().length > 0) {
$(this).parent().parent().prev().css("display", "block");
}
*/
// Fix the heights after importing
// fixHeights();
}
/* ================================================
Toggle the introduction text in fields
================================================= */
//$(selector).toggle(speed,easing,callback)
$('.card').on('click', '.intro-toggle', function() {
var $TogglingText = $($(this).closest('.card').find('.intro'));
var $Toggler = $($(this).closest('.card').find('.intro-toggle'));
$TogglingText.toggle('slow', function() {
// Do this when toggling:
// the boolean .is(':visible') of the current toggle state
if ($TogglingText.is(':visible')) {
// change the text of the toggle
$Toggler.find('.intro-toggle-text').text('Hide description');
// change the icon of the toggle
$Toggler.find('.intro-toggle-icon').switchClass("glyphicon-plus-sign", "glyphicon-minus-sign", 1000, "easeInOutQuad");
}
else {
$Toggler.find('.intro-toggle-text').text('Show description');
$Toggler.find('.intro-toggle-icon').switchClass("glyphicon-minus-sign", "glyphicon-plus-sign", 1000, "easeInOutQuad");
}
});
});
/* ================================================
Auto expand user input textareas
================================================= */
/* Works for textareas already exsting in the html when the page loads -> User input
$.each($('textarea[data-autoresize]'), function() {
var offset = this.offsetHeight - this.clientHeight;
var resizeTextarea = function(el) {
$(el).css('height', 'auto').css('height', el.scrollHeight + offset);
};
$(this).on('keyup input', function() {
resizeTextarea(this);
}).removeAttr('data-autoresize');
});
/* ================================================
Limiting the number of lines in textareas
================================================= */
//
/*
$('.card').on('keypress', 'textarea[data-limit-rows=true]', function(event) {
var textarea = $(this),
text = textarea.val(),
// match() -> Searches a string for a match against a regular expression, and returns the matches, as an Array object.
numberOfLines = (text.match(/\n/g) || []).length + 1,
maxRows = parseInt(textarea.attr('rows'));
// if the number of lines have reached the max rows
if (numberOfLines === maxRows) {
return false;
}
});
*/
/* ================================================
Handling user input, ADD items
A. Add button
B. Clicking enter
================================================= */
/* ----------------------------------------------
add new idea slide effect
----------------------------------------------- */
// 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
$('.card').on('click', 'a.add-idea', function(event) {
// stop the default behavior of the link (jumping back to the start of the page)
event.preventDefault();
// set the textarea automatically in focus
$(this).closest('.card').find('.user-input').slideToggle("slow", function() {
// When the toggle animation is complete:
// set the text area in focus
$(this).closest('.card').find('.new_item').val('');
$(this).closest('.card').find('.chars').text(maxLength);
$(this).closest('.card').find('.new_item').focus();
});
});
/* ----------------------------------------------
A. When we click the add btn to
add the item to the list
----------------------------------------------- */
// event deligation to handle the present and future elements that are dynamically added
$('.card').on('click', '.add_btn', function() {
var new_item = $(this).closest('.card').find('.new_item').val();
var new_item_height = $(this).closest('.card').find('.new_item').height();
// number of items are in the list
var fieldItemCount = $(this).closest('.card').find('ul.item_list').find('li').length;
// new item added, increment the number of items
fieldItemCount++;
// add the input value as a textarea item
/* 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) */
// if the new item input exist (is not empty), add the item
if (new_item) {
var field_attr = $(this).closest('.card').find('ul.item_list').attr('id') + '[]';
// The height of the newly added item = the height of the add new idea textarea
$(this).closest('.card').find('ul.item_list').append(
// ''
'' + new_item + '
'
);
// Fix the heights only after a new item is added
// fixHeights();
}
// clear the new item the text area value
$(this).closest('.card').find('.new_item').val('');
/* When clicking on "add idea", hide the input field for adding a new item (slideUp() doesn't work nicely here)*/
$(this).closest('.card').find('.user-input').hide("fast", function() {
// Animation complete.
});
// Limit the text in the idea field if it reaches the max length
limitLengthOnInput();
// Apply event listener to the added idea handling the application of tags should the user writes one of the terms in it
// applyTagOnTypeMatch();
// Toggle textarea.expandable/div.expandable on edit
toggleTextElementOnFocus();
// Remove all tags from all fields
removeTags();
// Get the user's tags from the database and apply them on the canvas
getTags();
// Show "Tag selected term" link
if($(this).parent().parent().prev().prev().children().length > 0) {
$(this).parent().parent().prev().css("display", "block");
}
});
/* ----------------------------------------------
B. Clicking enter in the add idea textarea,
will add the new item to the card
----------------------------------------------- */
$('.card').on('keypress', 'textarea[data-limit-rows=true]', function(event) {
var textarea = $(this);
var text = textarea.val();
/* The jQuery event.which -->
Returns which keyboard key was pressed: */
// if the enter is pressed, event.which === 13
if (event.which === 13 && !$("li.added_item .expandable").is(":focus")) {
var new_item = $(this).closest('.card').find('.new_item').val();
var new_item_height = $(this).closest('.card').find('.new_item').height();
// number of items are in the list
var fieldItemCount = $(this).closest('.card').find('ul.item_list')
.find('li').length;
// new item added, increment the number of items
fieldItemCount++;
// add the input value as a textarea item
/* 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) */
// if the new item input exist (is not empty), add the item
if (new_item) {
var field_attr = $(this).closest('.card').find('ul.item_list').attr(
'id') + '[]';
// The height of the newly added item = the height of the add new idea textarea
$(this).closest('.card').find('ul.item_list').append(
// '');
'' + new_item + '
'
);
// Fix the heights only after a new item is added
// fixHeights();
}
// clear the new item the text area value
$(this).closest('.card').find('.new_item').val('');
/* When clicking on "add idea", hide the input field for adding a new item (slideUp() doesn't work nicely here)*/
$(this).closest('.card').find('.user-input').hide("fast", function() {
// Animation complete.
});
// Limit the text in the idea field if it reaches the max length
limitLengthOnInput();
// Apply event listener to the added idea handling the application of tags should the user writes one of the terms in it
// applyTagOnTypeMatch();
// Toggle textarea.expandable/div.expandable on edit
toggleTextElementOnFocus();
// Remove all tags from all fields
removeTags();
// Get the user's tags from the database and apply them on the canvas
getTags();
// Show "Tag selected term" link
if($(this).parent().parent().parent().prev().prev().children().length > 0) {
$(this).parent().parent().parent().prev().css("display", "block");
}
}
});
/* ================================================
Moving ideas to a different category
================================================= */
// Declarations
// var categoryUl = $("div#move-window ul");
var categoryDestination;
var categoryLis = $("div#move-window ul").html();
var categoryAs = $("div#move-window ul a");
var categoryOrigin;
var ideaLi;
var linkLi;
var linkText;
// Remove the link to the current category, as the idea cannot be moved to its own category where it already is
function removeLinkToOriginCategory(text) {
// If the number of the category is between 10-99
if(text.substring(6, 7) != "0") {
categoryOrigin = text.substring(6, 9) - 1;
}
// If the number of the category is between 0-9
else {
categoryOrigin = text.substring(7, 9) - 1;
}
// Remove "a" tag
linkLi = $("div#move-window ul li").get(categoryOrigin);
linkText = categoryAs.get(categoryOrigin).innerHTML;
linkLi.innerHTML = linkText;
}
// If the user clicks on the "Move" icon, show the move window
$(".card").on("click", "span.handle", function() {
// Show the move window
$("div#shadow").css("display", "block");
$("div#move-window").css("display", "block");
// Assign the idea that is going to be moved
ideaLi = $(this).parent();
// Remove the link to the current category, as the idea cannot be moved to its own category where it already is
removeLinkToOriginCategory($(this).parent().parent().attr("id"));
});
// Close the move window
function closeMoveWindow() {
// Close the move window
$("div#shadow").css("display", "none");
$("div#move-window").css("display", "none");
}
// If the user clicks on the "Close" button
$("div#move-window button.close").on("click", function() {
// Close the move window
closeMoveWindow();
});
// If the user clicks on a category, move the idea
function moveIdeaOnClick() {
$("div#move-window ul a").on("click", function() {
// If the number of the category is between 10-99
if($(this).parent().text().trim().substring(1, 2) != ".") {
categoryDestination = $(this).parent().text().trim().substring(0, 2);
}
// If the number of the category is between 0-9
else {
categoryDestination = $(this).parent().text().trim().substring(0, 1);
}
// Move the idea
// If the number of the category is between 10-99
if(categoryDestination > 9) {
$("ul#field_" + categoryDestination).append(ideaLi);
// $("ul#field_0" + (categoryOrigin + 1)).parent().find("p.tag-selected-term").css("display", "none");
}
// If the number of the category is between 0-9
else {
$("ul#field_0" + categoryDestination).append(ideaLi);
// $("ul#field_0" + (categoryOrigin + 1)).parent().find("p.tag-selected-term").css("display", "none");
}
// Close the move window
closeMoveWindow();
// Restore links in the move window
if($("div#move-window li").length > $("div#move-window a").length) {
$("div#move-window ul").children().remove()
$("div#move-window ul").append(categoryLis);
moveIdeaOnClick();
}
// Hide "Tag selected term" link in the origin category if there are no ideas left
if($("ul#field_0" + (categoryOrigin + 1)).children().length === 0) {
// If the number of the category is between 10-99
if((categoryOrigin + 1) > 9) {
$("ul#field_" + (categoryOrigin + 1)).parent().find("p.tag-selected-term").css("display", "none");
}
// If the number of the category is between 0-9
else {
$("ul#field_0" + (categoryOrigin + 1)).parent().find("p.tag-selected-term").css("display", "none");
}
}
// Show "Tag selected term" link in the destination category
// If the number of the category is between 10-99
if((categoryOrigin + 1) > 9) {
$("ul#field_" + categoryDestination).parent().find("p.tag-selected-term").css("display", "block");
}
// If the number of the category is between 0-9
else {
$("ul#field_0" + categoryDestination).parent().find("p.tag-selected-term").css("display", "block");
}
});
}
moveIdeaOnClick();
/* ================================================
Moving ideas up
================================================= */
// If the user clicks on the "Up" button
$('.card').on('click', 'span.move-up', function() {
// Declarations
var ideaLiCurrent = $(this).parent();
var ideaLiPrevious = $(this).parent().prev();
// Move the idea
if(ideaLiPrevious.is("li")) {
ideaLiCurrent.detach();
ideaLiPrevious.before(ideaLiCurrent);
}
});
/* ================================================
Moving ideas down
================================================= */
// If the user clicks on the "Down" button
$('.card').on('click', 'span.move-down', function() {
// Declarations
var ideaLiCurrent = $(this).parent();
var ideaLiNext = $(this).parent().next();
// Move the idea
if(ideaLiNext.is("li")) {
ideaLiCurrent.detach();
ideaLiNext.after(ideaLiCurrent);
}
});
/* ================================================
Deleting ideas
================================================= */
// when the cross beside the textarea is clicked (span.remove)
// remove that list item
$('.card').on('click', 'span.remove', function() {
// If there are no ideas left, hide "Tag selected term" link
if($(this).prev().parent().parent().children().length === 1) {
$(this).prev().parent().parent().next().css("display", "none");
}
// Remove the list item
$(this).closest('li').remove();
});
/* ================================================
Sortable field ideas
================================================= */
// make items sortable in their fields and between fields
/*
$('.sortable').sortable({
connectWith: '.connectedList',
placeholder: "sort-placeholder",
// revert: true
zIndex: 300 // Or greater than any other relative/absolute/fixed elements and droppables
});
*/
/* ================================================
Sorting and Dragging events
================================================= */
/* sortstart
sortover
sortstop */
// 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)
/*
// Dragging starts
$(".sortable").on("sortstart", function(event, ui) {
// WHEN WE SORT CARDS, $(this) ---> the "begining" ul with the class of .sortable
});
// Dragging ends: item dropped
$(".sortable").on("sortstop", function(event, ui) {
// get the id of the field ul (to set the name attribute of textareas)
// # mouseleave is the right event for when we release and leave a card mouseup doesn't work properly in this case
$('.card').on('mouseleave', 'li', function() {
//$(selector).attr(attribute,value)
var fieldAttr = $(this).closest('ul.item_list').attr('id');
// $(this).find('textarea').attr('name', fieldAttr + '[]');
$(this).find('li.added_item .expandable').attr('name', fieldAttr + '[]');
});
});
*/
/* ================================================
SAVING THE CANVAS:
CLICK ON #EXPORT JSON# form button
================================================= */
/* ----------------------------------------------
If the user clicks on the SAVE CANVAS button
----------------------------------------------- */
$('.canvas-form').on('click', '.json_exp', function() {
/* ----------------------------------------------
A: Saving the canvas
as a registered user
----------------------------------------------- */
// php variables are retieved in the header of the canvas index.php as js variables -->
var name_save_canvas = $('.form-header').find('.proj_title').val();
// var date_save_canvas = $('.form-header').find('.proj_date').val();
var date_save_canvas = currentDate;
var save_canvas_obj = {
'email_save_canvas': email_save_canvas,
'name_save_canvas': name_save_canvas,
'date_save_canvas': date_save_canvas,
'id_save_canvas': canvasId
};
var save_canvas = $.param(save_canvas_obj);
/* Post the JSON stringified object to the php file
(the php script will save it in a .json file ) */
var save_reg_url = "php/save-canvas.php";
$.post(save_reg_url, { save_canvas: save_canvas }, function(data, status) {
//the returned data is successful, is the $canvas_id
var canvas_id = data;
// 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
// Give the user feedback that the canvas has been saved
if (data !== 400 || data !== 401) {
if ($('.imp-exp-btn ').find(".save-canvas-feedback") !== null) {
$('.imp-exp-btn ').find(".save-canvas-feedback").remove();
}
$('.canvas-form').find('.imp-exp-btn ').append('Your canvas has been saved in your dashboard
');
// remove the canvas is saves message as soon as user changes the canvas
// $('.canvas-form').on("change keyup", 'textarea', function() {
$('.canvas-form').on("change keyup", '.expandable', function() {
$('.imp-exp-btn ').find(".save-canvas-feedback").remove();
});
} else {
$('.canvas-form').find('.imp-exp-btn ').append('Oh! We could not save your canvas. Please try again or contact us at hello@ethicscanvas.org
');
}
// For the second AJAX request:
/* ----------------------------------------------
B: Exporing the form data json to a file
and save it on the server
----------------------------------------------- */
// $('#result').text(JSON.stringify($('.canvas-form').serializeObject()));
// Make the JSON object into a JSON string
// var JSONstrObj = JSON.stringify($('.canvas-form').serializeObject());
var JSONstrObj = JSON.stringify($('.canvas-form').serializeObject());
var url = "php/canvas.php";
// Post the JSON stringified object to the php file (the php script will save it in a .json file)
// Also, send the canvas_id and use it for naming the file
$.post(url, {
JSONstrObj: JSONstrObj,
canvas_id: canvas_id
}, function(data, status) {
console.log(
'Response from php when sending the form json object: \n' +
'data:' + data + '\n status: ' + status);
}).fail(function(jqXHR) {
console.log("Error " + jqXHR.status + ' ' + jqXHR.statustext);
});
}).fail(function(jqXHR) {
console.log("Error " + jqXHR.status + ' ' + jqXHR.statustext);
});
// Prevent the card item list from reseting itself after clicking on the export button (submission). Because the type of the button is submit
return false;
});
/* ================================================
HANDLING CLICK ON : Share This Canvas BUTTON
================================================= */
$('.canvas-form').on('click', '.share_canvas', function() {
$('.share_canvas_email').slideDown(1000, function() {
// SAVE THE PDF AS file
$.post('mpdf/canvas-pdf-save.php', function(data, status) { }); // save pdf as file
});
});
$('.canvas-form').on('click', '.share_canvas_send', function() {
var share_email = $('.share_canvas_email').find('input').serialize();
// 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
$.post('php/share-canvas.php', {
share_email: share_email
}, function(data, status) {
if (data == 200) { // canvas successfully shared
$('.canvas-form').find('.imp-exp-btn ').append('Your canvas has been shared by email
')
}
else {
$('.canvas-form').find('.imp-exp-btn ').append('Your canvas could not be shared by email
')
}
});
// slide up the .share_canvas_email area
$('.share_canvas_email').slideUp();
});
/* ================================================
Controlling the height of divs dynamically
================================================= */
// Call this function after adding a new item and importing
// $( window ).width(); ->Returns width of browser viewport
/*
function fixHeights() {
// Returns width of browser viewport
var screenSize = $(window).width();
//the longest card of the group 1 .masonry-layout7-5
var longest_1 = $('.masonry-layout7-5').height();
//the longest card of the group 2 .masonry-layout7-5
var longest_2 = $('.masonry-layout4').height();
// --- 5 COL Range ----
if (screenSize >= 1139) {
// 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
// card group 1:
// $('.field_05,.field_11, .field_07').css('min-height', longest_1 - longest_1 * 5 / 100);
// $('.field_06,.field_08, .field_12').css('min-height', longest_1 + longest_1 * 5 / 100);
// $('.field_01, .field_02').css('min-height', longest_1 * 2 + longest_1 * 1 / 100);
// card group 2:
// $('.field_03, .field_09, .field_10, .field_04').css('min-height', longest_2 * 2 - longest_2 * 20 / 100);
$('.field_05,.field_11, .field_07').css('min-height', longest_1 - longest_1 * 20 / 100);
$('.field_06,.field_08, .field_12').css('min-height', longest_1 - longest_1 * 20 / 100);
$('.field_01, .field_02').css('min-height', longest_1 + longest_1 * 40 / 100);
// card group 2:
$('.field_03, .field_09, .field_10, .field_04').css('min-height', longest_2 - longest_2 * 10 / 100);
}
// 4 COL Range //
else if (screenSize >= 977 && screenSize <= 1138) {
// card group 1:
// row 1
$('.field_01,.field_06, .field_12,.field_08 ').css('min-height', longest_1 + longest_2 * 20 / 100);
// row 2
$('.field_05,.field_11, .field_07,.field_02 ').css('min-height', longest_1 + longest_2 * 20 / 100);
// card group 2:
// row 3
$('.field_03, .field_09, .field_10, .field_04').css('min-height', longest_2 * 2 - longest_2 * 20 / 100);
} else if (screenSize >= 920 && screenSize <= 976) {
// card group 1:
// row 1
$('.field_01,.field_06, .field_12,.field_08 ').css('min-height', longest_1 + longest_2 * 20 / 100);
// row 2
$('.field_05,.field_11, .field_07,.field_02 ').css('min-height', longest_1 + longest_2 * 20 / 100);
// card group 2:
// row 3
$('.field_03, .field_09, .field_10, .field_04').css('min-height', longest_2 * 2 - longest_2 * 20 / 100);
} else if (screenSize >= 485 && screenSize <= 919) {
// else if (500 <= screenSize < 920) {
// card group 1:
$('.field_01,.field_06, .field_12,.field_08 ').css('min-height', longest_1 * 80 / 100);
$('.field_05,.field_11, .field_07,.field_02 ').css('min-height', longest_1 * 80 / 100);
// card group 2:
$('.field_03, .field_09, .field_10, .field_04').css('min-height', longest_2 * 80 / 100);
// --- 1 COL Range ----
} else {
// card group 1:
$('.field_01,.field_06, .field_12,.field_08 ').css('min-height', longest_1 * 20 / 100);
$('.field_05,.field_11, .field_07,.field_02 ').css('min-height', longest_1 * 20 / 100);
// card group 2:
$('.field_03, .field_09, .field_10, .field_04').css('min-height', longest_2 * 20 / 100);
}
}
function fixHeights() {
// Returns width of browser viewport
var screenSize = $(window).width();
var field01 = $("div.field_01");
var field02 = $("div.field_02");
var field03 = $("div.field_03");
var field04 = $("div.field_04");
var field05 = $("div.field_05");
var field06 = $("div.field_06");
var field07 = $("div.field_07");
var field08 = $("div.field_08");
var field09 = $("div.field_09");
// Set the height of every field
var heightOfField01 = field01.height();
var heightOfField03 = field03.height();
var heightOfField04 = field04.height();
var heightOfField03And04 = field03.height() + field04.height();
var heightOfField09 = field09.height();
var heightOfField05 = field05.height();
var heightOfField06 = field06.height();
var heightOfField05And06 = field05.height() + field06.height();
var heightOfField02 = field02.height();
// --- 5 COL Range ---
if (screenSize >= 935) {
var longestInGroup1 = Math.max(heightOfField01, heightOfField03, heightOfField04, heightOfField03And04, heightOfField09, heightOfField05, heightOfField06, heightOfField05And06, heightOfField02);
console.log(longestInGroup1);
// Field group 1
switch(longestInGroup1) {
case heightOfField01:
$(".field_04").css("min-height", longestInGroup1 + 10);
$(".field_09").css("min-height", longestInGroup1 + 448);
$(".field_06").css("min-height", longestInGroup1 + 10);
$(".field_02").css("min-height", longestInGroup1 + 448);
break;
case heightOfField03:
// Code goes here
break;
case heightOfField04:
// Code goes here
break;
case heightOfField03And04:
// Code goes here
break;
case heightOfField09:
// Code goes here
break;
case heightOfField05:
// Code goes here
break;
case heightOfField06:
// Code goes here
break;
case heightOfField05And06:
// Code goes here
break;
case heightOfField02:
// Code goes here
break;
default:
break;
}
}
// --- 4 COL Range ---
else if (screenSize >= 935 && screenSize <= 991) {
// Field group 1
// Code goes here
// Field group 2
// Code goes here
}
else if (screenSize >= 992 && screenSize <= 1153) {
// Field group 1
// Code goes here
// Field group 2
// Code goes here
}
// --- 2 COL Range ---
else if (screenSize >= 500 && screenSize <= 934) {
// Field group 1
// Code goes here
// Field group 2
// Code goes here
}
// --- 2-5 COL Range ---
if (screenSize >= 500) {
var longestInGroup2;
// Field group 2
// Determine the longest Field in group 2
if(field07.height() < field08.height()) {
longestInGroup2 = field08;
}
else {
longestInGroup2 = field07;
}
if(longestInGroup2 === field07) {
$(".field_08").css("min-height", longestInGroup2.height() + 10);
}
else {
$(".field_07").css("min-height", longestInGroup2.height() + 10);
}
}
// --- 1 COL Range ---
// Field group 1
// Code goes here
// Field group 2
// Code goes here
}
*/
/*
new ResizeSensor($(".field_01, .field_02, .field_03, .field_04, .field_05, .field_06, .field_07, .field_08, .field_09"), function() {
// fixHeights();
});
*/
});