$(document).ready(function () {
    var workFileSize = 50485760;
    var baseUrl = $('#baseUrl').val();
    var fileObject, workFileName, workFolderName, workFileStatus, workFolderObject;
    var folderStatus, fileNameStatus, fileValidStatus;
    var fileNameCounter, uploadFileCounter = 1;
    var workFileObject = {counter: [1], work_fle_id: [], work_file_name: []};
    var allowedFileType = " zip rar txt rtf pdf gif jpeg jpg png psd epub azw3 cbr lit mobi swf \n\
                                            docx xlsx pub pptx one doc vsdx accdb xlsb mso rpmsg asd xls oft thmx mdb \n\
                                            xlsm mpp obi pst snp xsn olm  ost dotx vsd laccdb accdr wbk pptm dot ppt xlam \n\
                                            onepkg xltx mde docm pip ppsx ppsm accde grv xla slk potx iaf xlt crtx xlb vss \n\
                                            xar xlw pps pa oab  dotm  mpd svd ops pot xlm mpt acl xltm mdt ade xl vst accdc mdw \n\
                                            accdt mat vdx xsf xll sldx mda mar ppam accda ppa vsx puz prf maf vtx potm xlc wll accdp \n\
                                            mam sldm maq accdu cnv maw xslb";

    /* 
     * @Description         : get update work file information
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 04-10-2016 09:29 AM
     * @Status              : Available        
     */
    var workFileUrl = baseUrl + 'user/get-work-file-info';
    $.get(workFileUrl, function (data) {
        var workFileData = JSON.parse(data);

        workFolderObject = workFileData.work_folder_info;
        for (var i = 0, counter = 1; i < workFileData.work_fle_id.length; i++, counter++) {
            folderStatus = fileNameStatus = fileValidStatus = '';
            updateArray(1, counter);
            updateArray(2, workFileData.work_fle_id[i]);
            updateArray(3, workFileData.work_file_name[i]);
        }
    });

    /*
     * @Function            : add_more_course_work_file_button 
     * @Description         : add course work file view
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 22-10-2016 10:02 AM
     * @Status              : Available        
     */
    $('#add_more_course_work_file_button').click(function () {
        var totalDiv = $('#upload_WorkFile_heaader').children('div[id^=upload_WorkFile]').length;

        if (workFileObject.work_fle_id.length === totalDiv) {
            var counter = Math.max.apply(Math, workFileObject.counter);
            $.ajax({
                type: 'post',
                url: baseUrl + 'user/get-more-work-file-view',
                data: {counter: counter, total_div: totalDiv},
                cache: false,
                traditional: true,
                beforeSend: function () {
                    updateButton(true);
                },
                complete: function () {
                    updateButton(false);
                },
                success: function (resposeData) {
                    var data = JSON.parse(resposeData);
                    if (data.error === undefined) {

                        updateArray(1, data.counter);
                        fileNameStatus = fileValidStatus = undefined;
                        fileNameCounter = uploadFileCounter = data.counter;
                        $(data.view_page).hide().appendTo('#upload_WorkFile_heaader').fadeIn(1000);
                    } else {
                        $('#final_error_message').html('Please upload first');
                    }
                }
            });
        } else {
            $('#final_error_message').html('Please upload first');
        }

    });



    /*
     * @Description         : check work file folder name validation
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 05-11-2016 12:03 PM
     * @Status              : Available        
     */
    $(document).on('keyup', 'input[id="work_file_folder_name"]', function () {
        var inputFolderName = $('#' + this.id).val().replace(/  +/g, ' ');
        if (inputFolderName !== '') {
            if (workFolderObject.indexOf(inputFolderName) > -1) {
                folderStatus = 2;
                $('#folder_name_error').html('Folder name already exists').fadeIn(1000);
            } else {
                folderStatus = '';
                $('#folder_name_error').fadeOut('slow');
            }
        } else {
            folderStatus = 1;
            $('#folder_name_error').html('Please type folder name').fadeIn(1000);
        }
    });


    /*
     * @Description         : check work file name validation
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 05-11-2016 12:03 PM
     * @Status              : Available        
     */

    $(document).on('keyup', 'input[id^="work_file_name"]', function () {
        var counter = Number(this.id.replace('work_file_name', ''));
        var counterIndex = workFileObject.counter.indexOf(counter);

        var inputFileName = $('#' + this.id).val().replace(/  +/g, ' ');
        if (inputFileName !== '') {
            if (workFileObject.work_file_name[counterIndex] === inputFileName) {
                fileNameStatus = '';
                $('#file_name_error' + counter).fadeOut('slow');
            } else {
                if (workFileObject.work_file_name.indexOf(inputFileName) > -1) {
                    fileNameStatus = 1;
                    $('#file_name_error' + counter).html('File name already exists').fadeIn('slow');
                } else {
                    fileNameStatus = '';
                    $('#file_name_error' + counter).fadeOut('slow');
                }
            }
        } else {
            fileNameStatus = 1;
            $('#file_name_error' + counter).html('Please type file name').fadeIn('slow');
        }
    });



    /*
     * @Description         : Upload work file
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 22-10-2016 11:02 AM
     * @Status              : Available        
     */
    $(document).on('change', 'input[id^="upload_work_file"]', function () {
        var counter = this.id.replace('upload_work_file', '');
        $('#remaining_work_file_size' + counter).fadeOut('slow');
        updateProgressBar(false, 0, counter);

        if (checkWorkFileValidation(counter) === undefined) {
            $('#work_file_access_level_error' + counter).fadeOut('slow');
            fileObject = $('#upload_work_file' + counter).prop('files')[0];
            $('#upload_work_file' + counter).val('');

            var fileExtention = fileObject.name.split('.').pop().toLowerCase();
            var n = allowedFileType.search(fileExtention);

            if (n < 0) {
                var errorMessage = 'Invalid file type';
                viewErrorMessage(counter, errorMessage);
            } else if (fileObject.size > workFileSize) {
                var errorMessage = 'File size must less then 10 Mb';
                viewErrorMessage(counter, errorMessage);
            } else {
                uploadWorkFile(counter);
            }
        }
    });


    /*
     * @Description         : Delete Single work work file
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 27-10-2016 11:51 AM
     * @Status              : Available        
     */
    $(document).on('click', 'a[id^="deleteWorkFile"]', function () {
        var counter = this.id.replace('deleteWorkFile', '');
        $('#viewDeleteWorkFile' + counter).modal('show');
    }).on('click', 'button[id^="modalNoButton"]', function () {
        var counter = this.id.replace('modalNoButton', '');
        $('#viewDeleteWorkFile' + counter).modal('hide');
    }).on('click', 'button[id^="modalYesButton"]', function () {
        var counter = Number(this.id.replace('modalYesButton', ''));
        var counterIndex = workFileObject.counter.indexOf(counter);

        if(counterIndex > -1){
            $.ajax({
            type: 'post',
            url: baseUrl + 'user/course/delete-work-file',
            data: {counter: counter},
            cache: false,
            traditional: true,
            beforeSend: function () {

                addFileUploadAction();
                updateButton(true);

            },
            complete: function (jqXHR) {
                if ((jqXHR.statusText).toLowerCase() === 'ok') {

                    removeFileUploadAction();
                    updateButton(false);
                    $('#viewDeleteWorkFile' + counter).modal('hide');
                    $('#upload_WorkFile' + counter).remove();
                }
            },
            error: function (jqXHR, textStatus) {
                if (textStatus === 'error') {
                    removeFileUploadAction();
                    updateButton(false);
                    $('#upload_work_file_error' + counter).html('There are some problem please try again later');
                }
            },
            success: function () {
                if (workFileObject.work_fle_id[counterIndex] !== undefined) {
                    workFileObject.counter.splice(counterIndex, 1);
                    workFileObject.work_fle_id.splice(counterIndex, 1);
                    workFileObject.work_file_name.splice(counterIndex, 1);
                } else {
                    workFileObject.counter.splice(counterIndex, 1);
                }
            }
        });
        }
    });

    /*
     * @Function            : uploadWorkFile
     * @Description         : Upload work file
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 22-10-2016 05:25 PM      
     * @Parameter           : Null
     * @Return              : NULL     
     * @Status              : available
     */
    var uploadWorkFile = function (counter) {
        var formData = new FormData();
        formData.append('counter', counter);
        formData.append('work_file_folder_name', workFolderName);
        formData.append('work_file_name', workFileName);
        formData.append('work_file_access_level', workFileStatus);
        formData.append('work_file_data', fileObject);

        $.ajax({
            type: "post",
            url: baseUrl + 'user/upload-course-work-file',
            data: formData,
            async: true,
            processData: false,
            cache: false,
            contentType: false,
            traditional: true,
            beforeSend: function () {

                addFileUploadAction();
                updateButton(true);

            },
            xhr: function () {
                var xhr = $.ajaxSettings.xhr();
                if (xhr.upload) {
                    xhr.upload.addEventListener('progress', function (evt) {

                        var percent = Math.round((evt.loaded / evt.total) * 100);
                        updateProgressBar(true, percent, counter);

                    }, false);
                }
                return xhr;
            },
            complete: function (jqXHR) {
                if ((jqXHR.statusText).toLowerCase() === 'ok') {

                    removeFileUploadAction();
                    updateButton(false);
                }
            },
            error: function (jqXHR, textStatus) {
                if (textStatus === 'error') {

                    updateProgressBar(false, 0, counter);
                    removeFileUploadAction();
                    updateButton(false);
                    fileValidStatus = 1;
                    $('#upload_work_file_error' + counter).html('There are some problem please try again later').fadeIn('slow');
                }
            },
            success: function (responseData) {
                var workFileData = JSON.parse(responseData);

                if (workFileData.error_msg === undefined) {
                    $('#uploadedFileName' + counter).val(fileObject.name);
                    $('#remaining_work_file_size' + counter).html(workFileData.file_size).fadeIn(1000);
                    $('#upload_work_file_error' + counter).fadeOut('slow');
                    fileValidStatus = '';

                    if (workFileData.work_fle_random_id !== undefined) {
                        updateArray(2, workFileData.work_fle_random_id);
                        updateArray(3, workFileData.work_file_name);
                    } else {
                        var counterIndex = workFileObject.counter.indexOf(Number(counter));
                        workFileObject.work_file_name[counterIndex] = workFileData.work_file_name;
                    }

                } else {
                    fileValidStatus = 1;
                    updateProgressBar(false, 0, counter);
//                    removeFileUploadAction();
//                    updateButton(false);
                    var errorMessage = 'There are some problem please try again later';
                    viewErrorMessage(counter, errorMessage);
                }
            }
        });
    };

    /*
     * @Function            : checkWorkFileValidation
     * @Description         : check work file validation
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 22-10-2016 04:52 PM      
     * @Parameter           : counter
     * @Return              : NULL     
     * @Status              : available
     */
    var checkWorkFileValidation = function (counter) {
        var returnValue;
        workFolderName = $('#work_file_folder_name').val();
        workFileName = $('#work_file_name' + counter).val();
        workFileStatus = $('input[name="work_file_access_level[' + counter + ']"]:checked').val();
        if (workFolderName === '') {
            returnValue = 1;
            $('#folder_name_error').html('Please type work file folder name').fadeIn(1000);
        }

        if (workFileName === '') {
            returnValue = 1;
            $('#file_name_error' + counter).html('Please type work file name').fadeIn(1000);
        }

        if (workFileStatus === undefined) {
            returnValue = 1;
            $('#work_file_access_level_error' + counter).html('Please select access level').fadeIn(1000);
        }
        return returnValue;
    };

    /*
     * @Function            : updateArray
     * @Description         : update Array
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 26-10-2016 11:30 AM      
     * @Parameter           : counter
     * @Return              : NULL     
     * @Status              : available
     */
    var updateArray = function (type, value) {
        switch (type) {
            case 1:
                if (workFileObject.counter.indexOf(Number(value)) < 0) {
                    workFileObject.counter.push(Number(value));
                }
                break;
            case 2:
                if (workFileObject.work_fle_id.indexOf(value) < 0) {
                    workFileObject.work_fle_id.push(value);
                }
                break;
            case 3:
                if (workFileObject.work_file_name.indexOf(value) < 0) {
                    workFileObject.work_file_name.push(value);
                }
                break;
        }
    };

    /*
     * @Description         : Skip work file
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 07-11-2016 03:41 PM
     * @Status              : Available        
     */
    $(document).on('click', 'button[id="skip_work_file"]', function () {
        $('#skipWorkFileModal-Skip').modal('show');
    }).on('click', 'button[id^="modalNoButton-Skip"]', function () {
        $('#skipWorkFileModal-Skip').modal('hide');
    }).on('click', 'button[id^="modalYesButton-Skip"]', function () {
        var serverUrl = baseUrl + 'user/course/skip-work-file';

        $.get(serverUrl, function (data) {
            var parseData = JSON.parse(data);
            var base_url = $('#baseUrl').val();
            window.location.replace(base_url+parseData.redirect_url);
        });
    });
    /*
     * @Description         : Submit form
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 05-11-2016 02:21 PM
     * @Status              : Available        
     */
    $('form').submit(function (e) {
        if (folderStatus === undefined || folderStatus !== '') {
            if (folderStatus === undefined) {
                $('#folder_name_error').html('Please type folder name').fadeIn(1000);
            }
            e.preventDefault();
        }
        if (fileNameStatus === undefined || fileNameStatus !== '') {
            if (fileNameStatus === undefined) {
                $('#file_name_error' + fileNameCounter).html('Please type file name').fadeIn(1000);
            }
            e.preventDefault();
        }

        if (fileValidStatus === undefined || fileValidStatus !== '') {
            if (fileValidStatus === undefined) {
                $('#upload_work_file_error' + uploadFileCounter).html('There are some problem please try again later').fadeIn(1000);
            }
            e.preventDefault();
        }
    });



    /*
     * @Description         : viewErrorMessage
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 05-11-2016 06:56 PM
     * @Status              : Available        
     */
    var viewErrorMessage = function (counter, errorMessage) {
        fileValidStatus = 1;
        $('#uploadedFileName' + counter).val('');
        $('#upload_work_file_error' + counter).html(errorMessage).fadeIn('slow');
    };
});




/*
 * @Function            : addFileUploadAction
 * @Description         : change file action while uploading file
 * @Developed By        : MD Jaherul Islam
 * @Start DateTime      : 25-10-2016 04:33 PM      
 * @Parameter           : Null
 * @Return              : NULL     
 * @Status              : available
 */
var addFileUploadAction = function () {
    $('#work_file_folder_name').attr('readonly', '');
    $('input[id^="work_file_name"]').attr('readonly', '');
    $('div[id^="cancelWorkFile"]').attr('style', 'pointer-events: none');
    $('input:radio').attr('disabled', true);
    $('input[id^="upload_work_file"]').attr('disabled', '');
};

/*
 * @Function            : removeFileUploadAction
 * @Description         : change file action while uploading file
 * @Developed By        : MD Jaherul Islam
 * @Start DateTime      : 25-10-2016 04:39 PM      
 * @Parameter           : Null
 * @Return              : NULL     
 * @Status              : available
 */
var removeFileUploadAction = function () {
    $('#work_file_folder_name').removeAttr('readonly');
    $('input[id^="work_file_name"]').removeAttr('readonly', '');
    $('div[id^="cancelWorkFile"]').attr('style', 'pointer-events: visible');
    $('input:radio').attr('disabled', false);
    $('input[id^="upload_work_file"]').removeAttr('disabled', '');
};
/*
 * @Function            : Update button  
 * @Description         : update button status while upload course work file
 * @Developed By        : MD Jaherul Islam
 * @Start DateTime      : 22-10-2016 02:31 PM      
 * @Parameter           : $status[TRUE/FALSE]
 * @Return              : NULL     
 * @Status              : available
 */
var updateButton = function (status) {
    $('#skip_work_file').attr('disabled', status);
    $('#submit_work_file').attr('disabled', status);
    $('#add_more_course_work_file_button').attr('disabled', status);
};

/*
 * @Function            : updateProgressBar
 * @Description         : update progress bar when upload file and get error
 * @Developed By        : MD Jaherul Islam
 * @Start DateTime      : 25-10-2016 02:31 PM      
 * @Parameter           : $status[TRUE/FALSE],percent, counter
 * @Return              : NULL     
 * @Status              : available
 */
var updateProgressBar = function (status, percent, counter) {
    if (status === true) {
        $('#progressBar' + counter).show('slow');
        $('#loadingProgressBar' + counter).attr('style', 'width:' + percent + '%');
        $('#loadingProgressBar' + counter).html((percent === 100) ? 'upload complete' : '' + percent + '% uploading');
    } else {
        $('#progressBar' + counter).hide('slow');
        $('#loadingProgressBar' + counter).attr('style', 'width:' + percent + '%');
        $('#loadingProgressBar' + counter).html('');
    }
};


