function OpenFileUpload() {
    $('#flUpload').click();
}

var reader = new FileReader();
var filename = '';
reader.onload = function (e) {
}
function readURL(input) {
    if (input.files && input.files[0]) {
        reader.readAsDataURL(input.files[0]);
        filename = input.files[0].name;

        //Check if same value inserted   
        var flag = false;
        var i = 0;
        var t = document.getElementById('ctl00_CP_OnlineFormSetupTabContainer_OnlineFormSetupAttachmentDetails_UploadOrganizationPhotoGridView');
        $("#ctl00_CP_OnlineFormSetupTabContainer_OnlineFormSetupAttachmentDetails_UploadOrganizationPhotoGridView tr").each(function () {
            var val1 = $(t.rows[i].cells[0]).text();            
            if (val1.indexOf('Logo') != -1 && $("input:radio[name='ctl00$CP$OnlineFormSetupTabContainer$OnlineFormSetupAttachmentDetails$UploadTypeRadioButtonList']:checked").val() == '1') {
                alert('cannot upload logo file again, delete the old one first');
                flag = true;
            }
            if (val1.indexOf('BackgroundImage') != -1 && $("input:radio[name='ctl00$CP$OnlineFormSetupTabContainer$OnlineFormSetupAttachmentDetails$UploadTypeRadioButtonList']:checked").val() == '2') {
                alert('cannot upload Background file again, delete the old one first');
                flag = true;
            }
            i++;
        });

        if (filename.includes('\u008d')) {
            alert('Please use proper filename')
            $('#flUpload')[0].value = '';
        }
        else if (flag == true) {

        }
        else if ($("input:radio[name='ctl00$CP$OnlineFormSetupTabContainer$OnlineFormSetupAttachmentDetails$UploadTypeRadioButtonList']:checked").val() == '1' && (filename.split('.').pop() != 'jpg' && filename.split('.').pop() != 'jpeg' && filename.split('.').pop() != 'png')) {
            alert('Can only upload images in logo')
        }
        else if ($("input:radio[name='ctl00$CP$OnlineFormSetupTabContainer$OnlineFormSetupAttachmentDetails$UploadTypeRadioButtonList']:checked").val() == '2' && (filename.split('.').pop() != 'jpg' && filename.split('.').pop() != 'jpeg' && filename.split('.').pop() != 'png')) {
            alert('Can only upload images in Background Image')
        }
        else if ($("input:radio[name='ctl00$CP$OnlineFormSetupTabContainer$OnlineFormSetupAttachmentDetails$UploadTypeRadioButtonList']:checked").val() == '3' && (filename.split('.').pop() != 'pdf')) {
            alert('Can only upload pdf file')
        }
        else if ($("input:radio[name='ctl00$CP$OnlineFormSetupTabContainer$OnlineFormSetupAttachmentDetails$UploadTypeRadioButtonList']:checked").val() != '3' && input.files.length > 1)
            alert('You can only upload 1 image for Type :- Logo,BackgroundImage');        
        else {
            ajaxFileUpload();
        }
    }
}

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
                }
                window.setTimeout(function () {
                    CloseLoadingpopup();
                    $("#ctl00_CP_OnlineFormSetupTabContainer_OnlineFormSetupAttachmentDetails_UploadSuccessLabel").text("Uploaded Successfully");
                    var a = document.getElementById('ctl00_CP_OnlineFormSetupTabContainer_OnlineFormSetupAttachmentDetails_RefreshButton');
                    a.click();
                }, 100);
            },
            error: function (response, status, e) {
                window.setTimeout(function () {
                    CloseLoadingpopup();
                }, 100);
            }
        })
        return false;
    }
}
function ajaxFileUploadAzure() {
    if (ValidateImageDetails()) {
        LoadingMessage('Uploading', '<b>Please Wait</b>');
        $("#loading").ajaxStart(function () {
            $(this).show();
        }).ajaxComplete(function () {
            $(this).hide();
        });
        var ScreenTypeId = 35;
        var DocumentId = 0;
        if ($('#ctl00_CP_OnlineFormSetupIdHiddenField').val() != '')
            DocumentId = $('#ctl00_CP_OnlineFormSetupIdHiddenField').val();
        var DocumentName = filename;
        var GUID = 0;
        if ($('#ctl00_CP_GUIDHiddenField').val() != '')
            GUID = $('#ctl00_CP_GUIDHiddenField').val();
        $.ajaxFileUpload({
            url: '/UserControls/MultiFileUpload/DocumentUpload.ashx?ScreenTypeId=' + ScreenTypeId + '&UserSourceTypeId=' + 0 + '&UserSourceId=' + 0 + '&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;
                }
                window.setTimeout(function () {
                    CloseLoadingpopup();
                    $("#ctl00_CP_OnlineFormSetupTabContainer_OnlineFormSetupAttachmentDetails_UploadSuccessLabel").text("Uploaded Successfully");
                    var a = document.getElementById('ctl00_CP_OnlineFormSetupTabContainer_OnlineFormSetupAttachmentDetails_RefreshButton');
                    a.click();
                }, 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;
    var jpg = /\.(jpg|)$/i;
    var png = /\.(png|)$/i;
    var jpeg = /\.(jpeg|)$/i;
    var gif = /\.(gif|)$/i;
    var pdf = /\.(pdf|)$/i;
    var pptx = /\.(pptx|)$/i;
    var ppt = /\.(ppt|)$/i;
    var docx = /\.(docx|)$/i;
    var doc = /\.(doc|)$/i;
    var txt = /\.(txt|)$/i;
    var count = document.getElementById('flUpload').files;
    var fileValu = document.getElementById('flUpload');
    var count_file = 0;
    for (var i = 0; i < count.length; i++) {
        var t = fileValu.files[i].name.split('.').pop();
        if (t.toLowerCase() == "jpg" || t.toLowerCase() == "jpeg" || t.toLowerCase() == "png" || t.toLowerCase() == "xls" || t.toLowerCase() == "csv" || t.toLowerCase() == "pdf" || t.toLowerCase() == "docx" || t.toLowerCase() == "doc" || t.toLowerCase() == "txt") {

            count_file = count_file + 1;
        }
        else {
            filename = fileValu.files[i].name;
            return false;
        }
    }
}

function ValidateImageDetails() {
    var fields;
    fields = "";
    var file = document.getElementById('flUpload').value;
    
    var iSize = ($('#flUpload')[0].files[0].size / 1024);
    iSize = (Math.round((iSize / 1024) * 100) / 100);

    if (iSize > 2) {
        alert('cannot upload file more than 2 MB');
        return false;
    }

    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;
    }
}