var URL = '';
URL = window.location.href;
URL = URL.split('?')[0];
var PageIndexLetest = 1;
var CreatePermission;
var EditPermission;
var DeletePermission;
var ReadPermission;

$(document).ready(function () {
    //$("#txtScreenGroupSearch").autocomplete('/Pages/MaterialManagement/Pharmacy/opd-search.ashx?qur=screen');
    $(".messageMessage").hide();

    if (document.location.href.indexOf('#') != -1)
        document.location.href = String(document.location.href).replace(/#/, "");

    $('#DropDownListParameterType').focus();
    LoadingMessage('Loading Details', '<b>Please Wait ...</b>');
    ShowButtons();
    CloseLoadingpopup();
    $(".close").click(function () {
        $(".messageMessage").hide();
    });

});

function ShowButtons() {
    GetFileUpload('TempImageRepository', "1");
    UploadTypeChange();
}

function OpenFileUpload() {
    var UploadTypeId = $("#ctl00_CP_UploadTypeDropDownList").val();
    if (UploadTypeId == "3")
    {
        GetAttachedFileCount(3);
    }
    if (UploadTypeId == "4")
    {
        GetAttachedFileCount(4);
    }
    if (UploadTypeId == "1" || UploadTypeId == "2" || UploadTypeId == "5") {
        $('#flUpload').click();
    }
}
var reader = new FileReader();
reader.onload = function (e) { }
function readURL(input) {
    if (input.files && input.files[0]) {
        reader.readAsDataURL(input.files[0]);
        filename = input.files[0].name;
        ajaxFileUpload();
        //if ($('#ctl00_CP_UploadConfigurationHiddenField').val() == "Azure") {
        //    ajaxFileUploadAzure();
        //}
        //else {
        //    ajaxFileUpload();
        //}
    }
}
function isFile(file) {
    var video = /\.(PNG|JPEG|JPG|GIF|BMP|PPM|PGM|)$/i;
    if (video.test(file))
        return true;
    else
        return false;
}
function ValidateImageDetails() {
    var fields;
    fields = "";
    var file = document.getElementById('flUpload').value;

    var extention = file.replace(/^.*\./, '');
    if ($("#ctl00_CP_UploadTypeDropDownList").val() == "2" || $("#ctl00_CP_UploadTypeDropDownList").val() == "3" || $("#ctl00_CP_UploadTypeDropDownList").val() == "4" || $("#ctl00_CP_UploadTypeDropDownList").val() == "5") {
        if (extention != "jpg" && extention != "png" && extention != "jpeg") {
            alert('Please upload Image File')
            return;
        }
    }

    //if (isFile(document.getElementById('flUpload').value) == false || document.getElementById('flUpload').value == null) {
    //    fields = fields + "\n-- Please Import Image File --";
    //}
    if (fields != "") {
        fields = "Please fill in the following details:\n------------------------------------" + fields;
        alert(fields);
        return false;
    }
    else {
        return true;
    }
}
function ValidateImageSize() {
    var fields;
    fields = "";
    var file = document.getElementById('flUpload').value;
    var iSize = ($("#flUpload")[0].files[0].size / 1024);
    //iSize = (Math.round((iSize / 1024) * 100) / 100);

    //else if (iSize > 1) {
    //    alert('File should be less than 1 MB');
    //    return false;
    //}
    if ($('#ctl00_CP_AttachmentSizeHiddenField').val() != '') {
        if (iSize > $('#ctl00_CP_AttachmentSizeHiddenField').val()) {
            alert('File should be less than ' + $('#ctl00_CP_AttachmentSizeHiddenField').val() + ' KB');
            return false;
        }
        else {
            return true;
        }
    }
    else {
        return true;
    }
}
function ajaxFileUpload() {
    if (ValidateImageDetails()) {
        if (ValidateImageSize()) {
            $("#loading").show();
            var QueryString = '';
            var UploadType = $("#ctl00_CP_UploadTypeDropDownList").val();
            if (UploadType == "1")
                QueryString = 'TempImageRepository';
            else if (UploadType == "2")
                QueryString = 'StudentBirthdayCard';
            else if (UploadType == "3")
                QueryString = 'Admission';
            else if (UploadType == "4")
                QueryString = 'Inquiry';
            else if (UploadType == "5")
                QueryString = 'EmployeeBirthdayCard';

            //for EmployeeBirthdayCard
            if (UploadType == "5") {
                var DocId = $("#ctl00_CP_EmployeeBirthdayCardCountHiddenField").val();
                //mantisid: 0035580
                if (DocId === null || DocId === undefined || DocId === "") {
                    DocId = 1;
                }
            }
            else {
                var DocId = $("#ctl00_CP_StudentBirthdayCardCountHiddenField").val();
                if (DocId === null || DocId === undefined || DocId === "") {
                    DocId = 1;
                }
            }
          
            $.ajaxFileUpload({
                url: '/UserControls/MultiFileUpload/common-file-upload.ashx?FolderName=' + QueryString + '&DocId=' + DocId,
                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>', '');
                    $('#FileName').val('');
                    $('#FileName').val(str);
                    GetFileUpload('TempImageRepository', $("#ctl00_CP_UploadTypeDropDownList").val());
                    window.setTimeout(function () {
                        $("#loading").hide();
                        // $("#ctl00_MainMessageBoxControl_divMessageType").show();

                        $(".messageMessage").show();
                        $("#maxmin").hide();
                        $(".close").removeAttr("onclick");                        
                        $("#ctl00_CP_MessageControlFile_divMessageType").addClass("successContainer");
                        $("#MessageTextDiv").html("File Uploded Successfully.");                        



                        //document.getElementById("MessageBoxDiv").innerHTML = GetSuccessMessage("File Uploded Successfully");                        
                        window.setTimeout(function () { MessageBoxDivHide(); }, 10000);
                    }, 10000);
                },
                error: function (response, status, e) { }
            })



        }
    }
    return false;
}
function ajaxFileUploadAzure() {
    if (ValidateImageDetails()) {
        if (ValidateImageSize()) {
            LoadingMessage('Uploading', '<b>Please Wait</b>');
            $("#loading").ajaxStart(function () {
                $(this).show();
            }).ajaxComplete(function () {
                $(this).hide();
            });
            var ScreenTypeId = 23;
            var UserSourceTypeId = $('#ctl00_CP_UserSourceTypeHiddenField').val();
            var UserSourceId = $('#ctl00_CP_UserSourceIdHiddenField').val();
            var DocumentId = $('#ctl00_CP_DocumentIdHiddenField').val();
            var DocumentName = '';

            if (DocumentId == "2")
                DocumentName = 'StudentBirthdayCard' + $("#ctl00_CP_StudentBirthdayCardCountHiddenField").val();
            else if (DocumentId == "3")
                DocumentName = 'Admission' + $("#ctl00_CP_StudentBirthdayCardCountHiddenField").val();
            else if (DocumentId == "4")
                DocumentName = 'Inquiry' + $("#ctl00_CP_StudentBirthdayCardCountHiddenField").val();
            else
                DocumentName = filename;

            var GUID = 0;

            $.ajaxFileUpload({
                url: '/UserControls/MultiFileUpload/DocumentUpload.ashx?ScreenTypeId=' + ScreenTypeId + '&UserSourceTypeId=' + UserSourceTypeId + '&UserSourceId=' + UserSourceId + '&DocumentId=' + DocumentId + '&DocumentName=' + DocumentName + '&GUID=' + GUID,
                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;
                    }
                    window.setTimeout(function () {
                        CloseLoadingpopup();
                        $("#ctl00_CP_Label2").text("Uploaded Successfully");
                        GetFileUpload('TempImageRepository', $("#ctl00_CP_UploadTypeDropDownList").val());
                    }, 100);
                },
                error: function (response, status, e) {
                    window.setTimeout(function () {
                        CloseLoadingpopup();
                    }, 100);
                }
            })
            return false;
        }
    }
}

function LoadingMessage(msg1, msg2) {
    $('#dvLoadingmsg').show();
    $('#spn1msg').html(msg1);
    $('#spn2msg').html(msg2);
    $('.hls-bg').show();
}
function CloseLoadingpopup() {
    $('#dvLoadingmsg').hide();
    $('.hls-bg').hide();
}
function GetValidationMsg(msg) {
    var t = '<div class="messageHolder" style="width: 33%;"><div class="himsWireBox" style="width:300%;padding-left:1px"><div class="himsBoxHeader"><div></div></div><div class="himsBoxContent messageMessage"><div class="errorContainer"><div class="fLeft statusImage"><div style="width: 18px; height: 19px;"></div></div><div style="width:98.4 !important;" class="statusMessage fLeft"><div>';
    t += "Mandatory fields are not filled.", t += '</div><div id="hideShowError"><ul>' + msg + '</ul></div></div><div align="right" class="pRight5 cursorHand" id="maxmin"><div id="hideShowImg" class="fRight"><img src="../../../images/minimize.jpg" title="Minimize" onclick="maxmin()" /></div></div><div class="cBoth"></div></div></div><div class="himsBoxFooter"><div></div></div></div></div>';
    return t;
}
function GetErrorMessage(msg) {
    var message = '<div class="messageHolder"><div class="himsWireBox" style="width:300%;padding-left:1px"><div class="himsBoxHeader"><div></div></div><div class="himsBoxContent messageMessage"><div class="errorContainer"><div class="fLeft statusImage"><div style="width: 18px; height: 19px;"></div></div><div style="width:98.4 !important;" class="statusMessage fLeft"><div>';
    message += '</div><div id="hideShowError"><ul>' + msg + '</ul></div></div><div align="right" class="pRight5 cursorHand" id="maxmin"><div id="hideShowImg" class="fRight"><img src="../../../images/minimize.jpg" title="Minimize" onclick="maxmin()" /></div></div><div class="cBoth"></div></div></div><div class="himsBoxFooter"><div></div></div></div></div>';
    return message;
}
function MessageBoxDivHide() {
    document.getElementById("MessageBoxDiv").innerHTML = '';
}

function GetFileUpload(FolderName, UploadType) {

    $.ajax({
        type: "POST",
        url: URL + "/GetOrgId",
        data: '{}',
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function (data) {
            if (parseInt(data.d) == 0) {
                LoadingMessage('Your Session has expired, Redirecting to Login page', '<b>Please Wait ...</b>');
                window.setTimeout(function () { window.location = '/Pages/BaseFramework/Security/Login.aspx'; }, 1000);
            }
            else {
                $.ajax({
                    type: "POST",
                    url: URL + "/GetFileUpload",
                    data: '{"FolderName":"' + FolderName + '", "UploadType":"' + UploadType + '"}',
                    contentType: "application/json;charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        $('#TableImageList').hide();
                        $('#tbodyImageList').html('');
                        if (data.d != "") {
                            $('#TableImageList').show();
                            $('#tbodyImageList').html(data.d);
                            
                            var Numbers = '';
                            var photonumber = 0;
                            var rows = $('#TableImageList tr > td:contains(StudentBirthdayCard)');
                            for (var i = 0; i < rows.length; i++) {
                                if (rows[i].innerText.indexOf("/") == -1) {                                    
                                    var tempphotonumber = parseInt(rows[i].innerText.split('StudentBirthdayCard')[1].split('.')[0]);
                                    Numbers = Numbers + tempphotonumber +  ',';
                                    if (photonumber < tempphotonumber) {
                                        photonumber = tempphotonumber;
                                    }
                                }
                            }
                            if (photonumber > 0) {
                                for (var j = 1; j <= photonumber + 1; j++) {
                                    if (Numbers.indexOf(j) == -1) {
                                        photonumber = j;
                                        $("#ctl00_CP_StudentBirthdayCardCountHiddenField").val(photonumber);
                                        break;
                                    }
                                }
                            }
                            else
                                $("#ctl00_CP_StudentBirthdayCardCountHiddenField").val("1");

                            //for EmployeeBirthdayCard generate cardno in sequence
                            var Numbers1 = '';
                            var photonumber1 = 0;
                            var rows1 = $('#TableImageList tr > td:contains(EmployeeBirthdayCard)');
                            for (var k = 0; k < rows1.length; k++) {
                                if (rows1[k].innerText.indexOf("/") == -1) {
                                    var tempphotonumber1 = parseInt(rows1[k].innerText.split('EmployeeBirthdayCard')[1].split('.')[0]);
                                    Numbers1 = Numbers1 + tempphotonumber1 + ',';
                                    if (photonumber1 < tempphotonumber1) {
                                        photonumber1 = tempphotonumber1;
                                    }
                                }
                            }
                            if (photonumber1 > 0) {
                                for (var l = 1; l <= photonumber1 + 1; l++) {
                                    if (Numbers1.indexOf(l) == -1) {
                                        photonumber1 = l;
                                        $("#ctl00_CP_EmployeeBirthdayCardCountHiddenField").val(photonumber1);
                                        break;
                                    }
                                }
                            }
                            else
                                $("#ctl00_CP_EmployeeBirthdayCardCountHiddenField").val("1");
                        }
                    },
                    error: function (xhr, status, error) {
                        var err = eval("(" + xhr.responseText + ")");
                        console.log(err.Message);
                        document.getElementById("MessageBoxDiv").innerHTML = GetErrorMessage(err.Message);
                        CloseLoadingpopup();
                    }
                });
            }
        },
        error: function (xhr, status, error) {
            var err = eval("(" + xhr.responseText + ")");
            console.log(err.Message);
            CloseLoadingpopup();
        }
    });
}
function DeleteFile(FileName) {
    var a = confirm('Are your Sure want to Delete..! ?');
    if (a) { RemoveFile(FileName); }
}
function GetAttachedFileCount(UploadTypeId) {
    $.ajax({
        type: "POST",
        url: URL + "/GetAttachedFileCount",
        data: '{"UploadTypeId":"' + UploadTypeId + '"}',
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function (data) {
            if (data.d != "") {
                if(UploadTypeId == 3)
                {
                    $("#ctl00_CP_AdmissionAttachmentCountHiddenField").val(data.d);
                    if ($("#ctl00_CP_AdmissionAttachmentCountHiddenField").val() >= 1) {
                        $(".messageMessage").show();
                        $("#maxmin").hide();
                        $(".close").removeAttr("onclick");
                        $("#ctl00_CP_MessageControlFile_divMessageType").addClass("successContainer");
                        $("#MessageTextDiv").html("already uploaded");

                        return;
                    }
                    else if ($("#ctl00_CP_AdmissionAttachmentCountHiddenField").val() == 0) {
                        $('#flUpload').click();
                    }
                }
                if(UploadTypeId == 4)
                {
                    $("#ctl00_CP_InquiryAttachmentCountHiddenField").val(data.d);
                    if ($("#ctl00_CP_InquiryAttachmentCountHiddenField").val() >= 1) {
                        $(".messageMessage").show();
                        $("#maxmin").hide();
                        $(".close").removeAttr("onclick");
                        $("#ctl00_CP_MessageControlFile_divMessageType").addClass("successContainer");
                        $("#MessageTextDiv").html("already uploaded");
                        return;
                    }

                    else if ($("#ctl00_CP_InquiryAttachmentCountHiddenField").val() == 0) {
                        $('#flUpload').click();
                    }
                }
            }
        },
        error: function (xhr, status, error) {
            var err = eval("(" + xhr.responseText + ")");
            console.log(err.Message);
            document.getElementById("MessageBoxDiv").innerHTML = GetErrorMessage(err.Message);
            CloseLoadingpopup();
        }
    });
}
function RemoveFile(FileName) {
    var FolderName = '';
    LoadingMessage('Deleting Image', '<b>Please Wait ...</b>');
    if (FileName.indexOf("StudentBirthdayCard") != -1)
        FolderName = 'StudentBirthdayCard'
    else if (FileName.indexOf("Admission") != -1)
        FolderName = 'Admission'
    else if (FileName.indexOf("Inquiry") != -1)
        FolderName = 'Inquiry'
    else if (FileName.indexOf("EmployeeBirthdayCard") != -1)
        FolderName = 'EmployeeBirthdayCard'
    else
        FolderName = 'TempImageRepository'
    $.ajax({
        type: "POST",
        url: URL + "/GetOrgId",
        data: '{}',
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function (data) {
            if (parseInt(data.d) == 0) {
                LoadingMessage('Your Session has expired, Redirecting to Login page', '<b>Please Wait ...</b>');
                window.setTimeout(function () { window.location = '/Pages/BaseFramework/Security/Login.aspx'; }, 1000);
            }
            else {
                $.ajax({
                    type: "POST",
                    url: URL + "/RemoveUplodedFile",
                    data: '{"FileName":"' + FileName + '","FolderName":"' + FolderName + '"}',
                    contentType: "application/json;charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        GetFileUpload('TempImageRepository', $("#ctl00_CP_UploadTypeDropDownList").val());
                        if (data.d != "") {
                            window.setTimeout(function () {
                                window.setTimeout(function () {
                                    CloseLoadingpopup();

                                    $(".messageMessage").show();
                                    $("#maxmin").hide();
                                    $(".close").removeAttr("onclick");                                    
                                    $("#ctl00_CP_MessageControlFile_divMessageType").addClass("successContainer");
                                    $("#MessageTextDiv").html("File Deleted Successfully.");                                    
                                    window.setTimeout(function () {
                                        MessageBoxDivHide();
                                    }, 5000);
                                }, 1000);
                            }, 1000);
                        }
                    },
                    error: function (xhr, status, error) {
                        var err = eval("(" + xhr.responseText + ")");
                        console.log(err.Message);
                        document.getElementById("MessageBoxDiv").innerHTML = GetErrorMessage(err.Message);
                        CloseLoadingpopup();
                    }
                });
            }
        },
        error: function (xhr, status, error) {
            var err = eval("(" + xhr.responseText + ")");
            console.log(err.Message);
            CloseLoadingpopup();
        }
    });
}

$(document).keydown(function (e) {
    if (e.keyCode == 27) { $('.hls-bg').hide(); $('#dvTipspopup').hide(); $('#buttonOpenTips').focus(); }
});

function copyToClipboard(element) {
    var text = $(element).parent().parent().find('span').html()
    element = $('<textarea>').appendTo('body').val(text).select()
    document.execCommand('copy')
    element.remove()
}

function UploadTypeChange() {
    var UploadType = $("#ctl00_CP_UploadTypeDropDownList").val();
    if (UploadType == "-1") {
        UploadType = "0"
        $("#UploadDiv").hide();
    }
    else
        $("#UploadDiv").show();

    if (UploadType == "1")
        $("#ctl00_CP_DocumentIdHiddenField").val("1");
    else if (UploadType == "2")
        $("#ctl00_CP_DocumentIdHiddenField").val("2");
    if (UploadType == "3")
        $("#ctl00_CP_DocumentIdHiddenField").val("3");
    else if (UploadType == "4")
        $("#ctl00_CP_DocumentIdHiddenField").val("4");
    else if (UploadType == "5")
        $("#ctl00_CP_DocumentIdHiddenField").val("5")

    GetFileUpload("StudentBirthdayCard", UploadType);
}