define([
  'jquery'
], function ($) {

  const BASE_URL = "http://127.0.0.1:51088/";
  const VERSION_PREFIX = "api/v1/";
  const DEFAULT_JOB_ID = '5851177ec172b7b936a4754b';
  const DEFAULT_JOB_PROCESSING_ID = '00001';
  const DEFAULT_FLOW_ID = '1';
  const DEFAULT_FILTER_ID = 'a2e33810-ccd1-11e6-aed9-b31b33166e93';
  const DEFAULT_SUBMITPOINT_ID = '';

  const USERNAME = 'Administrator';
  const PASSWORD = '!@$QBk%2BmdP1YJcU2cf61053cbstHmB7ysxyFB2Oy63WZwtSWN%2FhJzfVuiYo%2Fn%2Fx2Xn4x7f18%2BOB8oc1jovP%2FkNqMjj2e5o3XZYGWE7Qp6%2BaREcnu4XbFuooJ3y0lKPfC%2B0oDGq1P368uFdB7PznwhtOEKLUCl1CrNz98zzt1avqXgY%3D';

  const DOWNLOAD_JOB_REQUEST_NAME = 'JobDownload';
  const DOWNLOAD_REPORT_REQUEST_NAME = 'JobReportDownload';
  const GET_JOBS_METADATA = 'GetJobMetadata';
  const ADD_ANNOTATIONS_REQUEST_NAME = 'AddAnnotations';
  const REMOVE_ANNOTATIONS_REQUEST_NAME = 'RemoveAnnotations';
  const EDIT_ANNOTATION_REQUEST_NAME = 'EditAnnotation';
  const SET_FLOW_DATA_REQUEST_NAME = 'SetFlowData';
  const START_FLOW_REQUST_NAME = 'StartFlow';
  const GET_FLOWS_REQUEST_NAME = 'GetFlows'
  const STOP_FLOW_REQUST_NAME = 'StopFlow';
  const LOCK_JOB_REQUST_NAME = 'LockJob';
  const UNLOCK_JOB_REQUST_NAME = 'UnlockJob';
  const RUSH_JOB_REQUST_NAME = 'RushJob';
  const UNRUSH_JOB_REQUST_NAME = 'UnrushJob';
  const ROUTE_THE_JOB_REQUEST_NAME = 'RouteJob';
  const REPLACE_THE_JOB_REQUEST_NAME = 'ReplaceJob';
  const POST_JOB_REQUEST_NAME = 'PostJob';
  const ADD_JOB_FILTER_REQUEST_NAME = 'AddJobFilter';
  const EDIT_JOB_FILTER_REQUEST_NAME = 'EditJobFilter';
  const SHARE_JOB_FILTER_REQUEST_NAME = 'ShareJobFilter';
  const UNSHARE_JOB_FILTER_REQUEST_NAME = 'UnshareJobFilter';
  const ADD_MESSAGE_FILTER_REQUEST_NAME = 'AddMessageFilter';
  const EDIT_MESSAGE_FILTER_REQUEST_NAME = 'EditMessageFilter';
  const GET_JOBS_REQUEST_NAME = 'GetJobs';
  const GET_MESSAGES_LIST_REQUEST_NAME = 'GetMessagesList';
  const CLEAR_MESSAGES_REQUEST_NAME = 'PostClearMessages';
  const GET_SUBMITPOINTS_REQUEST_NAME = 'GetSubmitpoints';
  const GET_GROUPS_REQUEST_NAME = 'GetGroups'
  const DASHBOARD = 'dashboardGraphQL';
  const SWITCH_WEBSERVICE_API = "Switch Web Services REST API"
  const SWITCH_HELPER_API = "Switch Helper REST API"
  const SWITCH_HELPER_API_DESCRIPTION = `
This part of the document explains the REST API to integrate Switch Helper in your custom job client.<br>
<br>
The API of the Switch Helper is independent of the Switch Web Service for the following calls:<br>
DefaultApp<br>
Ping<br>
Cancel<br>
IsInEdit<br>
SelectJob<br>
<br>
The API of Switch Helper links to the Switch Web Service for the following calls:<br>
Edit<br>
Replace<br>
Submit<br>
<br>
Note that for these calls a token is required. In other words, you must log in to the Switch Web Service as explained in the
 first part of this document, using the port for that API. The token that is obtained is then given to the Switch Helper API
 using the port of that API, not that of the Switch Web Service!<br>
<br>
Also note that the port number used for accessing the Switch Helper API is not configurable. Potentially three port numbers
 could be used. The default one is 55150, but if it is occupied by another process 55151 is used, and if that one is occupied 55152.
 In order to be well-behaved your code should ping 55150, then 55151, then 55152 and take the first one that returns true.
 If all three fail, you should investigate what processes block these ports and see if they can be moved to another port number.<br>
<br>
Finally note that you are always accessing the local Switch Helper using the HTTP protocol. Although you can edit the URL in this
 documentation when testing, it will only work with http://127.0.0.1:xxxxx, where xxxxx is one of the three possible port numbers.`;

  const GRAPHQL_DEFAULT_QUERY = `# GraphQL queries start with a curly bracket ({).
# Lines that start with a hashtag (#) are ignored.
#
# Keyboard shortcuts:
# Run Query: Ctrl-Enter (or click the play button above)
# Auto Complete: Ctrl-Space (or just start typing)
#
query getJobHistData($filter: String!){
  gr: jobs_hist(period: "week", since: "2017-01-01T00:00:00.000Z", to: "2018-01-01T00:00:00.000Z", groupBy: ["flow"], filter: $filter) {
    jobs {
      group {
        flow
        period {
          start
          finish
        }
      }
      avgTimeInFlow
      count
    }
  }
}
`;

  const GRAPHQL_DEFAULT_VARIABLES = `{
  "filter": "{\\\"flow\\\":{ \\\"is_not\\\": \\\"debug\\\"}}"
}`;

  const GRAPHQL_DEFAULT_OPERATION = 'getJobHistData';

  var administratorToken;
  var uploadedFileData = {};

  function addDataGroupCategory() {
    $('li[data-group="Authentication"]').first().attr("data-category", SWITCH_WEBSERVICE_API);
    $('li[data-group="Messages"]').first().addClass('empty-category');
    $('li[data-group="Job"]').first().attr("data-category", "Client module");
    $('li[data-group="SwitchHelperInfo"]').first().attr("data-category", SWITCH_HELPER_API);
    var apidescription = "<div><h1><b>" + SWITCH_HELPER_API + "</b></h1></div><div>" + SWITCH_HELPER_API_DESCRIPTION + "</div><br>";
    $('#api-SwitchHelperInfo').prepend(apidescription);
  }

  const filterOptions = {
    filters: [{
      id: 'id',
      label: 'Id',
      type: 'string',
      operators: ['is']
    }, {
      id: 'flowId',
      label: 'Flow id',
      type: 'string',
      operators: ['contains', 'does_not_contain', 'is', 'is_not', 'starts_with', 'ends_with']
    }, {
      id: 'checkpointId',
      label: 'Checkpoint id',
      type: 'string',
      operators: ['contains', 'does_not_contain', 'is', 'is_not', 'starts_with', 'ends_with']
    }, {
      id: 'name',
      label: 'Name',
      type: 'string',
      operators: ['contains', 'does_not_contain', 'is', 'is_not', 'starts_with', 'ends_with']
    }, {
      id: 'family',
      label: 'Family',
      type: 'string',
      operators: ['contains', 'does_not_contain', 'is', 'is_not', 'starts_with', 'ends_with']
    }, {
      id: 'submittedTo',
      label: 'Submitted to',
      type: 'string',
      operators: ['contains', 'does_not_contain', 'is', 'is_not', 'starts_with', 'ends_with']
    }, {
      id: 'modificationDate',
      label: 'Modification date',
      type: 'string',
      operators: ['date_is', 'date_is_not', 'is_after', 'is_before', 'is_in_the_last', 'is_not_in_the_last', 'date_is_in_the_range']
    }, {
      id: 'initiated',
      label: 'Initiated',
      type: 'string',
      operators: ['date_is', 'date_is_not', 'is_after', 'is_before', 'is_in_the_last', 'is_not_in_the_last', 'date_is_in_the_range']
    }, {
      id: 'updated',
      label: 'Updated',
      type: 'string',
      operators: ['date_is', 'date_is_not', 'is_after', 'is_before', 'is_in_the_last', 'is_not_in_the_last', 'date_is_in_the_range']
    }, {
      id: 'onAlertSince',
      label: 'On alert since',
      type: 'string',
      operators: ['date_is', 'date_is_not', 'is_after', 'is_before', 'is_in_the_last', 'is_not_in_the_last', 'date_is_in_the_range']
    }, {
      id: 'userName',
      label: 'User name',
      type: 'string',
      operators: ['contains', 'does_not_contain', 'is', 'is_not', 'starts_with', 'ends_with']
    }, {
      id: 'type',
      label: 'Type',
      type: 'string',
      operators: ['contains', 'does_not_contain', 'is', 'is_not', 'starts_with', 'ends_with']
    }, {
      id: 'size',
      label: 'Size',
      type: 'integer',
      operators: ['num_is', 'num_is_not', 'is_greater_than', 'is_less_than', 'is_in_the_range']
    }, {
      id: 'pages',
      label: 'Pages',
      type: 'integer',
      operators: ['num_is', 'num_is_not', 'is_greater_than', 'is_less_than', 'is_in_the_range']
    }, {
      id: 'dimensions',
      label: 'Dimensions',
      type: 'string',
      operators: ['contains', 'does_not_contain', 'is', 'is_not', 'starts_with', 'ends_with']
    }, {
      id: 'files',
      label: 'Files',
      type: 'integer',
      operators: ['num_is', 'num_is_not', 'is_greater_than', 'is_less_than', 'is_in_the_range']
    }, {
      id: 'status',
      label: 'Status',
      type: 'string',
      operators: ['contains', 'does_not_contain', 'is', 'is_not', 'starts_with', 'ends_with']
    }, {
      id: 'stage',
      label: 'Stage',
      type: 'string',
      operators: ['contains', 'does_not_contain', 'is', 'is_not', 'starts_with', 'ends_with']
    }, {
      id: 'state',
      label: 'State',
      type: 'string',
      operators: ['contains', 'does_not_contain', 'is', 'is_not', 'starts_with', 'ends_with']
    }, {
      id: 'checkpointName',
      label: 'Checkpoint name',
      type: 'string',
      operators: ['contains', 'does_not_contain', 'is', 'is_not', 'starts_with', 'ends_with']
    }, {
      id: 'hasMetadata',
      label: 'Has metadata',
      type: 'boolean',
      operators: ['bool_is', 'bool_is_not']
    }, {
      id: 'allowMultipleOutput',
      label: 'Allow Multiple Output',
      type: 'boolean',
      operators: ['bool_is', 'bool_is_not']
    }, {
      id: 'flowName',
      label: 'Flow name',
      type: 'string',
      operators: ['contains', 'does_not_contain', 'is', 'is_not', 'starts_with', 'ends_with']
      }, {
        id: 'processingId',
        label: 'Processing Id',
        type: 'string',
        operators: ['is']
      }],
    operators: [{
      type: 'contains',
      nb_inputs: 1,
      multiple: false,
      apply_to: ['string']
    }, {
      type: 'does_not_contain',
      nb_inputs: 1,
      multiple: false,
      apply_to: ['string']
    }, {
      type: 'is',
      nb_inputs: 1,
      multiple: false,
      apply_to: ['string']
    }, {
      type: 'is_not',
      nb_inputs: 1,
      multiple: false,
      apply_to: ['string']
    }, {
      type: 'starts_with',
      nb_inputs: 1,
      multiple: false,
      apply_to: ['string']
    }, {
      type: 'ends_with',
      nb_inputs: 1,
      multiple: false,
      apply_to: ['string']
    }, {
      type: 'num_is',
      nb_inputs: 1,
      multiple: false,
      apply_to: ['string']
    }, {
      type: 'num_is_not',
      nb_inputs: 1,
      multiple: false,
      apply_to: ['string']
    }, {
      type: 'is_greater_than',
      nb_inputs: 1,
      multiple: false,
      apply_to: ['string']
    }, {
      type: 'is_less_than',
      nb_inputs: 1,
      multiple: false,
      apply_to: ['string']
    }, {
      type: 'is_in_the_range',
      nb_inputs: 2,
      multiple: false,
      apply_to: ['string']
    }, {
      type: 'date_is',
      nb_inputs: 1,
      multiple: false,
      apply_to: ['string']
    }, {
      type: 'date_is_not',
      nb_inputs: 1,
      multiple: false,
      apply_to: ['string']
    }, {
      type: 'is_after',
      nb_inputs: 1,
      multiple: false,
      apply_to: ['string']
    }, {
      type: 'is_before',
      nb_inputs: 1,
      multiple: false,
      apply_to: ['string']
    }, {
      type: 'is_in_the_last',
      nb_inputs: 1,
      multiple: false,
      apply_to: ['string']
    }, {
      type: 'is_not_in_the_last',
      nb_inputs: 1,
      multiple: false,
      apply_to: ['string']
    }, {
      type: 'date_is_in_the_range',
      nb_inputs: 2,
      multiple: false,
      apply_to: ['string']
    }, {
      type: 'bool_is',
      nb_inputs: 1,
      multiple: false,
      apply_to: ['boolean']
    }, {
      type: 'bool_is_not',
      nb_inputs: 1,
      multiple: false,
      apply_to: ['boolean']
    }]
  };

  var init = function () {
    addDataGroupCategory();
    helpers.authentication();
    helpers.downloadJob(DOWNLOAD_JOB_REQUEST_NAME);
    helpers.downloadJob(DOWNLOAD_REPORT_REQUEST_NAME);
    helpers.lockJob();
    helpers.unlockJob();
    helpers.rushJob();
    helpers.unrushJob();
    helpers.getJobsMetadata();
    helpers.sendRequestHandler();
    helpers.clearRequestHandler();
    helpers.routeJob();
    helpers.replaceJob();
    helpers.postJob();
    helpers.addJobFilter();
    helpers.editJobFilter();
    helpers.shareJobFilter();
    helpers.unshareJobFilter();
    helpers.getJobs();
    helpers.addMessageFilter();
    helpers.editMessageFilter();
    helpers.getMessagesList();
    helpers.clearMessages();
    helpers.getSubmitpoints();
    helpers.dashboard();
    helpers.startFlow();
    helpers.stopFlow();
    helpers.addAnnotations();
    helpers.removeAnnotations();
    helpers.editAnnotation();
    helpers.setFlowData();
    helpers.getFlows();
    helpers.getGroups();
  };

  var helpers = {
    authentication: function (token) {
      var authorizationPrefix = "Bearer ";
      var $root = $('article[data-name="LoginQuery"]');
      var paramFields = {
        url: $root.find("input.sample-request-url"),
        authorization: $("input[data-sample-request-header-name='Authorization']"),
        username: $root.find("input[data-sample-request-param-name='username']"),
        password: $root.find("input[data-sample-request-param-name='password']"),
        lang: $root.find("input[data-sample-request-param-name='lang']"),
        uid: $("input[data-sample-request-param-name='uid']"),
        downloadJobUrl: $('article[data-name="' + DOWNLOAD_JOB_REQUEST_NAME + '"] input.sample-request-url')
      };
      if (token) {
        var authorizationExampleString = $("pre span:contains('Bearer')");
        var authorizationExampleAddressString = $("pre.language-curl span:contains('uid')");
        administratorToken = token;
        paramFields.authorization.val(authorizationPrefix + administratorToken);
        paramFields.uid.val(administratorToken);
        paramFields.downloadJobUrl.val(BASE_URL + VERSION_PREFIX + 'job/' + DEFAULT_JOB_ID);
        authorizationExampleString.each(function (index, element) {
          replaceAuthorizationString(element, administratorToken);
        });
        replaceAuthorizationString(authorizationExampleAddressString, administratorToken);
      } else {
        paramFields.username.val(USERNAME);
        paramFields.password.val(PASSWORD);
        paramFields.authorization.val(authorizationPrefix);
        var authorizationParams = {
          username: paramFields.username.val(),
          password: paramFields.password.val()
        };
        var ajaxRequest = {
          url: BASE_URL + 'login',
          headers: {},
          data: authorizationParams,
          type: 'post',
          success: successAction,
          error: errorAction
        };
        $.ajax(ajaxRequest);
      }

      // Add lang to the url
      paramFields.lang.on("change paste keyup", function () {
        var langParam = paramFields.lang.val() !== '' ? '?lang=' + paramFields.lang.val() : '';
        paramFields.url.val(BASE_URL + 'login' + langParam);
      });


      function successAction(data, status, jqXHR) {
        var authorizationExampleString = $("pre span:contains('Bearer')");
        var authorizationExampleAddressString = $("pre[data-type='curl'] span:contains('uid')");
        var jsonResponseObject = {};
        try {
          jsonResponseObject = JSON.parse(jqXHR.responseText);
        } catch (e) {
          console.error('Failed response parsing');
        }
        if (jsonResponseObject.hasOwnProperty('token')) {
          administratorToken = jsonResponseObject.token;
          paramFields.authorization.val(authorizationPrefix + administratorToken);
          paramFields.uid.val(administratorToken);
          authorizationExampleString.each(function (index, element) {
            replaceAuthorizationString(element, administratorToken);
          });
          paramFields.downloadJobUrl.val(BASE_URL + VERSION_PREFIX + 'job/' + DEFAULT_JOB_ID);
          replaceAuthorizationString(authorizationExampleAddressString, administratorToken);
        }
        helpers.dashboard();
      }

      function errorAction(jqXHR, textStatus, error) {
        console.error('Failed authorization');
      }
    },
    sendRequestHandler: function () {
      $(".sample-request-send").off("click");
      $(".sample-request-send").on("click", function (e) {
        e.preventDefault();
        var $root = $(this).parents("article");
        var group = $root.data("group");
        var name = $root.data("name");
        var version = $root.data("version");
        sendSampleRequest(group, name, version, $(this).data("sample-request-type"));
      });
    },
    clearRequestHandler: function () {
      $(".sample-request-clear").off("click");
      $(".sample-request-clear").on("click", function (e) {
        e.preventDefault();
        var $root = $(this).parents("article");
        var group = $root.data("group");
        var name = $root.data("name");
        var version = $root.data("version");
        clearSampleRequest(group, name, version);
      });
    },
    downloadJob: function (requestName) {
      var $root = $('article[data-name="' + requestName + '"]');
      var jobIdValue;
      var paramFields = {
        url: $root.find("input.sample-request-url"),
        id: $root.find("input[data-sample-request-param-name='id']")
      };
      var baseUrlValue = paramFields.url.val();
      paramFields.url.val(baseUrlValue + '/' + DEFAULT_JOB_ID);
      paramFields.id.val(DEFAULT_JOB_ID);
      paramFields.id.on("change paste keyup", function () {
        jobIdValue = $(this).val() !== '' ? $(this).val() : undefined;
        var requestUrlPart = 'job/';
        if (requestName == DOWNLOAD_REPORT_REQUEST_NAME)
          requestUrlPart += 'report/';
        paramFields.url.val(BASE_URL + VERSION_PREFIX + requestUrlPart + (jobIdValue || DEFAULT_JOB_ID));
      });
    },
    getJobsMetadata: function () {
      var $root = $('article[data-name="' + GET_JOBS_METADATA + '"]');
      var paramFields = {
        ids: $root.find("input[data-sample-request-param-name='ids']"),
        readonly: $root.find("input[data-sample-request-param-name='readonly']")
      };
      var readonly = 'false';
      paramFields.ids.val(DEFAULT_JOB_ID);
      paramFields.readonly.val(readonly);
    },
    startFlow: function () {
      var $root = $('article[data-name="' + START_FLOW_REQUST_NAME + '"]');
      var paramFields = {
        url: $root.find("input.sample-request-url"),
        id: $root.find("input[data-sample-request-param-name='id']"),
        lang: $root.find("input[data-sample-request-param-name='lang']")
      };
      paramFields.id.val(DEFAULT_FLOW_ID);
      updateUrl();
      paramFields.id.on("change paste keyup", updateUrl);
      paramFields.lang.on("change paste keyup", updateUrl);

      function updateUrl() {
        var flowIdValue = paramFields.id.val() !== '' ? paramFields.id.val() : undefined;
        var langParam = paramFields.lang.val() !== '' ? '&lang=' + paramFields.lang.val() : '';
        paramFields.url.val(BASE_URL + VERSION_PREFIX + 'flows/' + (flowIdValue || DEFAULT_FLOW_ID) + '?action=start' + langParam);
      }
    },
    getFlows: function () {
      var $root = $('article[data-name="' + GET_FLOWS_REQUEST_NAME + '"]');
      var paramFields = {
        url: $root.find("input.sample-request-url"),
        ids: $root.find("input[data-sample-request-param-name='ids']"),
        fields: $root.find("input[data-sample-request-param-name='fields']"),
        lang: $root.find("input[data-sample-request-param-name='lang']")
      };
      updateUrl();
      paramFields.ids.on("change paste keyup", updateUrl);
      paramFields.fields.on("change paste keyup", updateUrl);
      paramFields.lang.on("change paste keyup", updateUrl);

      function updateUrl() {
        var idsValue = paramFields.ids.val() !== '' ? '&ids=' + paramFields.ids.val() : '';
        var fieldsValue = paramFields.fields.val() !== '' ? '&fields=' + paramFields.fields.val() : '';
        var langParam = paramFields.lang.val() !== '' ? '&lang=' + paramFields.lang.val() : '';
        paramFields.url.val(BASE_URL + VERSION_PREFIX + 'flows?' + langParam + fieldsValue + idsValue);
      }
    },
    addAnnotations: function () {
      var $root = $('article[data-name="' + ADD_ANNOTATIONS_REQUEST_NAME + '"]');
      var paramFields = {
        url: $root.find("input.sample-request-url"),
        id: $root.find("input[data-sample-request-param-name='id']"),
        lang: $root.find("input[data-sample-request-param-name='lang']")
      };
      paramFields.id.val(DEFAULT_FLOW_ID);
      updateUrl();
      paramFields.id.on("change paste keyup", updateUrl);
      paramFields.lang.on("change paste keyup", updateUrl);

      function updateUrl() {
        var flowIdValue = paramFields.id.val() !== '' ? paramFields.id.val() : undefined;
        var langParam = paramFields.lang.val() !== '' ? '&lang=' + paramFields.lang.val() : '';
        paramFields.url.val(BASE_URL + VERSION_PREFIX + 'flows/' + (flowIdValue || DEFAULT_FLOW_ID) + '/annotations?' + langParam);
      }
    },
    removeAnnotations: function () {
      var $root = $('article[data-name="' + REMOVE_ANNOTATIONS_REQUEST_NAME + '"]');
      var paramFields = {
        url: $root.find("input.sample-request-url"),
        id: $root.find("input[data-sample-request-param-name='id']"),
        annotId: $root.find("input[data-sample-request-param-name='annotId']"),
        lang: $root.find("input[data-sample-request-param-name='lang']")
      };
      paramFields.id.val(DEFAULT_FLOW_ID);
      paramFields.annotId.val('reqwr-4341rq-rqeqeq-431a');
      updateUrl();
      paramFields.id.on("change paste keyup", updateUrl);
      paramFields.annotId.on("change paste keyup", updateUrl);
      paramFields.lang.on("change paste keyup", updateUrl);

      function updateUrl() {
        var flowIdValue = paramFields.id.val() !== '' ? paramFields.id.val() : undefined;
        var annotIdValue = paramFields.annotId.val() !== '' ? paramFields.annotId.val() : undefined;
        var langParam = paramFields.lang.val() !== '' ? '&lang=' + paramFields.lang.val() : '';
        paramFields.url.val(BASE_URL + VERSION_PREFIX + 'flows/' + (flowIdValue || DEFAULT_FLOW_ID) + '/annotations/' + (annotIdValue) + '?' + langParam);
      }
    },
    editAnnotation: function () {
      var $root = $('article[data-name="' + EDIT_ANNOTATION_REQUEST_NAME + '"]');
      var paramFields = {
        url: $root.find("input.sample-request-url"),
        id: $root.find("input[data-sample-request-param-name='id']"),
        annotId: $root.find("input[data-sample-request-param-name='annotId']"),
        lang: $root.find("input[data-sample-request-param-name='lang']")
      };
      paramFields.id.val(DEFAULT_FLOW_ID);
      paramFields.annotId.val('reqwr-4341rq-rqeqeq-431a');
      updateUrl();
      paramFields.id.on("change paste keyup", updateUrl);
      paramFields.annotId.on("change paste keyup", updateUrl);
      paramFields.lang.on("change paste keyup", updateUrl);

      function updateUrl() {
        var flowIdValue = paramFields.id.val() !== '' ? paramFields.id.val() : undefined;
        var annotIdValue = paramFields.annotId.val() !== '' ? paramFields.annotId.val() : undefined;
        var langParam = paramFields.lang.val() !== '' ? '&lang=' + paramFields.lang.val() : '';
        paramFields.url.val(BASE_URL + VERSION_PREFIX + 'flows/' + (flowIdValue || DEFAULT_FLOW_ID) + '/annotations/' + (annotIdValue) + '?' + langParam);
      }
    },
    setFlowData: function () {
      var $root = $('article[data-name="' + SET_FLOW_DATA_REQUEST_NAME + '"]');
      var paramFields = {
        url: $root.find("input.sample-request-url"),
        id: $root.find("input[data-sample-request-param-name='id']"),
        lang: $root.find("input[data-sample-request-param-name='lang']")
      };
      paramFields.id.val(DEFAULT_FLOW_ID);
      updateUrl();
      paramFields.id.on("change paste keyup", updateUrl);
      paramFields.lang.on("change paste keyup", updateUrl);

      function updateUrl() {
        var flowIdValue = paramFields.id.val() !== '' ? paramFields.id.val() : undefined;
        var langParam = paramFields.lang.val() !== '' ? '&lang=' + paramFields.lang.val() : '';
        paramFields.url.val(BASE_URL + VERSION_PREFIX + 'flows/' + (flowIdValue || DEFAULT_FLOW_ID) + '/data?' + langParam);
      }
    },
    stopFlow: function () {
      var $root = $('article[data-name="' + STOP_FLOW_REQUST_NAME + '"]');
      var paramFields = {
        url: $root.find("input.sample-request-url"),
        id: $root.find("input[data-sample-request-param-name='id']"),
        lang: $root.find("input[data-sample-request-param-name='lang']")
      };
      paramFields.id.val(DEFAULT_FLOW_ID);
      updateUrl();
      paramFields.id.on("change paste keyup", updateUrl);
      paramFields.lang.on("change paste keyup", updateUrl);

      function updateUrl() {
        var flowIdValue = paramFields.id.val() !== '' ? paramFields.id.val() : undefined;
        var langParam = paramFields.lang.val() !== '' ? '&lang=' + paramFields.lang.val() : '';
        paramFields.url.val(BASE_URL + VERSION_PREFIX + 'flows/' + (flowIdValue || DEFAULT_FLOW_ID) + '?action=stop' + langParam);
      }
    },
    lockJob: function () {
      var $root = $('article[data-name="' + LOCK_JOB_REQUST_NAME + '"]');
      var paramFields = {
        url: $root.find("input.sample-request-url"),
        id: $root.find("input[data-sample-request-param-name='id']"),
        lang: $root.find("input[data-sample-request-param-name='lang']")
      };
      paramFields.id.val(DEFAULT_JOB_ID);
      updateUrl();
      paramFields.id.on("change paste keyup", updateUrl);
      paramFields.lang.on("change paste keyup", updateUrl);

      function updateUrl() {
        var jobIdValue = paramFields.id.val() !== '' ? paramFields.id.val() : undefined;
        var langParam = paramFields.lang.val() !== '' ? '&lang=' + paramFields.lang.val() : '';
        paramFields.url.val(BASE_URL + VERSION_PREFIX + 'job/' + (jobIdValue || DEFAULT_JOB_ID) + '?action=lock' + langParam);
      }
    },
    unlockJob: function () {
      var $root = $('article[data-name="' + UNLOCK_JOB_REQUST_NAME + '"]');
      var paramFields = {
        url: $root.find("input.sample-request-url"),
        id: $root.find("input[data-sample-request-param-name='id']"),
        check: $root.find("input[data-sample-request-param-name='check']"),
        lang: $root.find("input[data-sample-request-param-name='lang']")
      };
      paramFields.id.val(DEFAULT_JOB_ID);
      paramFields.check.val(false);
      updateUrl();
      paramFields.id.on("change paste keyup", updateUrl);
      paramFields.check.on("change paste keyup", updateUrl);
      paramFields.lang.on("change paste keyup", updateUrl);

      function updateUrl() {
        var jobIdValue = paramFields.id.val() !== '' ? paramFields.id.val() : undefined;
        var langParam = paramFields.lang.val() !== '' ? '&lang=' + paramFields.lang.val() : '';
        paramFields.url.val(BASE_URL + VERSION_PREFIX + 'job/' + (jobIdValue || DEFAULT_JOB_ID) + '?action=unlock&check=' + paramFields.check.val() + langParam);
      }
    },
    rushJob: function () {
      var $root = $('article[data-name="' + RUSH_JOB_REQUST_NAME + '"]');
      var paramFields = {
        url: $root.find("input.sample-request-url"),
        id: $root.find("input[data-sample-request-param-name='processingId']"),
        lang: $root.find("input[data-sample-request-param-name='lang']")
      };
      paramFields.id.val(DEFAULT_JOB_PROCESSING_ID);
      updateUrl();
      paramFields.id.on("change paste keyup", updateUrl);
      paramFields.lang.on("change paste keyup", updateUrl);

      function updateUrl() {
        var jobIdValue = paramFields.id.val() !== '' ? paramFields.id.val() : undefined;
        var langParam = paramFields.lang.val() !== '' ? '&lang=' + paramFields.lang.val() : '';
        paramFields.url.val(BASE_URL + VERSION_PREFIX + 'processingjob/' + (jobIdValue || DEFAULT_JOB_PROCESSING_ID) + '?action=rush' + langParam);
      }
    },
    unrushJob: function () {
      var $root = $('article[data-name="' + UNRUSH_JOB_REQUST_NAME + '"]');
      var paramFields = {
        url: $root.find("input.sample-request-url"),
        id: $root.find("input[data-sample-request-param-name='processingId']"),
        lang: $root.find("input[data-sample-request-param-name='lang']")
      };
      paramFields.id.val(DEFAULT_JOB_PROCESSING_ID);
      updateUrl();
      paramFields.id.on("change paste keyup", updateUrl);
      paramFields.lang.on("change paste keyup", updateUrl);

      function updateUrl() {
        var jobIdValue = paramFields.id.val() !== '' ? paramFields.id.val() : undefined;
        var langParam = paramFields.lang.val() !== '' ? '&lang=' + paramFields.lang.val() : '';
        paramFields.url.val(BASE_URL + VERSION_PREFIX + 'processingjob/' + (jobIdValue || DEFAULT_JOB_PROCESSING_ID) + '?action=unrush' + langParam);
      }
    },
    routeJob: function () {
      var $root = $('article[data-name="' + ROUTE_THE_JOB_REQUEST_NAME + '"]');
      var jobIdValue;
      var paramFields = {
        url: $root.find("input.sample-request-url"),
        id: $root.find("input[data-sample-request-param-name='id']"),
        connections: $root.find("input[data-sample-request-param-name='connections']"),
        metadata: $root.find("input[data-sample-request-param-name='metadata']"),
        /* We also hide couple of fields for request (see css), because not needed to fill them*/
        metadataName: $root.find("input[data-sample-request-param-name='metadata.name']"),
        /* We also hide couple of fields for request (see css), because not needed to fill them*/
        metadataValue: $root.find("input[data-sample-request-param-name='metadata.value']"),
        lang: $root.find("input[data-sample-request-param-name='lang']")
      };
      var metadataObject = {
        name: '',
        value: ''
      };
      var baseUrlValue = paramFields.url.val();
      var metadata = '[]';
      var connections = '[]';
      paramFields.url.val(baseUrlValue + '/' + DEFAULT_JOB_ID + '?action=route');
      paramFields.id.val(DEFAULT_JOB_ID);
      paramFields.connections.val(connections);
      paramFields.metadata.val(metadata);

      updateUrl();
      paramFields.id.on("change paste keyup", updateUrl);
      paramFields.lang.on("change paste keyup", updateUrl);

      function updateUrl() {
        var jobIdValue = paramFields.id.val() !== '' ? paramFields.id.val() : undefined;
        var langParam = paramFields.lang.val() !== '' ? '&lang=' + paramFields.lang.val() : '';
        paramFields.url.val(BASE_URL + VERSION_PREFIX + 'job/' + (jobIdValue || DEFAULT_JOB_ID) + '?action=route' + langParam);
      }

      paramFields.metadataName.on("change paste keyup", function () {
        var targetValue = $(this).val();
        metadataObject.name = targetValue;
        var metadataString = JSON.stringify(metadataObject);
        var metadata = '[' + metadataString + ']';
        paramFields.metadata.val(metadata);
      });
      paramFields.metadataValue.on("change paste keyup", function () {
        var targetValue = $(this).val();
        metadataObject.value = targetValue;
        var metadataString = JSON.stringify(metadataObject);
        var metadata = '[' + metadataString + ']';
        paramFields.metadata.val(metadata);
      });
    },
    replaceJob: function () {
      var $root = $('article[data-name="' + REPLACE_THE_JOB_REQUEST_NAME + '"]');
      /* We also hide couple of fields for request (see css), because not needed to fill them*/
      $root.find("input[data-sample-request-param-name='fileContent']").prop('disabled', true);
      var jobIdValue;
      var paramFields = {
        url: $root.find("input.sample-request-url"),
        id: $root.find("input[data-sample-request-param-name='id']"),
        updated: $root.find("input[data-sample-request-param-name='updated']"),
        filePath: $root.find("input[data-sample-request-param-name='filePath']"),
        contentLength: $root.find("input[data-sample-request-header-name='Content-Length']"),
        contentType: $root.find("input[data-sample-request-header-name='Content-Type']"),
        lang: $root.find("input[data-sample-request-param-name='lang']")
      };
      var baseUrlValue = paramFields.url.val();
      paramFields.url.val(baseUrlValue + '/' + DEFAULT_JOB_ID + '?action=replace');
      paramFields.id.val(DEFAULT_JOB_ID);

      updateUrl();
      paramFields.id.on("change paste keyup", updateUrl);
      paramFields.lang.on("change paste keyup", updateUrl);

      function updateUrl() {
        var jobIdValue = paramFields.id.val() !== '' ? paramFields.id.val() : undefined;
        var langParam = paramFields.lang.val() !== '' ? '&lang=' + paramFields.lang.val() : '';
        paramFields.url.val(BASE_URL + VERSION_PREFIX + 'job/' + (jobIdValue || DEFAULT_JOB_ID) + '?action=replace' + langParam);
      }

      $root.find(".sample-request-fileupload").off("click");
      $root.find(".sample-request-fileupload").on("click", function (e) {
        e.preventDefault();
        $('#fileInput').click();
      });
      document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);

      function handleFileSelect(event) {
        uploadedFileData = event.target.files[0];
        var contentType = 'multipart/form-data; boundary=----WebKitFormBoundaryPEVBKFgKPxbsxTfP';
        paramFields.contentLength.val(uploadedFileData.size);
        paramFields.contentType.val(contentType);
        $root.find("input[data-sample-request-param-name='fileContent']").val('<File Content>');
        paramFields.filePath.val(uploadedFileData.name);
      }
    },
    postJob: function () {
      var $root = $('article[data-name="' + POST_JOB_REQUEST_NAME + '"]');
      /* We also hide couple of fields for request (see css), because not needed to fill them*/
      $root.find("input[data-sample-request-param-name='fileContent']").prop('disabled', true);
      var paramFields = {
        url: $root.find("input.sample-request-url"),
        contentLength: $root.find("input[data-sample-request-header-name='Content-Length']"),
        contentType: $root.find("input[data-sample-request-header-name='Content-Type']"),
        flowId: $root.find("input[data-sample-request-param-name='flowId']"),
        objectId: $root.find("input[data-sample-request-param-name='objectId']"),
        filePath: $root.find("input[data-sample-request-param-name='filePath']"),
        jobName: $root.find("input[data-sample-request-param-name='jobName']"),
        origin: $root.find("input[data-sample-request-param-name='origin']"),
        created: $root.find("input[data-sample-request-param-name='created']"),
        modified: $root.find("input[data-sample-request-param-name='modified']"),
        metadata: $root.find("input[data-sample-request-param-name='metadata']"),
        /* We also hide couple of fields for request (see css), because not needed to fill them*/
        metadataName: $root.find("input[data-sample-request-param-name='metadata.name']"),
        /* We also hide couple of fields for request (see css), because not needed to fill them*/
        metadataValue: $root.find("input[data-sample-request-param-name='metadata.value']"),
        lang: $root.find("input[data-sample-request-param-name='lang']")
      };
      // Add lang to the url
      var baseUrlValue = paramFields.url.val();
      paramFields.lang.on("change paste keyup", function () {
        var targetValue = $(this).val();
        paramFields.url.val(baseUrlValue + '?lang=' + targetValue);
      });

      var metadataObject = {
        name: '',
        value: ''
      };
      $root.find(".sample-request-fileupload").off("click");
      $root.find(".sample-request-fileupload").on("click", function (e) {
        e.preventDefault();
        $('#fileInput').click();
      });
      document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);

      function handleFileSelect(event) {
        uploadedFileData = event.target.files[0];
        var contentType = 'multipart/form-data; boundary=----WebKitFormBoundaryPEVBKFgKPxbsxTfP';
        var flowId = 1;
        var objectId = 2;
        var created = '';
        var modifiedDate = new Date(uploadedFileData.lastModified).toISOString();
        var metadata = '[]';
        paramFields.contentLength.val(uploadedFileData.size);
        paramFields.contentType.val(contentType);
        paramFields.flowId.val(flowId);
        paramFields.objectId.val(objectId);
        paramFields.jobName.val(uploadedFileData.name);
        paramFields.filePath.val(uploadedFileData.name);
        paramFields.created.val(created);
        paramFields.modified.val(modifiedDate);
        paramFields.metadata.val(metadata);
        $root.find("input[data-sample-request-param-name='fileContent']").val('<File Content>');
      }
      paramFields.metadataName.on("change paste keyup", function () {
        var targetValue = $(this).val();
        metadataObject.name = targetValue;
        var metadataString = JSON.stringify(metadataObject);
        var metadata = '[' + metadataString + ']';
        paramFields.metadata.val(metadata);
      });
      paramFields.metadataValue.on("change paste keyup", function () {
        var targetValue = $(this).val();
        metadataObject.value = targetValue;
        var metadataString = JSON.stringify(metadataObject);
        var metadata = '[' + metadataString + ']';
        paramFields.metadata.val(metadata);
      });
    },
    addJobFilter: function () {
      var $root = $('article[data-name="' + ADD_JOB_FILTER_REQUEST_NAME + '"]');
      var paramFields = {
        url: $root.find("input.sample-request-url"),
        name: $root.find("input[data-sample-request-param-name='name']"),
        query: $root.find("input[data-sample-request-param-name='query']"),
        lang: $root.find("input[data-sample-request-param-name='lang']")
      };
      var name = 'example';
      var query = '{}';
      paramFields.name.val(name);
      paramFields.query.val(query);

      // Add lang to the url
      var baseUrlValue = paramFields.url.val();
      paramFields.lang.on("change paste keyup", function () {
        var targetValue = $(this).val();
        paramFields.url.val(baseUrlValue + '?lang=' + targetValue);
      });
    },
    editJobFilter: function () {
      var $root = $('article[data-name="' + EDIT_JOB_FILTER_REQUEST_NAME + '"]');
      var filterIdValue;
      var paramFields = {
        url: $root.find("input.sample-request-url"),
        id: $root.find("input[data-sample-request-param-name='id']"),
        name: $root.find("input[data-sample-request-param-name='name']"),
        query: $root.find("input[data-sample-request-param-name='query']"),
        lang: $root.find("input[data-sample-request-param-name='lang']")
      };
      var name = 'example';
      var query = '{}';
      paramFields.name.val(name);
      paramFields.query.val(query);
      var baseUrlValue = paramFields.url.val();
      paramFields.url.val(baseUrlValue + '/' + DEFAULT_FILTER_ID);
      paramFields.id.val(DEFAULT_FILTER_ID);
      paramFields.id.on("change paste keyup", updateUrl);
      paramFields.lang.on("change paste keyup", updateUrl);

      function updateUrl() {
        var filterId = paramFields.id.val() !== '' ? paramFields.id.val() : undefined;
        var langParam = paramFields.lang.val() !== '' ? '?lang=' + paramFields.lang.val() : '';
        paramFields.url.val(BASE_URL + VERSION_PREFIX + 'jobFilters/' + (filterId || DEFAULT_FILTER_ID) + langParam);
      }
    },
    shareJobFilter: function () {
      var $root = $('article[data-name="' + SHARE_JOB_FILTER_REQUEST_NAME + '"]');
      var paramFields = {
        url: $root.find("input.sample-request-url"),
        id: $root.find("input[data-sample-request-param-name='id']"),
        users: $root.find("input[data-sample-request-param-name='users']"),
        groups: $root.find("input[data-sample-request-param-name='groups']"),
        lang: $root.find("input[data-sample-request-param-name='lang']")
      };
      var baseUrlValue = paramFields.url.val();
      paramFields.url.val(baseUrlValue + '/' + DEFAULT_FILTER_ID);
      paramFields.id.val(DEFAULT_FILTER_ID);
      paramFields.users.attr("placeholder", 'users names separated with a comma character (e.g. "user1,user2")');
      paramFields.groups.attr("placeholder", 'users names separated with a comma character (e.g. "group1,group2")');
      paramFields.id.on("change paste keyup", updateUrl);
      paramFields.lang.on("change paste keyup", updateUrl);

      function updateUrl() {
        var filterId = paramFields.id.val() !== '' ? paramFields.id.val() : undefined;
        var langParam = paramFields.lang.val() !== '' ? '&lang=' + paramFields.lang.val() : '';
        paramFields.url.val(BASE_URL + VERSION_PREFIX + 'jobFilters/' + (filterId || DEFAULT_FILTER_ID) + '?action=share' + langParam);
      }
    },
    unshareJobFilter: function () {
      var $root = $('article[data-name="' + UNSHARE_JOB_FILTER_REQUEST_NAME + '"]');
      var paramFields = {
        url: $root.find("input.sample-request-url"),
        id: $root.find("input[data-sample-request-param-name='id']"),
        users: $root.find("input[data-sample-request-param-name='users']"),
        groups: $root.find("input[data-sample-request-param-name='groups']"),
        lang: $root.find("input[data-sample-request-param-name='lang']")
      };
      var baseUrlValue = paramFields.url.val();
      paramFields.url.val(baseUrlValue + '/' + DEFAULT_FILTER_ID);
      paramFields.id.val(DEFAULT_FILTER_ID);
      paramFields.users.attr("placeholder", 'users names separated with a comma character (e.g. "user1,user2")');
      paramFields.groups.attr("placeholder", 'users names separated with a comma character (e.g. "group1,group2")');
      paramFields.id.on("change paste keyup", updateUrl);
      paramFields.lang.on("change paste keyup", updateUrl);

      function updateUrl() {
        var filterId = paramFields.id.val() !== '' ? paramFields.id.val() : undefined;
        var langParam = paramFields.lang.val() !== '' ? '?lang=' + paramFields.lang.val() : '';
        paramFields.url.val(BASE_URL + VERSION_PREFIX + 'jobFilters/' + (filterId || DEFAULT_FILTER_ID) + '?action=unshare' + langParam);
      }
    },
    getJobs: function () {
      var $root = $('article[data-name="' + GET_JOBS_REQUEST_NAME + '"]');
      var paramFields = {
        fields: $root.find("input[data-sample-request-param-name='fields']"),
        sort: $root.find("input[data-sample-request-param-name='sort']"),
        limit: $root.find("input[data-sample-request-param-name='limit']"),
        lastUpdated: $root.find("input[data-sample-request-param-name='lastUpdated']"),
        data: $root.find("input[data-sample-request-param-name='data']"),
        filter: $root.find("input[data-sample-request-param-name='filter']")
      };
      var date = new Date();
      date.setDate(date.getDate() - 5);
      var fields = 'name,checkpointName,flowName,userName,size';
      var sort = '-size';
      var limit = 50;
      var lastUpdated = date.toISOString();
      paramFields.fields.val(fields);
      paramFields.sort.val(sort);
      paramFields.limit.val(limit);
      paramFields.lastUpdated.val(lastUpdated);
      var queryBuilder = $(".querybuilder");
      var isQueryBuilderEnabled = false;
      $root.find(".sample-request-querybuilder").off("click");
      $root.find(".sample-request-querybuilder").on("click", function (e) {
        e.preventDefault();
        var slideTime = 0;
        if (isQueryBuilderEnabled === false) {
          queryBuilder.css({
            display: 'none',
            minHeight: '100px'
          }).slideDown(slideTime, function () {
            isQueryBuilderEnabled = true;
            queryBuilder.queryBuilder(filterOptions);
            queryBuilder.on('afterUpdateRuleValue.queryBuilder', updateQueryString);
            queryBuilder.on('afterUpdateGroupCondition.queryBuilder', updateQueryString);
          });
        } else {
          queryBuilder.slideUp(slideTime, function () {
            isQueryBuilderEnabled = false;
            paramFields.filter.val('');
            queryBuilder.off('afterUpdateRuleValue.queryBuilder');
            queryBuilder.queryBuilder('destroy');
          });
        }
      });

      function updateQueryString(e, rule, error, value) {
        const rules = queryBuilder.queryBuilder('getRules');
        if (!jQuery.isEmptyObject(rules)) {
          paramFields.filter.val(transformFilterFormat(JSON.stringify(rules)));
        }
      };
    },
    addMessageFilter: function () {
      var $root = $('article[data-name="' + ADD_MESSAGE_FILTER_REQUEST_NAME + '"]');
      var paramFields = {
        url: $root.find("input.sample-request-url"),
        name: $root.find("input[data-sample-request-param-name='name']"),
        query: $root.find("input[data-sample-request-param-name='query']"),
        lang: $root.find("input[data-sample-request-param-name='lang']")
      };
      var name = 'example';
      var query = '{}';
      paramFields.name.val(name);
      paramFields.query.val(query);

      // Add lang to the url
      var baseUrlValue = paramFields.url.val();
      paramFields.lang.on("change paste keyup", function () {
        var targetValue = $(this).val();
        paramFields.url.val(baseUrlValue + '?lang=' + targetValue);
      });
    },
    editMessageFilter: function () {
      var $root = $('article[data-name="' + EDIT_MESSAGE_FILTER_REQUEST_NAME + '"]');
      var filterIdValue;
      var paramFields = {
        url: $root.find("input.sample-request-url"),
        id: $root.find("input[data-sample-request-param-name='id']"),
        name: $root.find("input[data-sample-request-param-name='name']"),
        query: $root.find("input[data-sample-request-param-name='query']"),
        lang: $root.find("input[data-sample-request-param-name='lang']")
      };
      var name = 'example';
      var query = '{}';
      paramFields.name.val(name);
      paramFields.query.val(query);
      var baseUrlValue = paramFields.url.val();
      paramFields.url.val(baseUrlValue + '/' + DEFAULT_FILTER_ID);
      paramFields.id.val(DEFAULT_FILTER_ID);
      paramFields.id.on("change paste keyup", updateUrl);
      paramFields.lang.on("change paste keyup", updateUrl);

      function updateUrl() {
        var filterId = paramFields.id.val() !== '' ? paramFields.id.val() : undefined;
        var langParam = paramFields.lang.val() !== '' ? '?lang=' + paramFields.lang.val() : '';
        paramFields.url.val(BASE_URL + VERSION_PREFIX + 'messageFilters/' + (filterId || DEFAULT_FILTER_ID) + langParam);
      }
    },
    getMessagesList: function () {
      var $root = $('article[data-name="' + GET_MESSAGES_LIST_REQUEST_NAME + '"]');
      var paramFields = {
        period: $root.find("input[data-sample-request-param-name='period']"),
        timestamp: $root.find("input[data-sample-request-param-name='timestamp']"),
        flow: $root.find("input[data-sample-request-param-name='flow']"),
        type: $root.find("input[data-sample-request-param-name='type']"),
        element: $root.find("input[data-sample-request-param-name='element']"),
        prefix: $root.find("input[data-sample-request-param-name='prefix']"),
        job: $root.find("input[data-sample-request-param-name='job']"),
        message: $root.find("input[data-sample-request-param-name='message']"),
        limit: $root.find("input[data-sample-request-param-name='limit']"),
        sort: $root.find("input[data-sample-request-param-name='sort']"),
        range: $root.find("input[data-sample-request-param-name='range']"),
        lang: $root.find("input[data-sample-request-param-name='lang']")
      };
      var period = '';
      var timestamp = '';
      var flow = '';
      var type = 'info';
      var element = '';
      var prefix = '';
      var job = '';
      var message = '';
      var limit = 500;
      var sort = '-type';
      var range = '0,100';
      var lang = 'enUS';
      paramFields.period.val(period);
      paramFields.timestamp.val(timestamp);
      paramFields.flow.val(flow);
      paramFields.type.val(type);
      paramFields.element.val(element);
      paramFields.prefix.val(prefix);
      paramFields.job.val(job);
      paramFields.message.val(message);
      paramFields.limit.val(limit);
      paramFields.sort.val(sort);
      paramFields.range.val(range);
      paramFields.lang.val(lang);
    },

    clearMessages: function () {
      var $root = $('article[data-name="' + CLEAR_MESSAGES_REQUEST_NAME + '"]');
      var paramFields = {
        url: $root.find("input.sample-request-url"),
        lang: $root.find("input[data-sample-request-param-name='lang']")
      }
      var baseUrl = paramFields.url.val();
      paramFields.lang.on("change paste keyup", updateUrl);

      function updateUrl() {
        var langParam = paramFields.lang.val() !== '' ? '?lang=' + paramFields.lang.val() : '';
        paramFields.url.val(baseUrl + langParam);
      }
    },

    getSubmitpoints: function () {
      var submitpointIdValue;
      var $root = $('article[data-name="' + GET_SUBMITPOINTS_REQUEST_NAME + '"]');
      var paramFields = {
        url: $root.find("input.sample-request-url"),
        id: $root.find("input[data-sample-request-param-name='id']")
      };
      var baseUrlValue = paramFields.url.val();
      paramFields.url.val(baseUrlValue + '/' + DEFAULT_SUBMITPOINT_ID);
      paramFields.id.on("change paste keyup", function () {
        submitpointIdValue = $(this).val() !== '' ? $(this).val() : DEFAULT_SUBMITPOINT_ID;
        paramFields.url.val(baseUrlValue + '/' + submitpointIdValue);
      });
    },
    dashboard: function () {
      $('.' + DASHBOARD).remove();
      var $root = $('article[data-name="' + DASHBOARD + '"]');
      var url = $root.find("input.sample-request-url");
      $root.find("[data-sample-request-header-name='Content-Type'], [data-sample-request-header-name='Content-Type'] + span, [for='sample-request-header-field-Content-Type'], .sample-request-send, h3").hide();
      var dashboardlUrl = url.val();
      var rootUrl = "graphiql.html?graphqlEndpoint=" + encodeURIComponent(dashboardlUrl);
      var token = "&token=" + administratorToken || '\"\"';
      var query = "&query=" + encodeURIComponent(GRAPHQL_DEFAULT_QUERY);
      var variables = "&variables=" + encodeURIComponent(GRAPHQL_DEFAULT_VARIABLES);
      var operations = "&operationName=" + GRAPHQL_DEFAULT_OPERATION;
      var iframe = $('<iframe />', {
        class: DASHBOARD,
        src: rootUrl + token + query + variables + operations
      });
      url.on("change paste keyup", function () {
        rootUrl = "graphiql.html?graphqlEndpoint=" + encodeURIComponent(url.val());
        token = "&token=" + administratorToken || '\"\"';
        iframe.attr('src', rootUrl + token + query + variables + operations);
      });
      $root.append(iframe);
    },
    getGroups: function () {
      var $root = $('article[data-name="' + GET_GROUPS_REQUEST_NAME + '"]');
      var paramFields = {
        url: $root.find("input.sample-request-url"),
        lang: $root.find("input[data-sample-request-param-name='lang']")
      };
      updateUrl();
      paramFields.lang.on("change paste keyup", updateUrl);

      function updateUrl() {
        var langParam = paramFields.lang.val() !== '' ? '&lang=' + paramFields.lang.val() : '';
        paramFields.url.val(BASE_URL + VERSION_PREFIX + 'userpermissions/groups?' + langParam);
      }
    },
  };

  function replaceAuthorizationString(element, value) {
    var pattern = /[0-9A-Fa-f]{40}/g;
    var content = $(element).text().replace(pattern, value);
    $(element).text(content);
  }

  function sendSampleRequest(group, name, version, type) {
    var $root = $('article[data-group="' + group + '"][data-name="' + name + '"][data-version="' + version + '"]');
    var header = {};
    $root.find(".sample-request-header").each(function (i, element) {
      var group = $(element).data("sample-request-header-group");
      $root.find("[data-sample-request-header-group=\"" + group + "\"]").each(function (i, element) {
        var key = $(element).data("sample-request-header-name");
        var value = element.value;
        if (!element.optional && element.defaultValue !== '') {
          value = element.defaultValue;
        }
        header[key] = value;
      });
    });

    var param = {};
    var paramType = {};
    $root.find(".sample-request-param").each(function (i, element) {
      var group = $(element).data("sample-request-param-group");
      $root.find("[data-sample-request-param-group=\"" + group + "\"]").each(function (i, element) {
        var key = $(element).data("sample-request-param-name");
        var isObject = key.indexOf('.') !== -1;
        var value = element.value;
        if (!element.optional && element.defaultValue !== '') {
          value = element.defaultValue;
        }
        if (value !== '' && !isObject) {
          param[key] = value;
          paramType[key] = $(element).next().text();
        }
      });
    });

    var url = $root.find(".sample-request-url").val();
    var pattern = pathToRegexp(url, null);
    var matches = pattern.exec(url);
    for (var i = 1; i < matches.length; i++) {
      var key = matches[i].substr(1);
      if (param[key] !== undefined) {
        url = url.replace(matches[i], encodeURIComponent(param[key]));
        delete param[key];
      }
    }
    _.each(param, function (val, key) {
      if (key === 'id' && url.indexOf(val) !== -1) {
        delete param[key];
      }
    });

    $root.find(".sample-request-response").fadeTo(250, 1);
    $root.find(".sample-request-response-json").html("Loading...");

    refreshScrollSpy();

    _.each(param, function (val, key) {
      var t = paramType[key].toLowerCase();
      if (t === 'object' || t === 'array') {
        try {
          param[key] = JSON.parse(val);
        } catch (e) { }
      }
    });

    // encode parameter with filter query before sending request
    if (group === 'Jobs') {
      var jobReplaceKey = 'filter';
      if (_.has(param, jobReplaceKey)) {
        param[jobReplaceKey] = encodeURIComponent(param[jobReplaceKey]);
      }
    }

    if (type === 'delete') {
      if (url.indexOf('?') < 0) {
        url += '?';
      } else {
        url += '&';
      }
      ajaxRequest = {
        url: url + getAsUriParameters(param),
        headers: header,
        type: type.toUpperCase(),
        success: displaySuccess,
        error: displayError
      };
    } else if ((name === POST_JOB_REQUEST_NAME || name === REPLACE_THE_JOB_REQUEST_NAME) && uploadedFileData) {
      var formatData = new FormData();
      formatData.append('file[0][file]', uploadedFileData);
      $.each(param, function (key, value) {
        if (key != 'fileContent' && key != 'filePath') {
          formatData.append(key, value);
        }
        if (key == 'filePath') {
          formatData.append('file[0][path]', value);
        }
      });
      ajaxRequest = {
        url: url,
        headers: {
          Authorization: header.Authorization
        },
        data: formatData,
        cache: false,
        contentType: false,
        processData: false,
        type: type.toUpperCase(),
        success: displaySuccess,
        error: displayError
      };
    } else if (name === SHARE_JOB_FILTER_REQUEST_NAME || name === UNSHARE_JOB_FILTER_REQUEST_NAME) {
      postData = {
        users: param.users ? param.users.split(',') : [],
        groups: param.groups ? param.groups.split(',') : []
      }
      header['Content-Type'] = 'application/json';
      ajaxRequest = {
        url: url,
        headers: header,
        data: JSON.stringify(postData),
        type: type.toUpperCase(),
        success: displaySuccess,
        error: displayError
      };
    } else if (name === ADD_ANNOTATIONS_REQUEST_NAME || name === EDIT_ANNOTATION_REQUEST_NAME || name === SET_FLOW_DATA_REQUEST_NAME || name === GET_FLOWS_REQUEST_NAME) {
      if (name === ADD_ANNOTATIONS_REQUEST_NAME) {
        postData = param.annotations;
      } else if (name === EDIT_ANNOTATION_REQUEST_NAME) {
        postData = JSON.stringify(param.annotation);
      } else if (name === SET_FLOW_DATA_REQUEST_NAME) {
        postData = JSON.stringify({ annotations: JSON.parse($('#api-Flows-SetFlowData label[for="sample-request-param-field-data.annotations"] + div input')[0].value) });
      } else if (name === GET_FLOWS_REQUEST_NAME) {
        postData = null;
      }
      header['Content-Type'] = 'application/json';
      ajaxRequest = {
        url: url,
        headers: header,
        data: postData,
        type: type.toUpperCase(),
        success: displaySuccess,
        error: displayError
      };
    } else {
      var postData = param;
      if (header['Content-Type'] == 'application/json') {
        postData = JSON.stringify(param);
      }
      ajaxRequest = {
        url: url,
        headers: header,
        data: postData,
        type: type.toUpperCase(),
        success: displaySuccess,
        error: displayError
      };
    }

    $.ajax(ajaxRequest);

    function getAsUriParameters(data) {
      var url = '';
      for (var prop in data) {
        url += encodeURIComponent(prop) + '=' +
          encodeURIComponent(data[prop]) + '&';
      }
      return url.substring(0, url.length - 1);
    }

    function displaySuccess(data, status, jqXHR) {
      var jsonResponseObject;
      var jsonResponse;
      try {
        jsonResponseObject = JSON.parse(jqXHR.responseText);
        jsonResponse = JSON.stringify(jsonResponseObject, null, 4);
      } catch (e) {
        jsonResponse = data;
      }
      $root.find(".sample-request-response-json").text(jsonResponse);
      refreshScrollSpy();
      if (jsonResponseObject !== null && jsonResponseObject.hasOwnProperty('token')) {
        helpers.authentication(jsonResponseObject.token);
      }
      helpers.dashboard();
    }

    function displayError(jqXHR, textStatus, error) {
      var message = "Error " + jqXHR.status + ": " + error;
      var jsonResponse;
      try {
        jsonResponse = JSON.parse(jqXHR.responseText);
        jsonResponse = JSON.stringify(jsonResponse, null, 4);
      } catch (e) {
        jsonResponse = escape(jqXHR.responseText);
      }
      jsonResponse = decodeURIComponent(jsonResponse);
      if (jsonResponse)
        message += "<br>" + jsonResponse;
      if ($root.find(".sample-request-response").is(":visible"))
        $root.find(".sample-request-response").fadeTo(1, 0.1);
      $root.find(".sample-request-response").fadeTo(250, 1);
      $root.find(".sample-request-response-json").html(message);
      refreshScrollSpy();
    }
  }

  function transformFilterFormat(data) {
    var result = JSON.parse(data, function (key, value) {
      if (value.hasOwnProperty('condition') && value.hasOwnProperty('rules')) {
        var valueCondition = String(value.condition).toLowerCase();
        var query = {};
        query[valueCondition] = value.rules;
        if (value.rules.length) {
          value.rules.forEach(function myFunction(item, index, arr) {
            if (item.hasOwnProperty('field') && item.hasOwnProperty('operator') && item.hasOwnProperty('value')) {
              query[valueCondition][index] = {};
              query[valueCondition][index][item.field] = {};
              if ($.isArray(item.value)) {
                query[valueCondition][index][item.field][item.operator] = item.value.join(" ");
              } else {
                query[valueCondition][index][item.field][item.operator] = item.value;
              }
            }
          });
        }
        return query;
      } else {
        return value;
      }
    });
    return JSON.stringify(result);
  }

  function clearSampleRequest(group, name, version) {
    var $root = $('article[data-group="' + group + '"][data-name="' + name + '"][data-version="' + version + '"]');
    $root.find(".sample-request-response-json").html("");
    $root.find(".sample-request-response").hide();
    $root.find(".sample-request-param").each(function (i, element) {
      element.value = "";
    });
    var $urlElement = $root.find(".sample-request-url");
    $urlElement.val($urlElement.prop("defaultValue"));
    refreshScrollSpy();
  }

  function refreshScrollSpy() {
    $('[data-spy="scroll"]').each(function () {
      $(this).scrollspy("refresh");
    });
  }

  return {
    initDynamic: init
  };
});
