
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Keybaord accelerator functions
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//

$(document).ready(function () {

// Works, but decided to use the version below
    //$(document).keydown(function (event) {
    //    if (event.which == 113) { //F2
    //        ToastMessage("F2 keydown - document.keydown");
    //        return false;
    //    }
    //});

    document.addEventListener('keydown', function (e) {
        OnAppKeydown(event);
    })

    //document.addEventListener('keyup', function (e) {
    //    OnAppKeyup(event);
    //})

})


//$(document).tooltip({
//    track: true
//});


function OnAppKeydown(event) {

    //console.log("OnAppKeydown: " + event.which);

    // Ctrl+F2
    if (event.ctrlKey && event.which == 113/*F2*/) { 
        PopupSelectedContentSqlQueryScript();
        return false;
    }

    // ESC
    if (event.which == 27/*ESC*/) {
        // Revert draggable items to their original position
        $('.ui-draggable-dragging').draggable({ 'revert': true }).trigger('mouseup');
        return false;
    }

    // Delete
    if (event.which == 46/*Delete*/) {
        OnAppDeleteKeydown();
        return false;
    }

    // Ctrl+S (Save)
    if (event.ctrlKey && event.which == 83/*s*/) {
        OnAppCtrlSKeydown();
        return false;
    }

    // F9
    if (event.which == 120/*F9*/) {
        ToggleFullscreen();
        return false;
    }

}





function OnAppDeleteKeydown() {

    // Don't handle for "input" elements
    if (IsInputTypeElement())
        return;

    // Delete key was pressed
    OnDeleteSelectedContentRecord();
}

/***
 * Is the focus in an "input" or "textarea" element?
 * */
function IsInputTypeElement() {

    var focused = document.activeElement;
    if (focused) {
        var elementType = $(focused).prop('nodeName');
        if (elementType) {
            elementType = elementType.toLowerCase();
            if (elementType == 'input')
                return true;
            if (elementType == 'textarea')
                return true;
        }
    }

    // Not an input type element
    return false;
}


function PopupSelectedContentSqlQueryScript() {

    // Div with the real information in it
    var ContentDiv = GetSelectedContentInformationDiv();
    if (!ContentDiv) {
        PopupMessageBox("SQL Script", "This content has no SQL Script to display");
        return;
    }

    var sSqlScript = $(ContentDiv).find('.HiddenSqlQueryScript').val();
    if (!sSqlScript)
        sSqlScript = "This content has no SQL Script to display";
    sSqlScript = sSqlScript.replace(/ /g, "&nbsp;");
    PopupResizableMessageBox("SQL Script", sSqlScript);
}


/**
 * Save keyboard accellerator
 * */
function OnAppCtrlSKeydown() {

    event.preventDefault();

    var ValueString = GetSelectedContentPaneValueString()
    var LayoutString = LoadSelectedPaneLayoutStringFromCookie();;
    var FilterJsonString = LoadSelectedPaneFilterJsonStringFromCookie();
    var SettingsJsonString = LoadSelectedPaneSettingsJsonStringFromCookie();
    var ContentType = GetSelectedContentType();
    var ContentTitle = GetSelectedContentTitle();
    if (!ContentType) {
        ToastError("Save", "Ctrl+S keyboard accelerator not available.\r\n\r\nChoose Options menu instead.");
        return;
    }

    if (ContentType == "REPORTVIEW") {
        SaveReport();
        return;
    }

    AjaxSaveAppContent(ContentType, ContentTitle, ValueString, LayoutString, FilterJsonString, SettingsJsonString);

    // TODO: P8 Call "Save" function for reports page (and other content that saves data)
    //ToastError("Save", "Ctrl+S keyboard accelerator not connected.\r\n\r\nChoose Options menu instead.");
}


/**
 * Show the current page's content div as fullscreen
 */
function ToggleFullscreen() {

    // Does the browser support this mode?
    if (!document.fullscreenEnabled) {
        ToastError("Full screen", "This browser does not support full-screen mode.");
        return;
    }

    // Find the selected content dov
    //var ContentDiv = GetSelectedContentPane();
    var ContentDiv = GetSelectedContentPartialViewDivElement();

    // NO! This div will be deleted and replaced in the next update
    // That update causes the browser to jump out of full-screen mode
    //var ContentDiv = GetSelectedContentInformationDiv();

    if (!ContentDiv || ContentDiv.length == 0) {
        ToastError("Full screen", "Oops, cannot find a page element to promote to full-screen!");
        return;
    }

    // Force into full app size
    bForceSmallApp = false;
    bForceFullApp = true;
    bLockAppSize = true;

    // Toggle full-screen mode now
    if (!document.fullscreenElement) {
        ContentDiv[0].requestFullscreen().catch((err) => {
            ToastError("Full screen", "Failed to go into full-screen mode! " + " " + err.message + " " + err.name);
        });
    } else {
        document.exitFullscreen();
    }
}




function AjaxSaveAppContent(ContentType, ContentTitle, ValueString, LayoutString, FilterJsonString, SettingsJsonString) {

    var params = {
        "ContentType": ContentType,
        "ContentTitle": ContentTitle,
        "ValueString": ValueString,
        "LayoutString": LayoutString,
        "FilterJsonString": FilterJsonString,
        "SettingsJsonString": SettingsJsonString,
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxSaveAppContent",
        type: "POST",
        data: JSON.stringify(params),
        dataType: "json",
        contentType: "application/json",
        success: function (response) {
            if (response.Success) {
                if (response.Results)
                    ToastMessage("Save", response.Results);
                else if (response.ErrorResults)
                    ToastError("Save", response.ErrorResults);
            }
            else {
                ToastError("AjaxCanSaveContentRecord", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxCanSaveContentRecord", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}





