
var {
    api,
    site_title,
    api_path,
    uploads_path,
    secret,
    notifications_sound
} = proxim;

api['data/upload'] = api_path + "/data/upload";
api['data/load'] = api_path + "/data/load";
api['user/picture'] = api_path + "/user/remove-picture";

function formatFileSize(bytes) {
    if (typeof bytes !== 'number') {
        return 'processing...';
    }
    if (bytes >= 1000000000) {
        return (bytes / 1000000000).toFixed(2) + ' GB';
    }
    if (bytes >= 1000000) {
        return (bytes / 1000000).toFixed(2) + ' MB';
    }
    return (bytes / 1000).toFixed(2) + ' KB';
}

function uploadFilesTransport(data) {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        // Add any event handlers here...
        xhr.open('POST', `${api_path}/files/upload`, true);

        xhr.onload = function () {
            if (this.status >= 200 && this.status < 300) {
                resolve(xhr.response);
            } else {
                reject({
                    status: this.status,
                    statusText: xhr.statusText
                });
            }
        };

        xhr.setRequestHeader('Cache-Control',
            'max-age=0');
        xhr.setRequestHeader('If-Modified-Since',
            'Sat, 01 Jan 2000 00:00:00 GMT');
        xhr.setRequestHeader('Accept',
            'application/json');

        xhr.addEventListener("progress",
            progress => uploadProgress({
                progress: progress,
                instanceId: data.get('instanceId')
            }));
        xhr.upload.addEventListener("progress",
            progress => uploadProgress({
                progress: progress,
                instanceId: data.get('instanceId')
            }));

        xhr.send(data);
    })
}

/** File Upload Progress */
function uploadProgress({ progress, instanceId }) {
    const { total, loaded } = progress;
    const percent = Math.min(100, (loaded / total) * 100) || 0;

    const formFile = $(`[data-id='${instanceId}']`);
    formFile.find(".FormFile__upload-progress-bar").width(`${percent}%`);
}

// initialize the modal (plugins)
function initialize_modal() {

     /*Summernote editor*/
     if ($("#summernote").length) {
        var $height = $("#summernote").data('height') || 450;
        $('#summernote').summernote({
            height: $height,
            tabsize: 2
        });
    }

    /* Ckeditor*/
    if ($("#ckeditor").length) {
        $ckeditor = document.querySelector( '#ckeditor' );
        var $height = $ckeditor.getAttribute('height') || 200;

        ClassicEditor
            .create( $ckeditor, {
                toolbar: [ 'heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', 'indent', 'outdent', 'insertTable', 'undo', 'redo' ]
            }).then( editor => {
                // Set custom height via jQuery by appending a scoped style
                $(`<style type="text/css" scoped>.ck-editor .ck-editor__editable_inline {min-height: ${$height}px !important;}</style>`).insertAfter($ckeditor);
        
            });
    }

    // run bootstrap selectpicker plugin
    $('.selectpicker').selectpicker({
        style: 'btn-option'
    });

    // init datetimepicker plugin
    if ($(".js_datetimepicker").length > 0) {
        $('.js_datetimepicker').datetimepicker({
            format: "DD-MM-YYYY HH:mm",
            locale: $('html').attr('lang').split("_", 1).toString() || 'en'
        });
    }

    // run autosize (expand textarea) plugin
    autosize($('.js_autosize'));

    // run uploader 
    initialize_uploader();

    initialize_dropzone();

    initialize_stepper();
}

function initialize_stepper() {
    $(".incr-btn").unbind('click').click(function (e) {
        e.preventDefault();
        var $button = $(this);
        var oldValue = $button.parent().find('.quantity').val();
        
        if (!oldValue.length) {
            oldValue = 0;
        }

        $button.parent().find('.incr-btn[data-action="decrease"]').removeClass('inactive');
        if ($button.data('action') == "increase") {
            var newVal = parseFloat(oldValue) + 1;
        } else {
            // Don't allow decrementing below 1
            if (oldValue > 1) {
                var newVal = parseFloat(oldValue) - 1;
            } else {
                newVal = $button.parent().find('.quantity').data('minvalue');
                $button.addClass('inactive');
            }
        }
        $button.parent().find('.quantity').val(newVal);
        e.preventDefault();
    });
}

function initialize_dropzone() {
    var dropArea = document.getElementsByClassName('js_dropzone');

    if(dropArea.length) {
        dropArea = dropArea[0];
        dropArea.addEventListener('dragenter', dropzoneHandler, false);
        dropArea.addEventListener('dragleave', dropzoneHandler, false);
        dropArea.addEventListener('dragover', dropzoneHandler, false);
        dropArea.addEventListener('drop', dropzoneHandler, false);
    }
    
}

function dropzoneHandler(e) {
    e.preventDefault();
    const files = Array.from(e.dataTransfer ? e.dataTransfer.files : e.target.files);

    const files_control = $(this);
    const publisher = files_control.parents('.js_files-uploader');
    const uploads_area = files_control.find('.files-control--files');
    const dragEnteredElements = [];
    const fileElement = files_control.find('[type="file"]');
    const handle = fileElement.data('handle') || 'order';

    Promise.all(
        files.map(blob => new Promise((resolve, reject) => {
            const instanceId = Math.round(Math.random() * Number.MAX_SAFE_INTEGER);
            const file = {
                is_order: handle == 'order' ? true : false,
                filename: blob.name,
                size: formatFileSize(blob.size),
                extension: blob.name.match(/[a-z]+$/),
                id: instanceId,
                isUploaded: false
            };

            this.progressTotal = 0;
            this.progressLoaded = 0;

            uploads_area.append(render_template("#form-file", file));

            const data = new window.FormData();
            data.append('files[]', blob);
            data.append('handle', handle);
            data.append('instanceId', instanceId);

            if(handle == 'order') {
                const orderId = fileElement.data('id');
                data.append('orderId', orderId);
            }

            var formFile = $(`[data-id='${instanceId}']`);
            var error = formFile.find('.alert.alert-danger');

            uploadFilesTransport(data)
                .then((response) => {
                    response = JSON.parse(response);
                    formFile.find("[name='uploadTypeId']").attr('disabled', false);
                    formFile.find('.FormFile__remove-button').attr('disabled', false);
                    formFile.find(".FormFile__upload-progress").remove();

                    /* handle response */
                    if (response.error) {
                        error.html(response.message).slideDown();
                    } else {
                        const uploadedFile = response.file;
                        formFile.attr('data-id', uploadedFile.id);
                        formFile.data('id', uploadedFile.id);

                        if (!publisher.data('files')) {
                            publisher.data('files', {});
                        }

                        let files = publisher.data('files');
                        files[uploadedFile.id] = uploadedFile;
                        publisher.data('files', files);

                        if (Object.keys(files).length > 0) {
                            publisher.find('button[type="submit"]').attr('disabled', false);
                        }
                    }
                })
        })
            .catch(() => { })
        ));
}

// initialize uploader
function initialize_uploader() {
    $('.js_x-uploader').each(function (index) {
        /* return if the plugin already running  */
        if ($(this).parents('form.x-uploader').length > 0) {
            return;
        }
        var multiple = ($(this).data('multiple') !== undefined) ? true : false;
        $(this).before(render_template("#x-uploader", { 'url': api['data/upload'], 'secret': secret, 'multiple': multiple }));
        $(this).prev().append($(this));
    });

    $(document).on('change', '.FormFile__upload-type-control [name="uploadTypeId"]', function (e) {
        e.preventDefault();
        const _this = $(this);
        const uploadTypeId = _this.val();
        const formFile = _this.closest('.FormFile');
        const fileId = formFile.data('id');
        const publisher = $('.js_files-uploader');
        if (!publisher.data('files')) {
            publisher.data('files', {});
        }

        let files = publisher.data('files');

        if (Object.keys(files).length == 0) {
            return;
        }

        files[fileId].uploadTypeId = uploadTypeId;
        publisher.data('files', files);
    });

    $(document).on('click', '.FormFile__remove-button', function (e) {
        e.preventDefault();
        const _this = $(this);
        const formFile = _this.closest('.FormFile');
        const fileId = formFile.data('id');
        const publisher = $('.js_files-uploader');

        if (!publisher.data('files')) {
            publisher.data('files', {});
        }
        let files = publisher.data('files');

        if (files[fileId] !== undefined) {
            delete files[fileId];
        }

        formFile.remove();

        publisher.data('files', files);
        if (files !== undefined) {
            if (Object.keys(files).length == 0) {
                publisher.removeData('files');
            }
        }
    });
}

// browser notification
function browser_notification(icon, body, url, tag) {
    /* check if the browser supports notifications */
    if (!("Notification" in window)) {
        return;
    }
    /* check whether notification permissions have alredy been granted */
    if (Notification.permission !== "granted") {
        /* request permission */
        Notification.requestPermission();
    } else {
        /* send notification */
        var notification = new Notification(site_title, {
            icon: icon,
            body: body,
            tag: tag
        });
        notification.onclick = function () {
            window.open(url);
            notification.close();
        };
    }
}

// notification highlighter
function notification_highlighter() {
    try {
        var search_params = new URLSearchParams(window.location.search);
        var notify_id = search_params.get("notify_id");
    } catch (err) {
        var notify_id = getParameterByName("notify_id");
    }
    if (notify_id) {
        var _elem = $('#' + notify_id);
        if (_elem.length > 0) {
            $('html, body').animate({
                scrollTop: _elem.offset().top
            }, 1000);
            _elem.find('.js_notifier-flasher:first').addClass("x-notifier");
            setTimeout(function () {
                _elem.find('.js_notifier-flasher:first').removeClass("x-notifier");
            }, '2500');
        }
    }
}

// data heartbeat
function data_heartbeat() {
    var data = {};

    data['last_message'] = $(".js_live-messages").find(".js_scroller li:first").data('id') || 0;
    data['last_notification'] = $(".js_live-notifications").find(".js_scroller li:first").data('id') || 0;

    $.post(api_path + '/data/live', data, function (response) {
        if (response.callback) {
            eval(response.callback);
        } else {
            if (response.messages) {
                if ($(".js_live-messages").find(".js_scroller ul").length > 0) {
                    $(".js_live-messages").find(".js_scroller ul").prepend(response.messages);
                } else {
                    $(".js_live-messages").find(".js_scroller").html("<ul>" + response.messages + "</ul>");
                }

                var messages = parseInt($(".js_live-messages").find("span.label").text()) + response.messages_count;
                $(".js_live-messages").find("span.label").text(messages).removeClass("hidden");
                $("#chat_sound")[0].play();
            }
            
            if (response.notifications) {
                $.each(response.notifications_json, function (index, element) {
                    /* send browser notifications */
                    browser_notification(element.user_picture, element.full_message, element.url, element.notification_id);
                });
                
                if ($(".js_live-notifications").find(".js_scroller ul").length > 0) {
                    $(".js_live-notifications").find(".js_scroller ul").prepend(response.notifications);
                } else {
                    $(".js_live-notifications").find(".js_scroller").html("<ul>" + response.notifications + "</ul>");
                }

                var notifications = parseInt($(".js_live-notifications").find("span.label").text()) + response.notifications_count;
                $(".js_live-notifications").find("span.label").text(notifications).removeClass("hidden");
                if (notifications_sound) {
                    $("#notification_sound")[0].play();
                }
            }

            setTimeout('data_heartbeat();', 10000);
        }
    }, 'json');
}

// load more
function load_more(element) {
    if (element.hasClass('done') || element.hasClass('loading')) return;
    var _this = element;
    var loading = _this.find('.loader');
    var text = _this.find('span');
    var remove = _this.data('remove') || false;
    var stream = _this.parent().find('ul:first');
    /* prepare data object */
    var data = {};
    data['get'] = _this.data('get');
    if (_this.data('filter') !== undefined) {
        data['filter'] = _this.data('filter');
    }
    if (_this.data('type') !== undefined) {
        data['type'] = _this.data('type');
    }
    if (_this.data('uid') !== undefined) {
        data['uid'] = _this.data('uid');
    }
    if (_this.data('id') !== undefined) {
        data['id'] = _this.data('id');
    }
    data['offset'] = _this.data('offset') || 1; /* we start from iteration 1 because 0 already loaded */
    /* show loader & hide text */
    _this.addClass('loading');
    text.hide();
    loading.removeClass('x-hidden');
    /* get & load data */
    $.post(api['data/load'], data, function (response) {
        _this.removeClass('loading');
        text.show();
        loading.addClass('x-hidden');
        /* check the response */
        if (response.callback) {
            eval(response.callback);
        } else {
            if (response.data) {
                data['offset']++;
                if (response.append) {
                    stream.append(response.data);
                } else {
                    stream.prepend(response.data);
                }
            } else {
                if (remove) {
                    _this.remove();
                } else {
                    _this.addClass('done');
                    text.text('There is no more data to show');
                }
            }
        }
        _this.data('offset', data['offset']);
    }, 'json')
        .fail(function () {
            _this.removeClass('loading');
            text.show();
            loading.addClass('x-hidden');
            modal('#modal-message', { title: 'Error', message: 'There is something that went wrong!' });
        });
}

$(function () {

    // run metisMenu
    $(".js_metisMenu").metisMenu();

    // init bootstrap selectpicker plugin
    $('.selectpicker').selectpicker({
        style: 'btn-option'
    });

    // init browser notifications
    if (("Notification" in window)) {
        if (Notification.permission !== "granted") {
            Notification.requestPermission();
        }
    }

    // run notification highlighter
    notification_highlighter();

    // run data heartbeat
    data_heartbeat();

    // run the stepper
    initialize_stepper();

    // run x-uploader
    /* initialize the uplodaer */
    initialize_uploader();
    $(document).ajaxComplete(function () {
        initialize_uploader();
    });

    /*Summernote editor*/
    if ($("#summernote").length) {
        var $height = $("#summernote").data('height') || 450;
        $('#summernote').summernote({
            height: $height,
            tabsize: 2
        });
    }

    /* Ckeditor*/
    if ($("#ckeditor").length) {
        $ckeditor = document.querySelector( '#ckeditor' );
        var $height = $ckeditor.getAttribute('height') || 200;

        ClassicEditor
            .create( $ckeditor, {
                toolbar: [ 'heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', 'indent', 'outdent', 'insertTable', 'undo', 'redo' ]
            }).then( editor => {
                // Set custom height via jQuery by appending a scoped style
                $(`<style type="text/css" scoped>.ck-editor .ck-editor__editable_inline {min-height: ${$height}px !important;}</style>`).insertAfter($ckeditor);
        
            });
    }

    /* stop propagation */
    $(document).on('click', '.x-uploader', function (e) {
        /* get type */
        var type = $(this).find('.js_x-uploader').data('type') || "photos";
        if (type == "photos") {
            e.stopPropagation();
        }
    });

    /* initialize uploading */
    $(document).on('change', '.x-uploader input[type="file"]', function () {
        $(this).parent('.x-uploader').submit();
    });

    /* uploading */
    $(document).on('submit', '.x-uploader', function (e) {
        e.preventDefault;
        /* initialize AJAX options */
        var options = {
            dataType: "json",
            uploadProgress: _handle_progress,
            success: _handle_success,
            error: _handle_error,
            resetForm: true
        };
        options['data'] = {};
        /* get uploader input */
        var uploader = $(this).find('input[type="file"]');
        /* get type */
        var type = $(this).find('.js_x-uploader').data('type') || "photos";
        options['data']['type'] = type;
        /* get handle */
        var handle = $(this).find('.js_x-uploader').data('handle');
        if (handle === undefined) {
            return false;
        }
        options['data']['handle'] = handle;
        /* get multiple */
        var multiple = ($(this).find('.js_x-uploader').data('multiple') !== undefined) ? true : false;
        options['data']['multiple'] = multiple;
        /* get id */
        var id = $(this).find('.js_x-uploader').data('id');
        if (id !== undefined) {
            options['data']['id'] = id;
        }
        /* check type */
        if (type == "photos") {
            /* check handle */
            if (handle == "picture-user") {
                var loader = $('.profile-avatar-change-loader');
                loader.show();

            } else if (handle == "x-image") {
                var parent = $(this).parents('.x-image');
                var loader = parent.find('.loader');
                loader.show();
            }
        } else if (type == "video" || type == "audio" || type == "file") {
            /* check handle */
            if (handle == "publisher") {
                /* show upload loader */
                var publisher = $('.publisher');
                /* check if there is current (uploading|scrabing|video|audio) process */
                if (publisher.data('photos') || publisher.data('scrabing') || publisher.data('video') || publisher.data('audio') || publisher.data('file')) {
                    return false;
                }
                publisher.data(type, {});
                var attachments = $('.publisher-attachments');
                var loader = $('<ul></ul>').appendTo(attachments);
                attachments.show();
                $('<li class="loading"><div class="loader loader_small"></div></li>').appendTo(loader).show();
            }
        }

        /* handle progress */
        function _handle_progress(e) {
            /* disable uploader input during uploading */
            uploader.prop('disabled', true);
        }
        /* handle success */
        function _handle_success(response) {
            /* enable uploader input */
            uploader.prop('disabled', false);
            /* hide upload loader */
            if (loader) loader.hide();
            /* handle the response */
            if (response.callback) {
                eval(response.callback);
            } else {
                /* check type */
                if (type == "photos") {
                    /* check the handle */
                    if (handle == "picture-user") {
                        /* update (user|page|group) picture */
                        var image_path = uploads_path + '/' + response.file;
                        $('.profile-avatar-wrapper img').attr("src", image_path);

                    } else if (handle == "x-image") {
                        /* update x-image picture */
                        var image_path = uploads_path + '/' + response.file;
                        parent.css("background-image", 'url(' + image_path + ')');
                        /* add the image to input */
                        parent.find('.js_x-image-input').val(response.file);
                        /* show the remover */
                        parent.find('button').show();
                    }
                }
            }
        }

        /* handle error */
        function _handle_error() {
            /* enable uploader input */
            uploader.prop('disabled', false);
            /* hide upload loader */
            if (loader) loader.hide();
            /* check the handle */
            if (handle == "publisher") {
                /* hide the attachment from publisher */
                if ((type == "photos" && jQuery.isEmptyObject(publisher.data('photos'))) || type != "photos") {
                    attachments.hide();
                }
                /* remove upload loader */
                if (loader) loader.remove();
            }
            modal('#modal-message', { title: 'Error', message: 'There is something that went wrong!' });
        }
        /* submit the form */
        $(this).ajaxSubmit(options);
        return false;
    });

    /* handle profile (picture) remover */
    $(document).on('click', '.js_delete-picture', function (e) {
        e.stopPropagation();
        var id = $(this).data('id');
        var handle = $(this).data('handle');
        var remove = ($(this).hasClass('js_delete-cover')) ? 'cover' : 'picture';

        var wrapper = $('.profile-avatar-wrapper');

        confirm('Delete Picture', 'Are you sure you want to remove your profile picture?', function () {
            $.post(api['user/picture'], { 'handle': handle, 'id': id }, function (response) {
                /* check the response */
                if (response.callback) {
                    eval(response.callback);
                } else {
                    /* hide delete btn  */
                    wrapper.find('.profile-avatar-delete').hide();
                    /* update (user) picture with default picture */
                    wrapper.find('img').attr("src", response.file);
                    $('#modal').modal('hide');
                }
            }, 'json')
                .fail(function () {
                    modal('#modal-message', { title: 'Error', message: 'There is something that went wrong!' });
                });
        });
    });

    /* handle x-image remover */
    $(document).on('click', '.js_x-image-remover', function () {
        var _this = $(this);
        var parent = _this.parents('.x-image');
        confirm('Delete', 'Are you sure you want to delete this?', function () {
            /* remove x-image image */
            parent.attr('style', '');
            /* add the image to input */
            parent.find('.js_x-image-input').val('');
            /* hide the remover */
            _this.hide();
            /* hide the confimation */
            $('#modal').modal('hide');
        });
    });

    // run load-more
    /* load more data by click */
    $('body').on('click', '.js_see-more', function () {
        load_more($(this));
    });
    /* load more data by scroll */
    $('.js_see-more-infinite').bind('inview', function (event, visible) {
        if (visible == true) {
            load_more($(this));
        }
    });

    // handle data reseter
    $('body').on('click', '.js_live-messages, .js_live-notifications', function () {
        var _this = $(this);
        var counter = parseInt(_this.find("span.label").text()) || 0;
        if (!$(this).hasClass('open') && counter > 0) {
            /* reset the client counter & hide it */
            _this.find("span.label").addClass('hidden').text('0');
            /* get the reset target */
            if (_this.hasClass('js_live-messages')) {
                var data = { 'reset': 'messages' };
            } else if (_this.hasClass('js_live-notifications')) {
                var data = { 'reset': 'notifications' };
            }
            /* reset the server counter */
            $.post(api_path + '/data/reset', data, function (response) {
                /* check the response */
                if (!response) return;
                /* check if there is a callback */
                if (response.callback) {
                    eval(response.callback);
                }
            }, 'json')
                .fail(function () {
                    modal('#modal-message', { title: 'Error', message: 'There is something that went wrong!' });
                });
        }
    });

    // handle notifications sound
    $(document).on('click', '.js_notifications-sound-toggle', function () {
        notifications_sound = $(this).is(":checked");
        $.get(api_path + '/user/settings', { 'edit': 'notifications_sound', 'notifications_sound': (notifications_sound) ? 1 : 0 }, function (response) {
            /* check the response */
            if (!response) return;
            /* check if there is a callback */
            if (response.callback) {
                eval(response.callback);
            }
        }, 'json')
            .fail(function () {
                modal('#modal-message', { title: 'Error', message: 'There is something that went wrong!' });
            });
    });

    /* assign user */
    $(document).on('click', '.js_assign-order', function (e) {
        e.preventDefault();
        var uid = $(this).data('uid');
        var oid = $(this).data('oid');

        confirm('Assign Order', 'Are you sure you want to assign this order to writer U' + uid + '?', function () {
            $.post(api_path + '/orders/' + oid + '/assign', { 'do': 'assign', 'uid': uid }, function (response) {
                if (response.callback) {
                    eval(response.callback);
                }

                window.location.reload;
            }, 'json')
                .fail(function () {
                    modal('#modal-message', { title: 'Error', message: 'There is something that went wrong!' });
                });
        });
    });

    /* complete order */
    $(document).on('click', '.js_complete-order', function (e) {
        e.preventDefault();
        var oid = $(this).data('oid');

        confirm('Mark as Complete', 'If all the requirements of this order are met, please, proceed with submitting your paper.', function () {
            $.post(api_path + '/orders/' + oid + '/complete', { 'do': 'complete' }, function (response) {
                if (response.callback) {
                    eval(response.callback);
                }

                window.location.reload;
            }, 'json')
                .fail(function () {
                    modal('#modal-message', { title: 'Error', message: 'There is something that went wrong!' });
                });
        });
    });

    /* deliver order */
    $(document).on('click', '.js_deliver-order', function (e) {
        e.preventDefault();
        var oid = $(this).data('oid');

        confirm('Deliver order to Customer', 'Are you sure you want to send this paper to the customer?', function () {
            $.post(api_path + '/orders/' + oid + '/deliver', { 'do': 'deliver' }, function (response) {
                if (response.callback) {
                    eval(response.callback);
                }

                window.location.reload;
            }, 'json')
                .fail(function () {
                    modal('#modal-message', { title: 'Error', message: 'There is something that went wrong!' });
                });
        });
    });

    /* take order */
    $(document).on('click', '.js_take-order', function (e) {
        e.preventDefault();
        var oid = $(this).data('oid');

        confirm('Take order', 'Are you sure you want to take and work on this order?.', function () {
            $.post(api_path + '/orders/' + oid + '/take', { 'do': 'take' }, function (response) {
                if (response.callback) {
                    eval(response.callback);
                }

                window.location.reload;
            }, 'json')
                .fail(function () {
                    modal('#modal-message', { title: 'Error', message: 'There is something that went wrong!' });
                });
        });
    });

    // place bid
    $(document).on('click', '.js_place-bid', function (e) {
        e.preventDefault();
        var oid = $(this).data('oid');

        confirm('Apply for this order', 'Are you sure you want to apply for this order?.', function () {
            $.post(api_path + '/orders/' + oid + '/apply', { 'do': 'apply' }, function (response) {
                if (response.callback) {
                    eval(response.callback);
                }

                window.location.reload;
            }, 'json')
                .fail(function () {
                    modal('#modal-message', { title: 'Error', message: 'There is something that went wrong!' });
                });
        });
    });

    // remove bid
    $(document).on('click', '.js_remove-bid', function (e) {
        e.preventDefault();
        var oid = $(this).data('oid');
        var bid = $(this).data('bid');

        confirm('Delete my Bid', 'Are you sure you want to delete your bid for this order?.', function () {
            $.post(api_path + '/orders/' + oid + '/remove_bid', { 'do': 'remove_bid', 'bid_id': bid }, function (response) {
                if (response.callback) {
                    eval(response.callback);
                }

                window.location.reload;
            }, 'json')
                .fail(function () {
                    modal('#modal-message', { title: 'Error', message: 'There is something that went wrong!' });
                });
        });
    });

    // confirm order
    $(document).on('click', '.js_confirm-order', function (e) {
        e.preventDefault();
        var oid = $(this).data('oid'),
            action = $(this).data('action');

        let title = description = "";

        if (action == "accept") {
            title = 'Accept Order Request';
            description = 'Support team assigned you this order. Are you sure you want to confirm this order request?';
        } else {
            title = 'Reject Order Request';
            description = 'Support team assigned you this order. Are you sure you want to decline this order request?';
        }

        confirm(title, description, function () {
            $.post(api_path + '/orders/' + oid + '/confirm', { 'do': action }, function (response) {
                if (response.callback) {
                    eval(response.callback);
                }

                window.location.reload;
            }, 'json')
                .fail(function () {
                    modal('#modal-message', { title: 'Error', message: 'There is something that went wrong!' });
                });
        });
    });

    // request payment
    $(document).on('click', '.js_request-payment', function (e) {
        e.preventDefault();

        confirm('Request Payment', 'Are you sure you want to send this request?', function () {
            $.post(api_path + '/user/request-payment', function (response) {
                if (response.callback) {
                    eval(response.callback);
                }

                window.location.reload;
            }, 'json')
                .fail(function () {
                    modal('#modal-message', { title: 'Error', message: 'There is something that went wrong!' });
                });
        });
    });

    // show message
    $(document).on('click', '.OrderMessageHeader', function (e) {
        e.preventDefault();
        var _this = $(this);
        var _parent = _this.parent();
        var mid = _parent.data('id');
        var is_read = _parent.data('read');

        _parent.find('.replyBox').toggleClass("x-hidden");

        if (!is_read) {
            $.post(api_path + '/messages/' + mid + '/read', { 'message_id': mid }, function (response) {
                _parent.removeClass('OrderMessage-new');
            }, 'json');
        }
    });

    $(document).on('click', '.files-control .browse-button', function (e) {
        e.preventDefault();
        $(document).find('body').removeClass('dragging-file');
        const files_control = $(this).closest('.files-control');
        const publisher = files_control.parents('.js_files-uploader');
        const uploads_area = files_control.find('.files-control--files');
        const dragEnteredElements = [];
        const fileElement = files_control.find('[type="file"]');
        const handle = fileElement.data('handle') || 'order';
        fileElement.click();

        fileElement.on('change', function (e) {
            const files = Array.from(e.dataTransfer ? e.dataTransfer.files : e.target.files);
            e.target.value = '';

            Promise.all(
                files.map(blob => new Promise((resolve, reject) => {
                    const instanceId = Math.round(Math.random() * Number.MAX_SAFE_INTEGER);
                    const file = {
                        is_order: handle == 'order' ? true : false,
                        filename: blob.name,
                        size: formatFileSize(blob.size),
                        extension: blob.name.match(/[a-z]+$/),
                        id: instanceId,
                        isUploaded: false
                    };

                    this.progressTotal = 0;
                    this.progressLoaded = 0;

                    uploads_area.append(render_template("#form-file", file));

                    const data = new window.FormData();
                    data.append('files[]', blob);
                    data.append('instanceId', instanceId);
                    data.append('handle', handle);

                    if(handle == 'order') {
                        const orderId = fileElement.data('id');
                        data.append('orderId', orderId);
                    }
                    
                    var formFile = $(`[data-id='${instanceId}']`);
                    var error = formFile.find('.alert.alert-danger');

                    uploadFilesTransport(data)
                        .then((response) => {
                            response = JSON.parse(response);
                            if(handle == 'order') {
                                formFile.find("[name='uploadTypeId']").attr('disabled', false);
                            }

                            formFile.find('.FormFile__remove-button').attr('disabled', false);
                            formFile.find(".FormFile__upload-progress").remove();

                            /* handle response */
                            if (response.error) {
                                error.html(response.message).slideDown();
                            } else {
                                const uploadedFile = response.file;
                                formFile.attr('data-id', uploadedFile.id);
                                formFile.data('id', uploadedFile.id);

                                if (!publisher.data('files')) {
                                    publisher.data('files', {});
                                }

                                let files = publisher.data('files');
                                files[uploadedFile.id] = uploadedFile;
                                publisher.data('files', files);

                                if (Object.keys(files).length > 0) {
                                    publisher.find('button[type="submit"]').attr('disabled', false);
                                }
                            }
                        })
                })
                    .catch(() => { })
                ));
        });
    });

    $(document).on('submit', '.js_files-uploader', function (e) {
        e.preventDefault();
        var publisher = $(this);
        var error = publisher.find(".alert.alert-danger");
        var handle = publisher.data('handle') || 'order';
        var files = publisher.data('files');

        if (files === undefined || Object.keys(files).length == 0) {
            return;
        }

        var actionURL;

        if(handle == 'order') {
            var order_id = publisher.data('oid');
            var upload_for = publisher.find('[name="upload_for"]:checked').val() || "me";
            if (order_id === undefined) {
                return;
            }

            order_id = parseInt(order_id);
            actionURL = `${api_path}/orders/${order_id}/upload_files?upload_for=${upload_for}`;
        } else if( handle == 'plugin' ) {
            actionURL = `${api_path}/modules/upload`;
        }

        for (var file in files) {
            var formFile = publisher.find(`[data-id='${files[file].id}']`);
            var fileError = formFile.find('.alert.alert-danger');

            if(handle == 'order') {
                if (!files[file].uploadTypeId) {
                    fileError.html("Select the file type").slideDown();
                    return;
                } else {
                    fileError.slideUp();
                }
            }
        }

        $.post(actionURL, { files: files }, 'json').then((response) => {
            /* handle response */
            if (response.error) {
                error.html(response.message).slideDown();
            } else {
                eval(response.callback);
            }
        }).fail((resp) => {
            error.html("There was a problem uploading the files. Please try again!").slideDown();
        });
    });

    $(document).on('keydown', '.force-integer', function (e) {
        // Allow: backspace, delete, tab, escape, enter and .
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
            // Allow: Ctrl+A, Command+A
            (e.keyCode == 65 && (e.ctrlKey === true || e.metaKey === true)) ||
            // Allow: home, end, left, right, down, up
            (e.keyCode >= 35 && e.keyCode <= 40)) {
            // let it happen, don't do anything
            return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
    });

});