//Submit button of settings
$('#SaveChangesProjectSettingsButton').click(function (event) {saveSettings(event)} );
$('#buttonDeleteConfirmed').click(function (event) {deleteProject(event)});

//Handle File Change
$('input[type=file]').change(function(e){
    readImageInput(this);
});

function deleteProject(event) {
    var path = currentURL().toString();
    event.preventDefault();

    var posting = $.ajax({
        url: path,
        type: "DELETE",
        data: ""
    });
    posting.done(function(response) {
        location.href = "http://" + location.host + "/";
        return true;
    }).fail(function (response) {
        $( "#modalPlaceholder" ).empty().append(response.responseText);
        $('#errorModal').modal('show');
    });
}

function saveSettings(event) {
    var path = currentURL().toString();
    ajaxRequestFragment(event, path, "POST");
}

function ajaxRequestFragment(event, target, requestType) {
    event.preventDefault();

    var posting = $.ajax({
        url: target,
        type: requestType,
        data: getParamsFragment()
    });
    posting.done(function(response) {
        location.replace(location.pathname);
        return true;
    }).fail(function (response) {
        $( "#modalPlaceholder" ).empty().append(response.responseText);
        $('#errorModal').modal('show');
    });
}

function getParamsFragment() {
    return {
        fragment:  false,
        inputProjectName: $('#inputProjectName').val(),
        inputProjectDesc: $('#inputProjectDescription').val(),
        inputProjectLogo: $('#projectImageSettings').val(),
        optionsProjectVisibility: document.querySelector('input[name="optionsProjectVisibility"]:checked').value
    }
}

function readImageInput(input) {

    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function(e) {
            $('#projectImageSettings').attr('src', e.target.result);
        };

        reader.readAsDataURL(input.files[0]);
    }
}