
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Tap To Start
// Tap to start and stop timers, deduct inventory, etc
// Similar to barcode scanning, but with icons instead
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//

var ClickedTapToStartItem = {};
var TapToStartDivId = "";

function ShowTapToStartView() {

    // Set the cookie to show
    setCookie("ST-ShowTapToStart", "1", 365);

    // Tap to start is part of the "Scan Barcodes" page
    ShowBarcodeView();

    // Make sure this shows, even if the page takes a while to load
    setTimeout(function () { ShowTapToStartPanel(true); }, 100);
    setTimeout(function () { ShowTapToStartPanel(true); }, 500);
    setTimeout(function () { ShowTapToStartPanel(true); }, 1000);
}

function SetupDisplayTapToStartById(elementid) {

    //ToastError("elementid", elementid);

    TapToStartDivId = elementid;
    var bShowTapToStart = getCookie("ST-ShowTapToStart") == "1";
    ShowTapToStartPanel(bShowTapToStart);
}

function SetupDisplayTapToStart(element) {

    if (!element)
        return;

    // Special value atttribute stored in the element
    // In this case, used as an ID for the input textarea
    var DataValue = $(element).attr("data-value");
    if (!DataValue)
        return;

    SetupDisplayTapToStartById(DataValue);

}

function OnClickTapToStartItem(evt) {

    if (!evt)
        return;
    if (!evt.target)
        return;
    var ElementObj = $(evt.target);
    if (!ElementObj)
        return;
    if (!ElementObj.length)
        return;

    // Item values
    var sObjectType = ElementObj.attr("data-object-type");
    var sPropertyType = ElementObj.attr("data-property-type");
    var sText = ElementObj.attr("data-text");
    var sValue = ElementObj.attr("data-value");
    var sValueId = ElementObj.attr("data-valueid");
    var sDbTable = ElementObj.attr("data-dbtable");
    //ToastMessage("OnClickTapToStartItem: \r\n" + sText + "\r\n" + sValue + "\r\n" + sObjectType + "\r\n" + sPropertyType + "\r\n" + sDbTable);

    // Remember this while Ajax popup is opening
    ClickedTapToStartItem.sObjectType = sObjectType;
    ClickedTapToStartItem.sPropertyType = sPropertyType;
    ClickedTapToStartItem.sText = sText;
    ClickedTapToStartItem.sValue = sValue;
    ClickedTapToStartItem.sValueId = sValueId;
    ClickedTapToStartItem.sDbTable = sDbTable;

    // Pop up a chooser (modeless dropdown to pick an item from a list)
    AjaxTapToStartItemChooser(ElementObj, sObjectType, sPropertyType, sDbTable, sText, sValue, sValueId, "OnClickTapToStartChooserItem");
}



function AjaxTapToStartItemChooser(ElementObj, sItemObjectType, sItemPropertyType, sItemDbTable, sItemText, sItemValue, sItemValueId, sOnClickFunction) {

    if (!sItemObjectType)
        return;
    if (!sItemPropertyType)
        return;
    if (!sItemDbTable)
        return;

    var params = {
        "ItemObjectType": sItemObjectType,
        "ItemPropertyType": sItemPropertyType,
        "ItemDbTable": sItemDbTable,
        "ItemText": sItemText,
        "ItemValue": sItemValue,
        "ItemValueId": sItemValueId,
        "OnClickFunction": sOnClickFunction,
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxTapToStartItemChooserHtml",
        type: "POST",
        data: JSON.stringify(params),
        contentType: "application/json",
        success: function (response) {
            if (response.Success) {

                if (response.ItemChooserHtml) {
                    OpenTapToStartPopupChoices(ElementObj, response.ItemChooserHtml);

                    // Do not refresh becuase it clears the popup contents
                    //RefreshSelectedContent();
                }
            }
            else {
                ToastError("Error", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText + "\r\nText: " + sItemText;
            ToastError("AjaxTapToStartItemChooser", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}

function OpenTapToStartPopupChoices(ElementObj, ItemChooserHtml) {

    var TapToStartPopupContainerDiv = $("#TapToStartPopupContainerDiv");
    var TapToStartPopupContentDiv = $("#TapToStartPopupContentDiv");
    if (!TapToStartPopupContainerDiv)
        return;
    if (!TapToStartPopupContainerDiv.length)
        return;
    if (!TapToStartPopupContentDiv)
        return;
    if (!TapToStartPopupContentDiv.length)
        return;

    // Set the chooser html into the popup
    TapToStartPopupContentDiv.html(ItemChooserHtml);

    // Html data is for a Mini Tree View
    // This is a list of <ul> and <li> items that act as a tree
    // https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_treeview
    //SetupMiniHtmlTreeView(TapToStartPopupContainerDiv);
    ExpandAllMiniHtmlTreeView(TapToStartPopupContainerDiv);
    RemoveCaretsMiniHtmlTreeView(TapToStartPopupContainerDiv);

    // Save this so the popup can be closed
    // Add the "click outside dropdown" listener function
    // This function recieves clicks anywhere in the window except this dropdown div
    DropDownOpenTime = new Date($.now());
    $('input[id="HiddenPopupDivId"]').val("TapToStartPopupContainerDiv");
    $('input[id="HiddenPopupRemoveFromBody"]').val("");
    document.removeEventListener("click", OnClickOutsidePopupDiv);
    document.addEventListener("click", OnClickOutsidePopupDiv);

    // Postion popup at the element postion
    var ElementPosition = ElementObj.position();
    var PopupTop = ElementPosition.top + ElementObj.height() + 15;
    var PopupLeft = ElementPosition.left;
    TapToStartPopupContainerDiv.css('top', PopupTop + 'px');
    TapToStartPopupContainerDiv.css('left', PopupLeft + 'px');

    // Finally, display the div
    TapToStartPopupContainerDiv.css('display', 'block');
}




/**
 * Called when a user clicks an item in a popup chooser list
 * Examples: Username, Project, Task
 * @param {any} evt
 * @param {any} sChoiceName
 * @param {any} sChoiceId
 */
function OnClickTapToStartChooserItem(evt, sChoiceName, sChoiceId) {

    if (!sChoiceName)
        return;
    if (!sChoiceName.trim())
        return;
    if (!ClickedTapToStartItem)
        return;
    if (!ClickedTapToStartItem.sObjectType)
        return;

    //ToastError("OnClickTapToStartChooserItem", ClickedTapToStartItem.sObjectType + "\r\n" + sChoiceName + "\r\n" + sChoiceId);

    var BarcodeInputTextObject = $("#" + BarcodeScanTextAreaId);
    if (!BarcodeInputTextObject)
        return;

    // Send text to barcode processor with Ajax
    // This will be processed like a normal barcode scan
    RestartBarcodeClearTimer();
    AjaxProcessBarcodeScanBegin(sChoiceName);

    ClickedTapToStartItem = {};
    CloseLastPopup();
}



function OnTapToStartClear() {

    // Send "CLEAR" to barcode scan
    RestartBarcodeClearTimer();
    AjaxProcessBarcodeScanBegin("CLEAR");
}


function OnCloseTapToStartPanel() {

    ShowTapToStartPanel(false);
}


function ShowTapToStartPanel(bShow) {

    if (!TapToStartDivId)
        return;

    var TapToStartDivObject = $("#" + TapToStartDivId);
    if (!TapToStartDivObject)
        return;
    if (TapToStartDivObject.length == 0)
        return;

    if (bShow) {
        setCookie("ST-ShowTapToStart", "1", 365);
        TapToStartDivObject.css('display', 'block');
    }
    else {
        setCookie("ST-ShowTapToStart", "0", 365);
        TapToStartDivObject.css('display', 'none');
    }
}




// OLD, use normal barcode processing to handle tap-to-start choices
//function AjaxTapToStartItemChoice(evt, sChoiceName, sChoiceId) {

//    if (!sChoiceName)
//        return;
//    if (!sChoiceId)
//        return;
//    if (!ClickedTapToStartItem)
//        return;
//    if (!ClickedTapToStartItem.sObjectType)
//        return;

//    var params = {
//        "ItemObjectType": ClickedTapToStartItem.sObjectType,
//        "ItemPropertyType": ClickedTapToStartItem.sPropertyType,
//        "ItemDbTable": ClickedTapToStartItem.sDbTable,
//        "ItemText": ClickedTapToStartItem.sText,
//        "ItemValue": ClickedTapToStartItem.sValue,
//        "ItemValueId": ClickedTapToStartItem.sValueId,
//        "ChoiceName": sChoiceName,
//        "ChoiceId": sChoiceId,
//    };

//    $.ajax({
//        url: VirtualDirectory + "/Home/AjaxTapToStartItemChoice",
//        type: "POST",
//        data: JSON.stringify(params),
//        contentType: "application/json",
//        success: function (response) {
//            if (response.Success) {

//                ToastError("AjaxTapToStartItemChoice", ClickedTapToStartItem.sObjectType + "\r\n" + sChoiceName + "\r\n" + sChoiceId);

//                ClickedTapToStartItem = {};
//                CloseLastPopup();
//                RefreshSelectedContent();
//            }
//            else {
//                ToastError("Error", response.ErrorResults);
//            }
//        },
//        error: function (xhr, status, error) {
//            var errormsg = "Error " + xhr.status + ", " + xhr.statusText + "\r\nText: " + sItemText;
//            ToastError("AjaxTapToStartItemChooser", errormsg);
//            console.log('AJAX: ' + errormsg);
//        }
//    });
//}



