/* 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;
        
    // 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 = "5";
    document.getElementById("4-col-layout").style.MozColumnCount = "4";
    
    // Prevent pressing ENTER on Project Title from submitting the form
    $('.proj_title').keydown(function(event){
        if(event.keyCode == 13) {
            event.preventDefault();
            return false;
        }
    });
        
    /* ================================================
    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 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();
        
        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);
    }
    
    // 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();
        
        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);
    }
    
    // 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;
        }
    });
    
    /* ================================================
    "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;
    }
    
    // When 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 - 57;
            
            // 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: {
                "username": username
            },
            timeout: 5000,
            success: function(returnData) {
                // Declarations
                var loopCounter = 0;
                tags = returnData;
                
                // For every added item
                $("li.added_item div").each(function() {                    
                    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("</a>") != -1) {
                            // Delete the tag
                            var text = thisDiv.html();
                            text = thisDiv.text().replace("<a class='tag'>" + tags[loopCounter] + "</a>", tags[loopCounter]);
                            thisDiv.html(text);
                        }
                        
                        loopCounter++;
                    }
                });
                
                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 div").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("</a>") != -1) {
                    // Delete the tag
                    var text = thisDiv.html();
                    text = thisDiv.text().replace("<a class='tag'>" + tags[loopCounter] + "</a>", tags[loopCounter]);
                    thisDiv.html(text);
                }
                
                loopCounter++;
            }
        });
        
        console.log(tags);
        console.log(tags.length);
        
        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 applyTags() {
        var loopCounter = 0;
        
        // For every added item
        // $("li.added_item textarea").each(function() {
        $("li.added_item div").each(function() {
            // Here the selector is retrieving the objects it is supposed to...
            
            // For every tag in the database that belongs to the active user
            for(t in tags) {
                // console.log("tags.length: " + tags.length);
                // console.log("tag: " + tags[loopCounter]);
                // console.log($(this));
                
                // console.log("Now working with " + tags[loopCounter]);
                
                // console.log($(this).html());
                
                // console.log("The tag " + tags[loopCounter] + " has index '" + tags[loopCounter].indexOf("&nbsp;") + "' for '&nbsp;'");
                
                var text = $(this).html();
                
                // If the current tag exists in the textarea
                if(text.indexOf(tags[loopCounter]) != -1) {
                    // console.log($(this).html());
                    
                    // ... But here the selector only seems to retrieve the first instance
                    
                    // console.log("Inside if!");
                    
                    // Apply the tag
                    text = text.replace(tags[loopCounter], "<a class='tag' contenteditable='false'>" + tags[loopCounter] + "</a>");
                    $(this).html(text);
                }
                
                loopCounter++;
            }
        });
        
        // Populate "Saved Tags"
        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("<a href='#' class='tag'>" + tags[loopCounter] + "</a>").append("&nbsp;&nbsp; ");
            
            loopCounter++;
        }
    }
    
    // Get the tags from the database
    function getTags() {
        // Declarations
        var username = $("input[name='username']").val();
        
        // AJAX
        $.ajax({
            type: "POST",
            url: "php/get-tags.php",
            dataType: "JSON",
            data: {
                "username": username
            },
            timeout: 5000,
            success: function(returnData) {
                if(returnData.length > 0) {
                    // Assign returnData to the tags variable
                    tags = returnData;
                    
                    // Sort the tags
                    returnData.sort(function (a, b) { 
                        return a.toLowerCase().localeCompare(b.toLowerCase())
                    });
                    
                    // Apply the tags on the canvas
                    applyTags();
                    showTagWindowOnTagClick();
                }
            },
            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 checkIfTagIsNew() {
        // Declarations
        var tagToAJAX = tag;
        
        // AJAX
        $.ajax({
            type: "POST",
            url: "php/check-if-tag-exists.php",
            dataType: "text",
            data: {
                "tag": tagToAJAX,
                "username": username
            },
            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,
                "username": username
            },
            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,
                "username": username
            },
            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-username").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 += "<p class='similar-tags-tag'><a class='tag'>" + returnData[index]["tag"] + "</a></p>"
                            +  "<p class='similar-tags-description'>" + returnData[index]["description"] + "</p>"
                            +  "<p class='similar-tags-username'>by <a href='#'>" + returnData[index]["username"] + "</a></p>";
                            
                        index++;
                    }
                    
                    // Append tags
                    $("div#tag-window h2.similar-tags").after(htmlToAppend);
                    $("p.similar-tags-description-none").css("display", "none");
                    
                    // Apply the tags on the canvas
                    // applyTags();
                    // showTagWindowOnTagClick();
                }
                else {
                    // If the tag isn't a new tag
                    if(tagIsNew === false) {
                        // 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() {
        $("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");
        
        // 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
        checkIfTagIsNew();
        
        // Get the description for the selected tag
        getDescriptionForSelectedTag();
        
        // Get tags by other users from the database
        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,
                    "username": username
                },
                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,
                "username": username
            },
            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 types a new character in the added idea field, add tag if a term could be found
    ================================================= */
    
    // 8an33j24
    
    function applyTagOnTypeMatch() {
        $("li.added_item div").on("focusin", function() {
            // If the user presses a key in the description textarea
            $("li.added_item div").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] + "</a>");   // 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], "<a class='tag' contenteditable='false'>" + tags[loopCounter] + "</a>");
                                    $(this).html(text);
                                }
                            }
                            
                            loopCounter++;
                        }
                    }
                    bugCounter++;                
                }
            });
        });
    };
    
    /* ----------------------------------------------
    Limiting the number of characters the user is able 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 div").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
        /*
        $("li.added_item div").on("paste", function(event) {
            var pastedText;
            
            $("li.added_item div").bind("paste", function(e) {
                pastedText = e.originalEvent.clipboardData.getData("Text");
                
                console.log(pastedText);
                
                if($(this).html().length + pastedText >= 100) {
                    event.preventDefault();
                }
                
            });
            
            // var text = $(this).html()
            // var length = text.length;
            // var newText = text.substring(0, maxLength);
            
            // if(length >= maxLength) {
                // $(this).html(newText);
                
                // Move the text cursor to the very end
            }
        });
         */
    }
    
    /* ================================================
    If the user closes a dialog
    ================================================= */
    $("div.dialog button").on("click", function() {
        $("div#shadow").css("display", "none");
        $("div.dialog").css("display", "none");
    });
    
    /* ================================================
    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 div").is(":focus")) {                   // This is nicer: $("li.added_item div").on("focusin", function() {
            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 textarea").on("focusout", function() {
    $("li.added_item div").on("focusout", function() {
        selection = "";
        tag = "";
    });
    
    /* ================================================
    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() {                                // Event not triggered...
            // Declarations
            tag = $(this).text();
            
            // If the user is logged in
            if($("input[name='username']").val() != "") {
                // 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;
    }
     */
        
    /* ================================================
        Serialize Form to JSON
    ================================================= */
    
    $.fn.serializeObject = function() {
        var o = {};
        var a = this.serializeArray();
        $.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 || '';
            }
        });
        return o;
    };
    
    /* ================================================
    Getting the current date
    ================================================= */
    
    var fullDate = new Date();
    var twoDigitMonth = fullDate.getMonth() + "";
    if (twoDigitMonth.length == 1) twoDigitMonth = "0" + twoDigitMonth;
    var twoDigitDate = fullDate.getDate() + "";
    if (twoDigitDate.length == 1) twoDigitDate = "0" + twoDigitDate;
    
    var currentDate = fullDate.getFullYear() + "-" + twoDigitMonth + "-" + twoDigitDate;
    // set the currebt 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();
                window.location.href="https://www.ethicscanvas.org";
            }
        });
    });
    
    /* ================================================
    When the page loads, Import the chosen canvas if the user has picked one from the dashbord,
    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 ISON 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 +=
                                // '<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>';
                                '<li class="added_item"><div class="expandable" name="' + key + '" contenteditable="true">' + itm + '</div><span class="handle glyphicon glyphicon-list"></span><span class="move-up glyphicon glyphicon-chevron-up"></span><span class="move-down glyphicon glyphicon-chevron-down"></span><span class="remove glyphicon glyphicon-remove-circle"></span></li>';
                        });
                    }
                    else { // a single value string
                        itemListHTML +=
                            // '<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>';
                            '<li class="added_item"><div class="expandable" name="' + key + '" contenteditable="true">' + value + '</div><span class="handle glyphicon glyphicon-list"></span><span class="move-up glyphicon glyphicon-chevron-up"></span><span class="move-down glyphicon glyphicon-chevron-down"></span><span class="remove glyphicon glyphicon-remove-circle"></span></li>';
                    }
                    /* 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 = '';
                    
                }
            });
            
        });
        
        // 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");
        }
        
        // 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
    ================================================= */
    
    // <textarea data-limit-rows="true" cols="60" rows="8"></textarea>
    /*
    $('.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(
                // '<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>'
                '<li class="added_item"><div class="expandable" name="' + field_attr + '" contenteditable="true">' + new_item + '</div><span class="handle glyphicon glyphicon-list"></span><span class="move-up glyphicon glyphicon-chevron-up"></span><span class="move-down glyphicon glyphicon-chevron-down"></span><span class="remove glyphicon glyphicon-remove-circle"></span></li>'
            );
            
            // 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();
        
        // Remove all tags from all fields
        removeTags();
        
        // Get the user's tags from the database and apply them on the canvas
        getTags();      // Really necessary?
        
        // 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) {
            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(
                    // '<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>');
                    '<li class="added_item"><div class="expandable" name="' + field_attr + '" contenteditable="true">' + new_item + '</div><span class="handle glyphicon glyphicon-list"></span><span class="move-up glyphicon glyphicon-chevron-up"></span><span class="move-down glyphicon glyphicon-chevron-down"></span><span class="remove glyphicon glyphicon-remove-circle"></span></li>'
                );
                // 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();
            
            // Remove all tags from all fields
            removeTags();
            
            // Get the user's tags from the database and apply them on the canvas
            getTags();      // Really necessary?
            
            // 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 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 = $("div#move-window ul a").get(categoryOrigin).innerHTML;
        linkLi.innerHTML = linkText;
    }
   
    // When 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");
    }
    
    // When the user clicks on the "Close" button
    $("div#move-window button.close").on("click", function() {
        // Close the move window
        closeMoveWindow();
    });
    
    // When 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
    ================================================= */
    
    // When 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
    ================================================= */
    
    // When 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 div').attr('name', fieldAttr + '[]');
        });
        
    });
     */
    
    /* ================================================
    SAVING THE CANVAS:
    CLICK ON #EXPORT JSON# form button
    ================================================= */
    
    /* ----------------------------------------------
    When 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 save_canvas_obj = {
            'email_save_canvas': email_save_canvas,
            'name_save_canvas': name_save_canvas,
            'date_save_canvas': date_save_canvas
        };
        
        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 is 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('<div class="save-canvas-feedback"><p><span class="glyphicon glyphicon-ok" aria-hidden="true"></span>Your canvas is saved in your dashbord</p></div>');
                // 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('<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>');
            }
            // 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 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('<div class="save-canvas-feedback"><p><span class="glyphicon glyphicon-ok" aria-hidden="true"></span>Your canvas has been shared by email</p></div>')
            }
            else { 
                $('.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>')
            }
        });
        
        // 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();
    });
     */
});