(function($){
    var $document = $(document);
    var $update_controllers = $('#update_controllers');
    var $upgrade_status_details = $('#upgrade_status_details');
    var $update_message_not_required = $upgrade_status_details.find('.update_message.not_required');
    var $update_message_updated = $upgrade_status_details.find('.update_message.updated');
    var $success_count = $upgrade_status_details.find('.success_count');
    var $error_count = $upgrade_status_details.find('.error_count');
    var $update_log_popup = $('#log_container');

    $document.off('click', '#update_is_available_block_button');
    $document.on('click', '#update_is_available_block_button', function(ev){
        ev.stopPropagation();

        $update_controllers.hide();

        $.coreUtilites.ajaxRequest(
            {
                subject: 'admin',
                action: 'ajax_action_update_db',
                token: $('#token').val()
            },
            function(data) {
                $upgrade_status_details.show();
                var update_data = data.message;
                switch(true) {
                    case update_data.status === 'not_required':
                        $update_message_not_required.show();
                        $upgrade_status_details.find('.details_controllers').hide();
                        break;
                    case update_data.status === 'updated':
                        $update_message_updated.show();

                        $success_count.find('.value').html(update_data.success_count);
                        $error_count.find('.value').html(update_data.error_count);

                        $('#current_version .value').html(update_data.current_db_version);

                        update_data.log = update_data.log.replace(/\n/g, "<br />");
                        update_data.log = update_data.log.replace(/\t/g, "&nbsp;&nbsp;&nbsp;&nbsp;");

                        $update_log_popup.find('.log').html(update_data.log);
                        break;
                }
            }
        );

        return false;
    });

    $document.off('click', '#view_update_log_button');
    $document.on('click', '#view_update_log_button', function(ev){
        ev.stopPropagation();
        $update_log_popup.show();
        return false;
    });

    $document.off('click', '#log_container .log');
    $document.on('click', '#log_container .log', function(ev){
        ev.stopPropagation();
        $update_log_popup.hide();
        return false;
    });

})(SWjQuery);