/*
 *  Naam      : R. Wacanno  Skip Harks  Chris Bras  Bodi Boelé
 *  UvAnetID  : 11741163    12002038    11917318    11904089
 *  Studie    : BSc Informatica
 *
 *  homeTextfield.js
 *  -This file handles the manipulation of the contents
 *   of threads by their original posters.
 */

/* Pulls the thread content from the database and displays it
   in the threadMessage div, including markdown conversion. */
function pullText()
{
    var threadId = getQueryVariable('id');

    $.get("threadContent.php",
    {
        id: threadId
    },
    function(data)
    {
        $('#threadMessage').html(data);
    }).fail(function()
    {
        alert( "Er ging iets mis bij het laden." );
    });
}


/* Pulls the thread content from the database and inserts it
   into the textarea, excluding markdown conversion. */
function pullTextP()
{
    var threadId = getQueryVariable('id');

    $.post("threadContentP.php",
    {
        id: threadId
    },
    function(data)
    {
        $('#textfield').val(data);
    }).fail(function()
    {
        alert( "Er ging iets mis bij het laden." );
    });
}

/* Inserst contents of the textarea into the database. */
function pushText()
{
    var text = $('#textfield').val();
    var threadId = getQueryVariable('id');

    $.post("changeThread.php",
    {
        thread_id: threadId,
        text: text
    },
    function(data)
    {
        showText();
    }).fail(function()
    {
        alert( "Er ging iets mis bij het opslaan." );
    });
}

/*Hides the textarea and save button and changes the 'annuleren' button
  into the 'veranderen' button. */
function showText()
{
    pullText();
    pullTextP();
    $('#textWrapper').css('display', 'none');
    $('#saveButton').css('display', 'none');
    $('#textButton').html('Veranderen');
    $('#textButton').attr('onclick', 'showField()');
    $('#textButton').attr('class', 'formButton');
}

/* Displays the textarea and the save button and changes the 'veranderen' button
   into the 'annuleren' button. */
function showField()
{
    pullText();
    pullTextP();
    $('#textWrapper').css('display', 'inline');
    $('#saveButton').css('display', 'inline');
    $('#textfield').focus();
    $('#textButton').html('Annuleren');
    $('#textButton').attr('onclick', 'showText()');
    $('#textButton').attr('class', 'formButtonRed');
}

/* Saves the contents of the textarea. */
function saveText()
{
    pushText();
}

$('body').ready(showText());

/* Adapt textarea height based on its contents */
$('#textWrapper').on( 'focus change keyup keydown paste cut', 'textarea', function (){
    $(this).height(0).height(this.scrollHeight);
}).find( 'textarea' ).change();
