Advertisement
Guest User

Untitled

a guest
Jul 12th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
jQuery 24.30 KB | None | 0 0
  1. /**
  2.  * Changes the order_by filter and reloads the datagrid
  3.  *
  4.  * @param string
  5.  *            id datagrid id
  6.  * @param string
  7.  *            key name of the field to order by
  8.  */
  9. var datagridv2_readyFunctions = [];
  10.  
  11. function datagridv2_registerReadyFunction(id, func) {
  12.     if (empty(datagridv2_readyFunctions[id])) {
  13.         datagridv2_readyFunctions[id] = [];
  14.     }
  15.     datagridv2_readyFunctions[id].push(func);
  16. }
  17.  
  18. function datagridv2_order(id, key) {
  19.     var order = jQuery('#order_by_' + id);
  20.     jQuery('.order_by_' + id + ' .datagrid_order_img').hide();
  21.     jQuery('.order_by_' + id + ' .datagrid_order_none').show();
  22.     if (order.val() == "" || order.val() != key + " ASC") {
  23.         order.val(key + " ASC");
  24.         jQuery('#order_by_' + id + '_' + key + ' .datagrid_order_none').hide();
  25.         jQuery('#order_by_' + id + '_' + key + ' .datagrid_order_asc').show();
  26.     } else {
  27.         order.val(key + " DESC");
  28.         jQuery('#order_by_' + id + '_' + key + ' .datagrid_order_none').hide();
  29.         jQuery('#order_by_' + id + '_' + key + ' .datagrid_order_desc').show();
  30.     }
  31.     datagridv2_reload(id);
  32. }
  33.  
  34. function datagridv2_pagin(id, page, nb) {
  35.     var pagin = jQuery('#pagin_page_' + id);
  36.     var nb_elem = jQuery('#pagin_nb_' + id);
  37.     var page_list = jQuery('#page_list_' + id);
  38.  
  39.     page_list.find('li').each(function () {
  40.         jQuery(this).removeClass('active');
  41.     });
  42.  
  43.     page_list.find('#page_' + page + '_' + id).addClass('active');
  44.  
  45.     pagin.val(page);
  46.     nb_elem.val(nb);
  47.  
  48.     datagridv2_reload(id);
  49. }
  50.  
  51. function datagridv2_reset(id) {
  52.     var form = jQuery('#datagridForm_' + id);
  53.     form.find('.datagridFilter').each(function () {
  54.         jQuery(this).val("");
  55.     });
  56.     form.find('#order_by_' + id).val("")
  57.  
  58.     datagridv2_reload(id);
  59. }
  60.  
  61. function datagridv2_saveInput(id) {
  62.     // Loader
  63.     showSpinner();
  64.  
  65.     var form = jQuery('#datagridForm_' + id);
  66.     var saveTarget = form.find('#save_target_' + id).val();
  67.     var data = {};
  68.     jQuery('#divSaveMessage_' + id).html('');
  69.  
  70.     data = datagridv2_getFormData(id, true);
  71.  
  72.     jQuery.ajax({
  73.         type: 'POST',
  74.         url: saveTarget,
  75.         data: data,
  76.         success: function (response) {
  77.             datagrid_save(response, id)
  78.         }
  79.     });
  80. }
  81.  
  82. function datagrid_save(response, id)
  83. {
  84.     hideSpinner();
  85.     datagridv2_reload(id);
  86.     jQuery('#divSaveMessage_' + id).html('');
  87.     if (undefined != response) {
  88.         response = JSON.parse(response);
  89.     }
  90.     jQuery('#tbody_' + id).find('.inputData.changeDatagridInput').each(function () {
  91.         if (undefined == response || response.error == false
  92.                 || (response.error == true && response.id[jQuery(this).parents('tr').attr('id')] != jQuery(this).parents('tr').attr('id'))) {
  93.             jQuery(this).removeClass('changeDatagridInput');
  94.             jQuery('#save_button_' + id).attr('disabled', 'disabled');
  95.         }
  96.     });
  97.     if (undefined !== response && undefined !== response.message) {
  98.         // datagridv2_reset(id);
  99.         jQuery('#divSaveMessage_' + id).html('<div class="alert ' + (response.error ? "alert-error" : "alert-success") + '"><span style="font-weight: 700;font-size: 20px;">' + response.message + '</span></div>');
  100.     }
  101.  
  102.     jQuery('body').animate({
  103.         scrollTop: 0
  104.     }, 1000);
  105. }
  106.  
  107. function datagridv2_getFormData(id, include_inputs) {
  108.     // HTTPRequest
  109.     var form = jQuery('#datagridForm_' + id);
  110.     var advancedform = jQuery('#datagridAdvancedForm_' + id);
  111.     var target = form.attr('action');
  112.     var data = {};
  113.     // for cake...
  114.     data.data = {};
  115.     data.data.filters = {};
  116.     data.data.order_by = [];
  117.     data.data.paginate = {};
  118.     data.data.input = [];
  119.  
  120.     if (include_inputs) {
  121.         var inputs = {};
  122.         form.find('.changeDatagridInput').closest('tr').find('.inputData').each(function () {
  123.             var temp = {};
  124.             parse_str(jQuery(this).attr('name') + "=" + jQuery(this).val(), temp);
  125.             inputs = array_replace_recursive(inputs, temp);
  126.         });
  127.         data.data.input = inputs.inputData;
  128.     }
  129.  
  130.     form.find('.datagridFilter').each(function () {
  131.         if (jQuery(this).val() != "") {
  132.             if (data.data.filters[jQuery(this).attr('name')] == undefined)
  133.                 data.data.filters[jQuery(this).attr('name')] = {};
  134.             data.data.filters[jQuery(this).attr('name')]['value'] = jQuery(this).val();
  135.         }
  136.     });
  137.  
  138.     advancedform.find('.datagridFilter').each(function () {
  139.         if (jQuery(this).val() != "") {
  140.             if (data.data.filters[jQuery(this).attr('name')] == undefined)
  141.                 data.data.filters[jQuery(this).attr('name')] = {};
  142.             data.data.filters[jQuery(this).attr('name')]['value'] = jQuery(this).val();
  143.         }
  144.     });
  145.  
  146.     advancedform.find('.datagridAdvanceFilter').each(function () {
  147.         if (jQuery(this).val() != "") {
  148.             if (data.data.filters[jQuery(this).attr('name')] == undefined)
  149.                 data.data.filters[jQuery(this).attr('name')] = {};
  150.             data.data.filters[jQuery(this).attr('name')]['operator'] = jQuery(
  151.                     this).val();
  152.         }
  153.     });
  154.  
  155.     if (form.find('#order_by_' + id).val() !== '')
  156.         data.data.order_by.push(form.find('#order_by_' + id).val());
  157.  
  158.     form.find('.paginationField').each(function () {
  159.         if (jQuery(this).val() != "") {
  160.             data.data.paginate[jQuery(this).attr('name')] = jQuery(this).val();
  161.         }
  162.     });
  163.  
  164.     data._securityToken = form.find('[name=_securityToken]').val();
  165.     return data;
  166. }
  167.  
  168. /**
  169.  * posts the data to the refresh action populates the data refreshes the
  170.  * datagrid and return a Promise so you can run an action on promise resolve
  171.  *
  172.  * @return Promise
  173.  * @param id String Datagrid id
  174.  */
  175. function datagridv2_reload(id) {
  176.     // Loader
  177.     showSpinner();
  178.  
  179.     var form = jQuery('#datagridForm_' + id);
  180.     var target = form.attr('action');
  181.     var data = datagridv2_getFormData(id);
  182.  
  183.     jQuery('#divSaveMessage_' + id).html('');
  184.  
  185.     return jQuery.ajax({
  186.         type: 'POST',
  187.         url: target,
  188.         data: data,
  189.         success: function (response) {
  190.             jQuery("#datagridData_" + id).html(response);
  191.             // refreshContent
  192.             datagridv2_refresh(id);
  193.             // end loader
  194.             hideSpinner();
  195.         }
  196.     });
  197. }
  198.  
  199. /**
  200.  * refreshes the datagrid with the data present (as json) in the page
  201.  *
  202.  * @param string
  203.  *            id datagrid id
  204.  */
  205. function datagridv2_refresh(id) {
  206.     // getData
  207.     var data = datagridv2_getData(id);
  208.     if (data === false) {
  209.         console.error("datagrid " + id + " failed to reload");
  210.         return false;
  211.     }
  212.  
  213.     // Render data
  214.     datagridv2_render(id, data);
  215.     handle_delete_link(id);
  216.  
  217.     // trigger a generic event
  218.     // var event = new Event('datagrid_refresh_' + id);
  219.     // window.dispatchEvent(event);
  220.     // /!\ warning /!\
  221.     // Above lines don't work in IE
  222.     // so, the following is a replacement.
  223.  
  224.     function CustomEvent(event, params) {
  225.         params = params || {bubbles: false, cancelable: false, detail: undefined};
  226.         var evt = document.createEvent('CustomEvent');
  227.         evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
  228.         return evt;
  229.     }
  230.  
  231.     CustomEvent.prototype = window.Event.prototype;
  232.     window.CustomEvent = CustomEvent;
  233.  
  234.     var event = new CustomEvent('datagrid_refresh_' + id);
  235.     window.dispatchEvent(event);
  236.  
  237.     return true;
  238. }
  239.  
  240. /**
  241.  * translates the data present in the div : datagridData_<id> and returns the
  242.  * jsonDecoded content
  243.  *
  244.  * @param string
  245.  *            id datagrid id
  246.  */
  247. function datagridv2_getData(id) {
  248.     var ret = [];
  249.     try {
  250.         ret = JSON.parse(jQuery("#datagridData_" + id).html());
  251.     } catch (e) {
  252.         console.error("Datagrid V2 Parsing error:", e);
  253.         return false;
  254.     }
  255.     return ret;
  256. }
  257.  
  258. /**
  259.  * builds up lines in the datagrid table with the given dataset
  260.  *
  261.  * @param string
  262.  *            id datagrid id
  263.  * @param string
  264.  *            data data to build table lines with
  265.  */
  266. function datagridv2_render(id, data) {
  267.     _renderContent(id, data);
  268.     _renderPagin(id, data.condition.paginate);
  269.  
  270.     datagridv2_executeReadyFunction(id);
  271. }
  272.  
  273. function datagridv2_executeReadyFunction(id) {
  274.     if (!empty(datagridv2_readyFunctions[id])) {
  275.         var target = jQuery('#' + id);
  276.         for (var i = 0; i < datagridv2_readyFunctions[id].length; i++) {
  277.             datagridv2_readyFunctions[id][i](id, target);
  278.         }
  279.     }
  280. }
  281.  
  282. function countProperties(obj) {
  283.     var count = 0;
  284.  
  285.     for (var prop in obj) {
  286.         if (obj.hasOwnProperty(prop))
  287.             ++count;
  288.     }
  289.  
  290.     return count;
  291. }
  292.  
  293. function _renderContent(id, data) {
  294.     var contentData = data.data;
  295.  
  296.     if (!Array.isArray(contentData)) {
  297.         console.error("Datagrid V2 Render error: jsonData should be array, "
  298.                 + typeof contentData + " given");
  299.         return false;
  300.     }
  301.  
  302.     if (data.meta['adding_row'] && data.meta['editable']) {
  303.         var empty_row = {_id: null};
  304.         jQuery.each(data.header, function (column) {
  305.             if (column != 'actions') {
  306.                 empty_row[column] = '';
  307.             } else {
  308.                 empty_row['actions'] = [];
  309.             }
  310.         });
  311.         data.data.push(empty_row);
  312.     }
  313.  
  314.     var content = '';
  315.     var totalLines = contentData.length;
  316.     for (var line = 0; line < totalLines; line++) {
  317.         var lineClass = (line % 2 == 0) ? 'even' : '';
  318.         var columnIndice = 0;
  319.         lineId = ('undefined' != typeof contentData[line]['_id']) ? contentData[line]['_id'] : '';
  320.         lineClass = ('undefined' != typeof contentData[line]['_class']) ? contentData[line]['_class'] : '';
  321.         if ('' != lineId) {
  322.             content += '<tr class="' + lineClass + '"  id="line_' + id + "_" + lineId + '">';
  323.         } else {
  324.             content += '<tr class="' + lineClass + '">';
  325.         }
  326.         for (column in contentData[line]) {
  327.             if (column == "_id" || column == "_class")
  328.                 continue;
  329.  
  330.             content += '<td id="' + id + "_" + lineId + '_' + 'column_' + columnIndice + '" class="' + id + "_" + 'column_' + columnIndice;
  331.             if (data.header[column] !== undefined && data.header[column].class !== undefined)
  332.                 content += ' ' + data.header[column].class;
  333.             if (contentData[line][column] !== null && contentData[line][column] !== undefined && contentData[line][column]['class'] !== null && contentData[line][column]['class'] !== undefined)
  334.                 content += ' ' + contentData[line][column]['class'];
  335.             content += '">';
  336.             columnIndice++;
  337.             if (data.meta['editable'] && column != 'actions') {
  338.                 // print Inputs
  339.                 fieldName = 'inputData[' + lineId + '][' + column + ']';
  340.                 if (!empty(data.input) && !empty(data.input[column])) {
  341.                     if (data.input[column]['type'] == "text") {
  342.                         content += '<input class="inputData form-control" type="text" value="'
  343.                                 + contentData[line][column]
  344.                                 + '" name="'
  345.                                 + fieldName + '" />';
  346.                     } else if (data.input[column]['type'] == "select"
  347.                             && typeof data.input[column]['value'] === 'object') {
  348.                         content += '<select class="inputData form-control" name="'
  349.                                 + fieldName + '" >';
  350.                         content += '<option value="#"></option>';
  351.                         for (selectValue in data.input[column]['value']) {
  352.                             if (data.input[column]['value'][selectValue] !== '') {
  353.                                 content += '<option value="'
  354.                                         + selectValue + '" '
  355.                                         + (selectValue == contentData[line][column] ? "selected='selected'"
  356.                                                 : "") + '>';
  357.                                 content += data.input[column]['value'][selectValue];
  358.                                 content += '</option>';
  359.                             }
  360.                         }
  361.                         content += "</select>";
  362.                     } else if (data.input[column]['type'] == "checkbox") {
  363.                         content += '<input class="inputData form-control" type="checkbox" value="'
  364.                                 + contentData[line][column]
  365.                                 + '" checked="'
  366.                                 + (contentData[line][column] ? 'checked' : '')
  367.                                 + '" + name="'
  368.                                 + fieldName
  369.                                 + '" />'
  370.                                 + contentData[line][column];
  371.                     } else if (data.input[column]['type'] == "textarea") {
  372.                         content += '<textarea class="inputData form-control" name="'
  373.                                 + fieldName + '" >' + contentData[line][column]
  374.                                 + '</textarea>';
  375.                     }
  376.                 } else {
  377.                     content += (contentData[line][column] ? contentData[line][column] : '');
  378.                 }
  379.             } else if (!Array.isArray(contentData[line][column])) {
  380.                 if (contentData[line][column] === undefined || contentData[line][column] === null)
  381.                     content += '';
  382.                 else if (typeof (contentData[line][column]) == 'object' && contentData[line][column]['data'] !== undefined && contentData[line][column]['data'] !== null)
  383.                     content += contentData[line][column]['data'];
  384.                 else if (contentData[line][column] !== undefined && contentData[line][column] !== null)
  385.                     content += contentData[line][column];
  386.             } else { // actions
  387.                 var totalActions = contentData[line][column].length;
  388.  
  389.                 for (var action = 0; action < totalActions; action++) {
  390.                     if (contentData[line][column][action]['custom'] !== undefined) {
  391.                         content += '<' + contentData[line][column][action]['custom']['tag'];
  392.                         var totalAttributes = countProperties(contentData[line][column][action]['custom']['attributes']);
  393.                         var keyAttribute = valueAttribute = '';
  394.                         for (var attributes = 0; attributes < totalAttributes; attributes++) {
  395.                             var keyValueAttribut = 0;
  396.                             if ((undefined !== Object) && (null !== Object)) {
  397.                                 jQuery.each(contentData[line][column][action]['custom']['attributes'], function (keyAttribute, valueAttribute) {
  398.                                     if (('' !== keyAttribute) && ('' !== valueAttribute)) {
  399.                                         content += ' ' + keyAttribute + '="' + valueAttribute + '"';
  400.                                     }
  401.                                 });
  402.                             }
  403.                         }
  404.  
  405.                         if (undefined !== contentData[line][column][action]['custom']['value']) {
  406.                             content += '>';
  407.                             if (undefined !== contentData[line][column][action]['custom']['icon'])
  408.                                 content += '<i class="' + contentData[line][column][action]['custom']['icon'] + ' datagrid-icon"></i> ';
  409.                             content += '<span class="datagrid-text">' + contentData[line][column][action]['custom']['value'] + '</span>';
  410.                             content += '</' + contentData[line][column][action]['custom']['tag'] + '>';
  411.                         } else {
  412.                             content += '/>';
  413.                         }
  414.                     } else {
  415.                         if (contentData[line][column][action]['title'] === undefined)
  416.                             var title = contentData[line][column][action]['icon'];
  417.                         else
  418.                             var title = contentData[line][column][action]['title'];
  419.  
  420.                         content += '<a class="icon-'
  421.                                 + contentData[line][column][action]['icon']
  422.                                 + '" href="'
  423.                                 + contentData[line][column][action]['href'];
  424.                         if (contentData[line][column][action]['onclick'] != undefined) {
  425.                             content += '" onclick="'
  426.                                     + contentData[line][column][action]['onclick'];
  427.                         }
  428.                         content += '" title="'
  429.                                 + title;
  430.  
  431.                         if (contentData[line][column][action]['data-id'] !== undefined)
  432.                             content += '" data-id="' + contentData[line][column][action]['data-id'];
  433.  
  434.                         var attrs = contentData[line][column][action]['attributes'];
  435.                         for (var attr in attrs) {
  436.                             if (attrs.hasOwnProperty(attr)) {
  437.                                 content += '" ' + attr + '="' + attrs[attr];
  438.                             }
  439.                         }
  440.                         content += '">';
  441.                         content += "</a>";
  442.                     }
  443.                     // CHANGE END
  444.                 }
  445.             }
  446.             content += '</td>';
  447.         }
  448.         content += '</tr>';
  449.     }
  450.     jQuery('#save_button_' + id).unbind('click').click(function () {
  451.         datagridv2_saveInput(id);
  452.     });
  453.     jQuery('#results_' + id).html(totalLines);
  454.     jQuery('#tbody_' + id).html(content).find('.inputData').each(function () {
  455.         jQuery(this).bind('input propertychange', function (e) {
  456.             jQuery(this).addClass('changeDatagridInput');
  457.             jQuery('#save_button_' + id).removeAttr('disabled');
  458.         });
  459.     });
  460.     if (content != '') {
  461.         jQuery('#tbody_no_result_' + id).hide();
  462.     } else//case where there is no data
  463.     {
  464.         jQuery('#tbody_no_result_' + id).show();
  465.     }
  466.     return true;
  467. }
  468.  
  469. function datagridv2_toggle_advanced_filter2(selector) {
  470.     if (selector.find(':selected').attr('data-double') === 'true')
  471.         selector.parent().find('.datagridFilter2').show();
  472.     else {
  473.         selector.parent().find('.datagridFilter2').hide();
  474.         selector.parent().find('.datagridFilter2').val('');
  475.     }
  476. }
  477.  
  478. window.smoothScrollTo = (function () {
  479.     var timer, start, factor;
  480.  
  481.     return function (target, duration) {
  482.         var offset = window.pageYOffset,
  483.                 delta = target - window.pageYOffset; // Y-offset difference
  484.         duration = duration || 1000;              // default 1 sec animation
  485.         start = Date.now();                       // get start time
  486.         factor = 0;
  487.  
  488.         if (timer) {
  489.             clearInterval(timer); // stop any running animations
  490.         }
  491.  
  492.         function step() {
  493.             var y;
  494.             factor = (Date.now() - start) / duration; // get interpolation factor
  495.             if (factor >= 1) {
  496.                 clearInterval(timer); // stop animation
  497.                 factor = 1;           // clip to max 1.0
  498.             }
  499.             y = factor * delta + offset;
  500.             window.scrollBy(0, y - window.pageYOffset);
  501.         }
  502.  
  503.         timer = setInterval(step, 10);
  504.         return timer;
  505.     };
  506. }());
  507.  
  508. function goToSmoothScrollId(id) {
  509.     var top_div = parseInt(jQuery('#' + id).offset().top) - 87;//top - header_size - close_button_size
  510.     smoothScrollTo(top_div);
  511. }
  512.  
  513. function goToSmoothScrollClass(id) {
  514.     var top_div = parseInt(jQuery('.' + id).offset().top) - 87;//top - header_size - close_button_size
  515.     smoothScrollTo(top_div);
  516. }
  517.  
  518. jQuery(document).ready(function () {
  519.     jQuery('.datagridAdvancedSearchClose').hide();
  520.     jQuery('.datagridAdvanceFilter').each(function () {
  521.         datagridv2_toggle_advanced_filter2(jQuery(this));
  522.     });
  523.     jQuery('.datagridAdvanceFilter').change(function () {
  524.         datagridv2_toggle_advanced_filter2(jQuery(this));
  525.     });
  526.     jQuery('#hideFilterSearch').on('click', function () {
  527.         jQuery('.datagridAdvancedSearch').hide();
  528.         jQuery('.datagridAdvancedSearchClose').show();
  529.         goToSmoothScrollClass('datagridAdvancedSearch');
  530.     });
  531.     jQuery('#showFilterSearch').on('click', function () {
  532.         jQuery('.datagridAdvancedSearch').show();
  533.         jQuery('.datagridAdvancedSearchClose').hide();
  534.         goToSmoothScrollClass('datagridAdvancedSearch');
  535.     });
  536. });
  537.  
  538. function _renderPagin(id, paginData) {
  539.     if (!paginData) {
  540.         return false;
  541.     }
  542.     if ((typeof paginData) != 'object') {
  543.         console.error("Datagrid V2 Pagination Render error: paginData should be object, " + typeof paginData + " given");
  544.         return false;
  545.     }
  546.     if (!paginData.hasOwnProperty("page") ||
  547.             !paginData.hasOwnProperty("nb") ||
  548.             !paginData.hasOwnProperty("page_total") ||
  549.             !paginData.hasOwnProperty("nb_total")) {
  550.         console.error("Datagrid V2 Pagination Render error: paginData is missing properties");
  551.         return false;
  552.     }
  553.  
  554.     var datagrid = jQuery('#' + id);
  555.     var pageList = datagrid.find('#page_list_' + id);
  556.     var displayedNb = datagrid.find('#total_results_' + id);
  557.     var listContent = "";
  558.  
  559.     var max_pages = 12;
  560.     var max_range = 3;
  561.     var min_page = (paginData.page - max_range < 1) ? 1 : paginData.page - max_range;
  562.     var max_increment = (paginData.page + max_range > paginData.page_total) ? paginData.page_total : paginData.page + max_range;
  563.  
  564.     if (paginData.page_total <= max_pages) {
  565.         for (var i = 1; i <= paginData.page_total; i++) {
  566.             listContent += '<li id="page_' + i + '_' + id + '" ';
  567.             listContent += 'onclick="datagridv2_pagin(\'' + id + '\', ' + i + ', \''
  568.                     + paginData.nb + '\');" ';
  569.             listContent += 'class="' + ((i == paginData.page) ? "active" : '')
  570.                     + '">';
  571.             listContent += '<span>' + i + '</span>';
  572.             listContent += '</li>';
  573.         }
  574.     } else {
  575.         if (min_page > 1) {
  576.             listContent += '<li onclick="datagridv2_pagin(\'' + id + '\', ' + 1 + ', \'' + paginData.nb + '\');" ><span > << </span></li>';
  577.             listContent += '<li><span style="background-color: inherit; border: none; cursor: auto;"> ... </span></li>';
  578.         }
  579.         for (var i = min_page; i <= max_increment; i++) {
  580.             listContent += '<li id="page_' + i + '_' + id + '" ';
  581.             listContent += 'onclick="datagridv2_pagin(\'' + id + '\', ' + i + ', \''
  582.                     + paginData.nb + '\');" ';
  583.             listContent += 'class="' + ((i == paginData.page) ? "active" : '')
  584.                     + '">';
  585.             listContent += '<span>' + i + '</span>';
  586.             listContent += '</li>';
  587.         }
  588.         if (max_increment < paginData.page_total) {
  589.             listContent += '<li><span style="background-color: inherit; border: none; cursor: auto;"> ... </span></li>';
  590.             listContent += '<li onclick="datagridv2_pagin(\'' + id + '\', ' + paginData.page_total + ', \'' + paginData.nb + '\');" ><span > >> </span></li>';
  591.         }
  592.     }
  593.  
  594.  
  595.     pageList.html(listContent);
  596.     displayedNb.html(paginData.nb_total);
  597.  
  598.     return true;
  599. }
  600.  
  601. function datagridv2_select_nb_elems(id) {
  602.     // get value
  603.     var selectedNb = jQuery("#select_nb_elems_" + id).val();
  604.     var totalNb = jQuery("#pagin_nb_total_" + id).val();
  605.     // calc hidden fields
  606.     jQuery("#pagin_page_" + id).val(1);
  607.     jQuery("#pagin_nb_" + id).val(selectedNb);
  608.     jQuery("#pagin_page_total_" + id).val(Math.ceil(totalNb / selectedNb));
  609.     // refresh
  610.     datagridv2_reload(id);
  611. }
  612.  
  613. function empty(content) {
  614.     return typeof content == 'undefined' || content == '' || content == [];
  615. }
  616.  
  617. function parse_str(str, array) {
  618.  
  619.     var strArr = String(str).replace(/^&/, '').replace(/&$/, '').split('&'), sal = strArr.length, i, j, ct, p, lastObj, obj, lastIter, undef, chr, tmp, key, value, postLeftBracketPos, keys, keysLen, fixStr = function (
  620.             str) {
  621.         return decodeURIComponent(str.replace(/\+/g, '%20'));
  622.     };
  623.  
  624.     if (!array) {
  625.         array = this.window;
  626.     }
  627.  
  628.     for (i = 0; i < sal; i++) {
  629.         tmp = strArr[i].split('=');
  630.         key = fixStr(tmp[0]);
  631.         value = (tmp.length < 2) ? '' : fixStr(tmp[1]);
  632.  
  633.         while (key.charAt(0) === ' ') {
  634.             key = key.slice(1);
  635.         }
  636.         if (key.indexOf('\x00') > -1) {
  637.             key = key.slice(0, key.indexOf('\x00'));
  638.         }
  639.         if (key && key.charAt(0) !== '[') {
  640.             keys = [];
  641.             postLeftBracketPos = 0;
  642.             for (j = 0; j < key.length; j++) {
  643.                 if (key.charAt(j) === '[' && !postLeftBracketPos) {
  644.                     postLeftBracketPos = j + 1;
  645.                 } else if (key.charAt(j) === ']') {
  646.                     if (postLeftBracketPos) {
  647.                         if (!keys.length) {
  648.                             keys.push(key.slice(0, postLeftBracketPos - 1));
  649.                         }
  650.                         keys.push(key.substr(postLeftBracketPos, j
  651.                                 - postLeftBracketPos));
  652.                         postLeftBracketPos = 0;
  653.                         if (key.charAt(j + 1) !== '[') {
  654.                             break;
  655.                         }
  656.                     }
  657.                 }
  658.             }
  659.             if (!keys.length) {
  660.                 keys = [key];
  661.             }
  662.             for (j = 0; j < keys[0].length; j++) {
  663.                 chr = keys[0].charAt(j);
  664.                 if (chr === ' ' || chr === '.' || chr === '[') {
  665.                     keys[0] = keys[0].substr(0, j) + '_'
  666.                             + keys[0].substr(j + 1);
  667.                 }
  668.                 if (chr === '[') {
  669.                     break;
  670.                 }
  671.             }
  672.  
  673.             obj = array;
  674.             for (j = 0, keysLen = keys.length; j < keysLen; j++) {
  675.                 key = keys[j].replace(/^['"]/, '').replace(/['"]$/, '');
  676.                 lastIter = j !== keys.length - 1;
  677.                 lastObj = obj;
  678.                 if ((key !== '' && key !== ' ') || j === 0) {
  679.                     if (obj[key] === undef) {
  680.                         obj[key] = {};
  681.                     }
  682.                     obj = obj[key];
  683.                 } else { // To insert new dimension
  684.                     ct = -1;
  685.                     for (p in obj) {
  686.                         if (obj.hasOwnProperty(p)) {
  687.                             if (+p > ct && p.match(/^\d+$/g)) {
  688.                                 ct = +p;
  689.                             }
  690.                         }
  691.                     }
  692.                     key = ct + 1;
  693.                 }
  694.             }
  695.             lastObj[key] = value;
  696.         }
  697.     }
  698. }
  699.  
  700. function array_replace_recursive(arr) {
  701.     // discuss at: http://phpjs.org/functions/array_replace_recursive/
  702.     // original by: Brett Zamir (http://brett-zamir.me)
  703.     // example 1: array_replace_recursive({'citrus' : ["orange"], 'berries' :
  704.     // ["blackberry", "raspberry"]}, {'citrus' : ['pineapple'], 'berries' :
  705.     // ['blueberry']});
  706.     // returns 1: {citrus : ['pineapple'], berries : ['blueberry', 'raspberry']}
  707.  
  708.     var retObj = {}, i = 0, p = '', argl = arguments.length;
  709.  
  710.     if (argl < 2) {
  711.         throw new Error(
  712.                 'There should be at least 2 arguments passed to array_replace_recursive()');
  713.     }
  714.  
  715.     // Although docs state that the arguments are passed in by reference, it
  716.     // seems they are not altered, but rather the copy that is returned (just
  717.     // guessing), so we make a copy here, instead of acting on arr itself
  718.     for (p in arr) {
  719.         retObj[p] = arr[p];
  720.     }
  721.  
  722.     for (i = 1; i < argl; i++) {
  723.         for (p in arguments[i]) {
  724.             if (retObj[p] && typeof retObj[p] === 'object') {
  725.                 retObj[p] = this.array_replace_recursive(retObj[p],
  726.                         arguments[i][p]);
  727.             } else {
  728.                 retObj[p] = arguments[i][p];
  729.             }
  730.         }
  731.     }
  732.     return retObj;
  733. }
  734.  
  735. function showSpinner() {
  736.     jQuery('.datagrid-backdrop').addClass('in');
  737. }
  738.  
  739. function hideSpinner() {
  740.     jQuery('.datagrid-backdrop').removeClass('in');
  741. }
  742.  
  743. function handle_delete_link(id) {
  744.     jQuery('#' + id + ' .delete-datagrid').click(function () {
  745.         let link = jQuery(this);
  746.         let confirmText = link.data('confirm-text');
  747.         let dataId = link.data('id');
  748.         if (typeof dataId != 'undefined') {
  749.             if (typeof confirmText != 'undefined') {
  750.                 if (!confirm(confirmText)) {
  751.                     return false;
  752.                 }
  753.             }
  754.             jQuery.ajax({
  755.                 url: link.attr('href'),
  756.                 method: "POST",
  757.                 data: {id: dataId, '_securityToken': jQuery('#' + id + ' [name=_securityToken]').val()}
  758.             }).done(function (response) {
  759.                 if (response != 'undefined') {
  760.                     let response = JSON.parse(response)
  761.                     jQuery('#divSaveMessage_' + id).html('<div class="alert ' + (response.error ? "alert-error" : "alert-success") + '"><span style="font-weight: 700;font-size: 20px;">' + response.message + '</span></div>')
  762.                 }
  763.             });
  764.             datagridv2_reload(id)
  765.         }
  766.         return false
  767.     });
  768. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement