function fnValidateStockIssue() {
    var himsValidator;
    himsValidator = [new hims_ctl_val("ctl00_CP_ToDepartmentDropDownList", "To Dept", "T", "", "", "", "", "", "")];
    if (fnDoValidate(himsValidator))
        return true;
    else
        return false;
}
function fnValidateAddToList() {
    var himsValidator;
    himsValidator = [new hims_ctl_val('ctl00_CP_StockItemCodeTextBox' + '_NameTextBox', "Item Code", "T", "", "", "", "", "", ""),
                                    new hims_ctl_val("ctl00_CP_IssueQtyTextBox", "Issue Qty", "T", "", "", "", "", "", "")];
    if (fnDoValidate(himsValidator))
        return true;
    else
        return false;
}
function uppercase() {
    key = window.event.keyCode;
    if ((key > 0x60) && (key < 0x7B))
        window.event.keyCode = key - 0x20;
}
function fnClearTabIndexChange() {

}
function fnCloseForm() {
    window.close();
    return false;
}
//function cpageLoad() {
//    var browser = navigator.userAgent.toLowerCase();
//    if (browser.indexOf('firefox') >= 0) {
//        $("#ctl00_CP_FileUpload1").fileUpload({
//            'uploader': '../../../UserControls/MultiFileUpload/uploader.swf',
//            'cancelImg': '../../../Images/cancel.png',
//            'script': '../../../UserControls/MultiFileUpload/Upload.ashx?ASPSESSID=' + $('#ctl00_CP_hdnSessionid').val(),
//            'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
//            'multi': true,
//            'auto': true
//        });
//    }
//    else {
//        $("#ctl00_CP_FileUpload1").fileUpload({
//            'uploader': '../../../UserControls/MultiFileUpload/uploader.swf',
//            'cancelImg': '../../../Images/cancel.png',
//            'script': '../../../UserControls/MultiFileUpload/Upload.ashx',
//            'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
//            'multi': true,
//            'auto': true
//        });
//    }
//}

var reader = new FileReader();
reader.onload = function (e) {
}
function readURL(input) {
    if (input.files && input.files[0]) {
        reader.readAsDataURL(input.files[0]);
        ajaxFileUpload();
    }
}
function OpenFileUpload() {
    $('#flUpload').click();
}
function LoadingMessage(msg1, msg2) {
    $('#dvTestLoadingmsg').show();
    $('#spn1msg').html(msg1);
    $('#spn2msg').html(msg2);
    $('.hls-bg').show();
}
function CloseLoadingpopup() {
    $('#dvTestLoadingmsg').hide();
    $('.hls-bg').hide();
}
function ajaxFileUpload() {
    if (ValidateImageDetails()) {
        LoadingMessage('Uploading', '<b>Please Wait</b>');
        $("#loading").ajaxStart(function () {
            $(this).show();
        }).ajaxComplete(function () {
            $(this).hide();
        });
        $.ajaxFileUpload({
            url: '/UserControls/MultiFileUpload/common-file-upload.ashx',
            secureuri: false,
            fileElementId: 'flUpload',
            dataType: 'text',
            contentType: "application/json; charset=utf-8",
            data: { name: 'logan', id: 'id', hdn: '1' },
            success: function (response, status) {
                if (response == "-007") {
                    alert('Cannot upload file as the used space exceeds allocated space')
                    return
                }
                if (response == "-008") {
                    alert('Invalid Extention')
                    return
                }
                if (response == "-009") {
                    alert('Cannot include / or .. in a filename')
                    return;
                }
                /*var str = response;
                str = str.replace('<pre style="word-wrap: break-word; white-space: pre-wrap;">','');
                str = str.replace('</pre>','');				
                $('#hdnFileName').val(str);*/
                window.setTimeout(function () {
                    CloseLoadingpopup();
                    $("#ctl00_CP_Label2").text("Uploaded Successfully");
                }, 100);
            },
            error: function (response, status, e) {
                window.setTimeout(function () {
                    CloseLoadingpopup();
                }, 100);
            }
        })
        return false;
    }
}
function isFile(file) {
    var video = /\.(xls|)$/i;
    var CSV = /\.(csv|)$/i;
    var xlsx = /\.(xlsx|)$/i;
    if (video.test(file.toLowerCase()) || CSV.test(file.toLowerCase()) || xlsx.test(file.toLowerCase()))
        return true;
    else
        return false;
}
function ValidateImageDetails() {
    var fields;
    fields = "";
    var file = document.getElementById('flUpload').value;
    //if (isFile(document.getElementById('flUpload').value) == false || document.getElementById('flUpload').value == null) {
    //    fields = fields + "\n-- Invalid file --";
    //}
    if (fields != "") {
        fields = "Please fill in the following details:\n------------------------------------" + fields;
        alert(fields);
        return false;
    }
    else {
        return true;
    }
}

function NumberOnly() {
    var AsciiValue = event.keyCode;
    if ((AsciiValue >= 48 && AsciiValue <= 57) || (AsciiValue == 8 || AsciiValue == 127))
        event.returnValue = true;
    else
        event.returnValue = false;
}

// Mantis : 0027516 : Add Student Search Functionality
function SearchStudent(obj) {
    if (obj.id == 'ctl00_CP_StudentAutoSearchTextBox') {
        var OrgId = $("#ctl00_CP_OrganizationDropDownList").val();
        var BatchId = $("#ctl00_CP_Batch_DropDownList").val();
        if ($(obj).val().length > 1) {
            $.ajax({
                type: "POST",
                url: "/Pages/MaterialManagement/Procurement/StockIssueStudent.aspx/SearchStudent",
                data: '{"SearchValue":"' + $(obj).val() + '", "OrgId": "' + OrgId + '", "BatchId": "' + BatchId + '", "Flag": "' + $("#ctl00_CP_SearchListHiddenField").val() + '"}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    if ($("#ctl00_CP_SearchListHiddenField").val() == "true") {
                        if (data.d.includes("</li>")) {
                            $("#ctl00_CP_SearchListHiddenField").val("false");
                        }
                    }
                    document.getElementById("AutoSearchSuggestion").hidden = false;
                    document.getElementById("AutoSearchSuggestion").innerHTML = data.d;
                },
                error: function (jqXHR, Status, errorMsg) {

                }
            });
        }
        else {
            document.getElementById("AutoSearchSuggestion").hidden = true;
        }
    }
}

document.addEventListener('keydown', function (e) {
    // Add this Page name in StudentSearch.js KeyDown event so that the keydown event is not triggered twice
    var tag = $(e.target).attr("id");
    var tag1 = $(e.target).attr('class');
    if (tag1 == "studentautosearchitem" && (e.keyCode == 37 || e.keyCode == 38 || e.keyCode == 39 || e.keyCode == 40)) {
        switch (e.keyCode) {
            case 37: case 39: case 38: case 40: e.preventDefault();
        }
    }
    if ((tag == "ctl00_CP_StudentAutoSearchTextBox" || e.keyCode == 13) || (e.keyCode == 13 || tag1 == "studentautosearchitem")) {
        Focus();
    }
});

function Focus() {
    var keyCode = window.event.keyCode;
    if (keyCode !== 38 && keyCode !== 40 && keyCode !== 13) return;

    var current = document.activeElement;
    let items = [];
    for (i = 0; i < document.getElementsByClassName('studentautosearchitem').length; i++) {
        items[i] = document.getElementsByClassName('studentautosearchitem')[i];
    }
    var currentIndex = items.indexOf(current);
    var newIndex;

    if (keyCode == 13) {
        selectStudent(items[currentIndex].innerHTML, true);
    }
    else {
        if (currentIndex === -1) {
            newIndex = 0
        } else {
            if (keyCode === 38) newIndex = (currentIndex + items.length - 1) % items.length
            else newIndex = (currentIndex + 1) % items.length
        }
        items[newIndex].focus();
    }
}

function selectStudent(val, IsEnter) {
    $("#ctl00_CP_StudentAutoSearchTextBox").val(val);
    var str = $("#ctl00_CP_StudentAutoSearchTextBox").val();
    if (!IsEnter)
        str = str.substring(0, str.length - 1);

    $("#ctl00_CP_StudentAutoSearchTextBox").val(str);
    //$("#ctl00_CP_SourceCodeTextBox").val(str.substring(str.lastIndexOf(' ') + 1)); //Mantis 35022
    $("#ctl00_CP_SourceCodeTextBox").val(str.substring(str.lastIndexOf('[') + 1, str.lastIndexOf(']')).trim());
    $("#ctl00_CP_SourceCodeTextBox").trigger("change");
    document.getElementById("AutoSearchSuggestion").hidden = true;
}