code
stringlengths
1
2.08M
language
stringclasses
1 value
(function ($) { /** * Move a block in the blocks table from one region to another via select list. * * This behavior is dependent on the tableDrag behavior, since it uses the * objects initialized in that behavior to update the row. */ Drupal.behaviors.termDrag = { attach: function (context, settings) { var table = $('#taxonomy', context); var tableDrag = Drupal.tableDrag.taxonomy; // Get the blocks tableDrag object. var rows = $('tr', table).length; // When a row is swapped, keep previous and next page classes set. tableDrag.row.prototype.onSwap = function (swappedRow) { $('tr.taxonomy-term-preview', table).removeClass('taxonomy-term-preview'); $('tr.taxonomy-term-divider-top', table).removeClass('taxonomy-term-divider-top'); $('tr.taxonomy-term-divider-bottom', table).removeClass('taxonomy-term-divider-bottom'); if (settings.taxonomy.backStep) { for (var n = 0; n < settings.taxonomy.backStep; n++) { $(table[0].tBodies[0].rows[n]).addClass('taxonomy-term-preview'); } $(table[0].tBodies[0].rows[settings.taxonomy.backStep - 1]).addClass('taxonomy-term-divider-top'); $(table[0].tBodies[0].rows[settings.taxonomy.backStep]).addClass('taxonomy-term-divider-bottom'); } if (settings.taxonomy.forwardStep) { for (var n = rows - settings.taxonomy.forwardStep - 1; n < rows - 1; n++) { $(table[0].tBodies[0].rows[n]).addClass('taxonomy-term-preview'); } $(table[0].tBodies[0].rows[rows - settings.taxonomy.forwardStep - 2]).addClass('taxonomy-term-divider-top'); $(table[0].tBodies[0].rows[rows - settings.taxonomy.forwardStep - 1]).addClass('taxonomy-term-divider-bottom'); } }; } }; })(jQuery);
JavaScript
/** * @file * Provides JavaScript additions to the managed file field type. * * This file provides progress bar support (if available), popup windows for * file previews, and disabling of other file fields during Ajax uploads (which * prevents separate file fields from accidentally uploading files). */ (function ($) { /** * Attach behaviors to managed file element upload fields. */ Drupal.behaviors.fileValidateAutoAttach = { attach: function (context, settings) { if (settings.file && settings.file.elements) { $.each(settings.file.elements, function(selector) { var extensions = settings.file.elements[selector]; $(selector, context).bind('change', {extensions: extensions}, Drupal.file.validateExtension); }); } }, detach: function (context, settings) { if (settings.file && settings.file.elements) { $.each(settings.file.elements, function(selector) { $(selector, context).unbind('change', Drupal.file.validateExtension); }); } } }; /** * Attach behaviors to the file upload and remove buttons. */ Drupal.behaviors.fileButtons = { attach: function (context) { $('input.form-submit', context).bind('mousedown', Drupal.file.disableFields); $('div.form-managed-file input.form-submit', context).bind('mousedown', Drupal.file.progressBar); }, detach: function (context) { $('input.form-submit', context).unbind('mousedown', Drupal.file.disableFields); $('div.form-managed-file input.form-submit', context).unbind('mousedown', Drupal.file.progressBar); } }; /** * Attach behaviors to links within managed file elements. */ Drupal.behaviors.filePreviewLinks = { attach: function (context) { $('div.form-managed-file .file a, .file-widget .file a', context).bind('click',Drupal.file.openInNewWindow); }, detach: function (context){ $('div.form-managed-file .file a, .file-widget .file a', context).unbind('click', Drupal.file.openInNewWindow); } }; /** * File upload utility functions. */ Drupal.file = Drupal.file || { /** * Client-side file input validation of file extensions. */ validateExtension: function (event) { // Remove any previous errors. $('.file-upload-js-error').remove(); // Add client side validation for the input[type=file]. var extensionPattern = event.data.extensions.replace(/,\s*/g, '|'); if (extensionPattern.length > 1 && this.value.length > 0) { var acceptableMatch = new RegExp('\\.(' + extensionPattern + ')$', 'gi'); if (!acceptableMatch.test(this.value)) { var error = Drupal.t("The selected file %filename cannot be uploaded. Only files with the following extensions are allowed: %extensions.", { // According to the specifications of HTML5, a file upload control // should not reveal the real local path to the file that a user // has selected. Some web browsers implement this restriction by // replacing the local path with "C:\fakepath\", which can cause // confusion by leaving the user thinking perhaps Drupal could not // find the file because it messed up the file path. To avoid this // confusion, therefore, we strip out the bogus fakepath string. '%filename': this.value.replace('C:\\fakepath\\', ''), '%extensions': extensionPattern.replace(/\|/g, ', ') }); $(this).closest('div.form-managed-file').prepend('<div class="messages error file-upload-js-error">' + error + '</div>'); this.value = ''; return false; } } }, /** * Prevent file uploads when using buttons not intended to upload. */ disableFields: function (event){ var clickedButton = this; // Only disable upload fields for Ajax buttons. if (!$(clickedButton).hasClass('ajax-processed')) { return; } // Check if we're working with an "Upload" button. var $enabledFields = []; if ($(this).closest('div.form-managed-file').length > 0) { $enabledFields = $(this).closest('div.form-managed-file').find('input.form-file'); } // Temporarily disable upload fields other than the one we're currently // working with. Filter out fields that are already disabled so that they // do not get enabled when we re-enable these fields at the end of behavior // processing. Re-enable in a setTimeout set to a relatively short amount // of time (1 second). All the other mousedown handlers (like Drupal's Ajax // behaviors) are excuted before any timeout functions are called, so we // don't have to worry about the fields being re-enabled too soon. // @todo If the previous sentence is true, why not set the timeout to 0? var $fieldsToTemporarilyDisable = $('div.form-managed-file input.form-file').not($enabledFields).not(':disabled'); $fieldsToTemporarilyDisable.attr('disabled', 'disabled'); setTimeout(function (){ $fieldsToTemporarilyDisable.attr('disabled', false); }, 1000); }, /** * Add progress bar support if possible. */ progressBar: function (event) { var clickedButton = this; var $progressId = $(clickedButton).closest('div.form-managed-file').find('input.file-progress'); if ($progressId.length) { var originalName = $progressId.attr('name'); // Replace the name with the required identifier. $progressId.attr('name', originalName.match(/APC_UPLOAD_PROGRESS|UPLOAD_IDENTIFIER/)[0]); // Restore the original name after the upload begins. setTimeout(function () { $progressId.attr('name', originalName); }, 1000); } // Show the progress bar if the upload takes longer than half a second. setTimeout(function () { $(clickedButton).closest('div.form-managed-file').find('div.ajax-progress-bar').slideDown(); }, 500); }, /** * Open links to files within forms in a new window. */ openInNewWindow: function (event) { $(this).attr('target', '_blank'); window.open(this.href, 'filePreview', 'toolbar=0,scrollbars=1,location=1,statusbar=1,menubar=0,resizable=1,width=500,height=550'); return false; } }; })(jQuery);
JavaScript
(function ($) { Drupal.toolbar = Drupal.toolbar || {}; /** * Attach toggling behavior and notify the overlay of the toolbar. */ Drupal.behaviors.toolbar = { attach: function(context) { // Set the initial state of the toolbar. $('#toolbar', context).once('toolbar', Drupal.toolbar.init); // Toggling toolbar drawer. $('#toolbar a.toggle', context).once('toolbar-toggle').click(function(e) { Drupal.toolbar.toggle(); // Allow resize event handlers to recalculate sizes/positions. $(window).triggerHandler('resize'); return false; }); } }; /** * Retrieve last saved cookie settings and set up the initial toolbar state. */ Drupal.toolbar.init = function() { // Retrieve the collapsed status from a stored cookie. var collapsed = $.cookie('Drupal.toolbar.collapsed'); // Expand or collapse the toolbar based on the cookie value. if (collapsed == 1) { Drupal.toolbar.collapse(); } else { Drupal.toolbar.expand(); } }; /** * Collapse the toolbar. */ Drupal.toolbar.collapse = function() { var toggle_text = Drupal.t('Show shortcuts'); $('#toolbar div.toolbar-drawer').addClass('collapsed'); $('#toolbar a.toggle') .removeClass('toggle-active') .attr('title', toggle_text) .html(toggle_text); $('body').removeClass('toolbar-drawer').css('paddingTop', Drupal.toolbar.height()); $.cookie( 'Drupal.toolbar.collapsed', 1, { path: Drupal.settings.basePath, // The cookie should "never" expire. expires: 36500 } ); }; /** * Expand the toolbar. */ Drupal.toolbar.expand = function() { var toggle_text = Drupal.t('Hide shortcuts'); $('#toolbar div.toolbar-drawer').removeClass('collapsed'); $('#toolbar a.toggle') .addClass('toggle-active') .attr('title', toggle_text) .html(toggle_text); $('body').addClass('toolbar-drawer').css('paddingTop', Drupal.toolbar.height()); $.cookie( 'Drupal.toolbar.collapsed', 0, { path: Drupal.settings.basePath, // The cookie should "never" expire. expires: 36500 } ); }; /** * Toggle the toolbar. */ Drupal.toolbar.toggle = function() { if ($('#toolbar div.toolbar-drawer').hasClass('collapsed')) { Drupal.toolbar.expand(); } else { Drupal.toolbar.collapse(); } }; Drupal.toolbar.height = function() { var $toolbar = $('#toolbar'); var height = $toolbar.outerHeight(); // In modern browsers (including IE9), when box-shadow is defined, use the // normal height. var cssBoxShadowValue = $toolbar.css('box-shadow'); var boxShadow = (typeof cssBoxShadowValue !== 'undefined' && cssBoxShadowValue !== 'none'); // In IE8 and below, we use the shadow filter to apply box-shadow styles to // the toolbar. It adds some extra height that we need to remove. if (!boxShadow && /DXImageTransform\.Microsoft\.Shadow/.test($toolbar.css('filter'))) { height -= $toolbar[0].filters.item("DXImageTransform.Microsoft.Shadow").strength; } return height; }; })(jQuery);
JavaScript
(function ($) { /** * Attach handlers to evaluate the strength of any password fields and to check * that its confirmation is correct. */ Drupal.behaviors.password = { attach: function (context, settings) { var translate = settings.password; $('input.password-field', context).once('password', function () { var passwordInput = $(this); var innerWrapper = $(this).parent(); var outerWrapper = $(this).parent().parent(); // Add identifying class to password element parent. innerWrapper.addClass('password-parent'); // Add the password confirmation layer. $('input.password-confirm', outerWrapper).parent().prepend('<div class="password-confirm">' + translate['confirmTitle'] + ' <span></span></div>').addClass('confirm-parent'); var confirmInput = $('input.password-confirm', outerWrapper); var confirmResult = $('div.password-confirm', outerWrapper); var confirmChild = $('span', confirmResult); // Add the description box. var passwordMeter = '<div class="password-strength"><div class="password-strength-text" aria-live="assertive"></div><div class="password-strength-title">' + translate['strengthTitle'] + '</div><div class="password-indicator"><div class="indicator"></div></div></div>'; $(confirmInput).parent().after('<div class="password-suggestions description"></div>'); $(innerWrapper).prepend(passwordMeter); var passwordDescription = $('div.password-suggestions', outerWrapper).hide(); // Check the password strength. var passwordCheck = function () { // Evaluate the password strength. var result = Drupal.evaluatePasswordStrength(passwordInput.val(), settings.password); // Update the suggestions for how to improve the password. if (passwordDescription.html() != result.message) { passwordDescription.html(result.message); } // Only show the description box if there is a weakness in the password. if (result.strength == 100) { passwordDescription.hide(); } else { passwordDescription.show(); } // Adjust the length of the strength indicator. $(innerWrapper).find('.indicator').css('width', result.strength + '%'); // Update the strength indication text. $(innerWrapper).find('.password-strength-text').html(result.indicatorText); passwordCheckMatch(); }; // Check that password and confirmation inputs match. var passwordCheckMatch = function () { if (confirmInput.val()) { var success = passwordInput.val() === confirmInput.val(); // Show the confirm result. confirmResult.css({ visibility: 'visible' }); // Remove the previous styling if any exists. if (this.confirmClass) { confirmChild.removeClass(this.confirmClass); } // Fill in the success message and set the class accordingly. var confirmClass = success ? 'ok' : 'error'; confirmChild.html(translate['confirm' + (success ? 'Success' : 'Failure')]).addClass(confirmClass); this.confirmClass = confirmClass; } else { confirmResult.css({ visibility: 'hidden' }); } }; // Monitor keyup and blur events. // Blur must be used because a mouse paste does not trigger keyup. passwordInput.keyup(passwordCheck).focus(passwordCheck).blur(passwordCheck); confirmInput.keyup(passwordCheckMatch).blur(passwordCheckMatch); }); } }; /** * Evaluate the strength of a user's password. * * Returns the estimated strength and the relevant output message. */ Drupal.evaluatePasswordStrength = function (password, translate) { var weaknesses = 0, strength = 100, msg = []; var hasLowercase = /[a-z]+/.test(password); var hasUppercase = /[A-Z]+/.test(password); var hasNumbers = /[0-9]+/.test(password); var hasPunctuation = /[^a-zA-Z0-9]+/.test(password); // If there is a username edit box on the page, compare password to that, otherwise // use value from the database. var usernameBox = $('input.username'); var username = (usernameBox.length > 0) ? usernameBox.val() : translate.username; // Lose 5 points for every character less than 6, plus a 30 point penalty. if (password.length < 6) { msg.push(translate.tooShort); strength -= ((6 - password.length) * 5) + 30; } // Count weaknesses. if (!hasLowercase) { msg.push(translate.addLowerCase); weaknesses++; } if (!hasUppercase) { msg.push(translate.addUpperCase); weaknesses++; } if (!hasNumbers) { msg.push(translate.addNumbers); weaknesses++; } if (!hasPunctuation) { msg.push(translate.addPunctuation); weaknesses++; } // Apply penalty for each weakness (balanced against length penalty). switch (weaknesses) { case 1: strength -= 12.5; break; case 2: strength -= 25; break; case 3: strength -= 40; break; case 4: strength -= 40; break; } // Check if password is the same as the username. if (password !== '' && password.toLowerCase() === username.toLowerCase()) { msg.push(translate.sameAsUsername); // Passwords the same as username are always very weak. strength = 5; } // Based on the strength, work out what text should be shown by the password strength meter. if (strength < 60) { indicatorText = translate.weak; } else if (strength < 70) { indicatorText = translate.fair; } else if (strength < 80) { indicatorText = translate.good; } else if (strength <= 100) { indicatorText = translate.strong; } // Assemble the final message. msg = translate.hasWeaknesses + '<ul><li>' + msg.join('</li><li>') + '</li></ul>'; return { strength: strength, message: msg, indicatorText: indicatorText }; }; /** * Field instance settings screen: force the 'Display on registration form' * checkbox checked whenever 'Required' is checked. */ Drupal.behaviors.fieldUserRegistration = { attach: function (context, settings) { var $checkbox = $('form#field-ui-field-edit-form input#edit-instance-settings-user-register-form'); if ($checkbox.length) { $('input#edit-instance-required', context).once('user-register-form-checkbox', function () { $(this).bind('change', function (e) { if ($(this).attr('checked')) { $checkbox.attr('checked', true); } }); }); } } }; })(jQuery);
JavaScript
(function ($) { /** * Shows checked and disabled checkboxes for inherited permissions. */ Drupal.behaviors.permissions = { attach: function (context) { var self = this; $('table#permissions').once('permissions', function () { // On a site with many roles and permissions, this behavior initially has // to perform thousands of DOM manipulations to inject checkboxes and hide // them. By detaching the table from the DOM, all operations can be // performed without triggering internal layout and re-rendering processes // in the browser. var $table = $(this); if ($table.prev().length) { var $ancestor = $table.prev(), method = 'after'; } else { var $ancestor = $table.parent(), method = 'append'; } $table.detach(); // Create dummy checkboxes. We use dummy checkboxes instead of reusing // the existing checkboxes here because new checkboxes don't alter the // submitted form. If we'd automatically check existing checkboxes, the // permission table would be polluted with redundant entries. This // is deliberate, but desirable when we automatically check them. var $dummy = $('<input type="checkbox" class="dummy-checkbox" disabled="disabled" checked="checked" />') .attr('title', Drupal.t("This permission is inherited from the authenticated user role.")) .hide(); $('input[type=checkbox]', this).not('.rid-2, .rid-1').addClass('real-checkbox').each(function () { $dummy.clone().insertAfter(this); }); // Initialize the authenticated user checkbox. $('input[type=checkbox].rid-2', this) .bind('click.permissions', self.toggle) // .triggerHandler() cannot be used here, as it only affects the first // element. .each(self.toggle); // Re-insert the table into the DOM. $ancestor[method]($table); }); }, /** * Toggles all dummy checkboxes based on the checkboxes' state. * * If the "authenticated user" checkbox is checked, the checked and disabled * checkboxes are shown, the real checkboxes otherwise. */ toggle: function () { var authCheckbox = this, $row = $(this).closest('tr'); // jQuery performs too many layout calculations for .hide() and .show(), // leading to a major page rendering lag on sites with many roles and // permissions. Therefore, we toggle visibility directly. $row.find('.real-checkbox').each(function () { this.style.display = (authCheckbox.checked ? 'none' : ''); }); $row.find('.dummy-checkbox').each(function () { this.style.display = (authCheckbox.checked ? '' : 'none'); }); } }; })(jQuery);
JavaScript
/** * @file * Attaches behaviors for the Path module. */ (function ($) { Drupal.behaviors.pathFieldsetSummaries = { attach: function (context) { $('fieldset.path-form', context).drupalSetSummary(function (context) { var path = $('.form-item-path-alias input').val(); return path ? Drupal.t('Alias: @alias', { '@alias': path }) : Drupal.t('No alias'); }); } }; })(jQuery);
JavaScript
(function ($) { Drupal.behaviors.commentFieldsetSummaries = { attach: function (context) { $('fieldset.comment-node-settings-form', context).drupalSetSummary(function (context) { return Drupal.checkPlain($('.form-item-comment input:checked', context).next('label').text()); }); // Provide the summary for the node type form. $('fieldset.comment-node-type-settings-form', context).drupalSetSummary(function(context) { var vals = []; // Default comment setting. vals.push($(".form-item-comment select option:selected", context).text()); // Threading. var threading = $(".form-item-comment-default-mode input:checked", context).next('label').text(); if (threading) { vals.push(threading); } // Comments per page. var number = $(".form-item-comment-default-per-page select option:selected", context).val(); vals.push(Drupal.t('@number comments per page', {'@number': number})); return Drupal.checkPlain(vals.join(', ')); }); } }; })(jQuery);
JavaScript
/** * @file * Javascript behaviors for the Book module. */ (function ($) { Drupal.behaviors.bookFieldsetSummaries = { attach: function (context) { $('fieldset.book-outline-form', context).drupalSetSummary(function (context) { var $select = $('.form-item-book-bid select'); var val = $select.val(); if (val === '0') { return Drupal.t('Not in book'); } else if (val === 'new') { return Drupal.t('New book'); } else { return Drupal.checkPlain($select.find(':selected').text()); } }); } }; })(jQuery);
JavaScript
(function ($) { Drupal.behaviors.openid = { attach: function (context) { var loginElements = $('.form-item-name, .form-item-pass, li.openid-link'); var openidElements = $('.form-item-openid-identifier, li.user-link'); var cookie = $.cookie('Drupal.visitor.openid_identifier'); // This behavior attaches by ID, so is only valid once on a page. if (!$('#edit-openid-identifier.openid-processed').length) { if (cookie) { $('#edit-openid-identifier').val(cookie); } if ($('#edit-openid-identifier').val() || location.hash == '#openid-login') { $('#edit-openid-identifier').addClass('openid-processed'); loginElements.hide(); // Use .css('display', 'block') instead of .show() to be Konqueror friendly. openidElements.css('display', 'block'); } } $('li.openid-link:not(.openid-processed)', context) .addClass('openid-processed') .click(function () { loginElements.hide(); openidElements.css('display', 'block'); // Remove possible error message. $('#edit-name, #edit-pass').removeClass('error'); $('div.messages.error').hide(); // Set focus on OpenID Identifier field. $('#edit-openid-identifier')[0].focus(); return false; }); $('li.user-link:not(.openid-processed)', context) .addClass('openid-processed') .click(function () { openidElements.hide(); loginElements.css('display', 'block'); // Clear OpenID Identifier field and remove possible error message. $('#edit-openid-identifier').val('').removeClass('error'); $('div.messages.error').css('display', 'block'); // Set focus on username field. $('#edit-name')[0].focus(); return false; }); } }; })(jQuery);
JavaScript
(function ($) { Drupal.behaviors.nodeFieldsetSummaries = { attach: function (context) { $('fieldset.node-form-revision-information', context).drupalSetSummary(function (context) { var revisionCheckbox = $('.form-item-revision input', context); // Return 'New revision' if the 'Create new revision' checkbox is checked, // or if the checkbox doesn't exist, but the revision log does. For users // without the "Administer content" permission the checkbox won't appear, // but the revision log will if the content type is set to auto-revision. if (revisionCheckbox.is(':checked') || (!revisionCheckbox.length && $('.form-item-log textarea', context).length)) { return Drupal.t('New revision'); } return Drupal.t('No revision'); }); $('fieldset.node-form-author', context).drupalSetSummary(function (context) { var name = $('.form-item-name input', context).val() || Drupal.settings.anonymous, date = $('.form-item-date input', context).val(); return date ? Drupal.t('By @name on @date', { '@name': name, '@date': date }) : Drupal.t('By @name', { '@name': name }); }); $('fieldset.node-form-options', context).drupalSetSummary(function (context) { var vals = []; $('input:checked', context).parent().each(function () { vals.push(Drupal.checkPlain($.trim($(this).text()))); }); if (!$('.form-item-status input', context).is(':checked')) { vals.unshift(Drupal.t('Not published')); } return vals.join(', '); }); } }; })(jQuery);
JavaScript
(function ($) { Drupal.behaviors.contentTypes = { attach: function (context) { // Provide the vertical tab summaries. $('fieldset#edit-submission', context).drupalSetSummary(function(context) { var vals = []; vals.push(Drupal.checkPlain($('#edit-title-label', context).val()) || Drupal.t('Requires a title')); return vals.join(', '); }); $('fieldset#edit-workflow', context).drupalSetSummary(function(context) { var vals = []; $("input[name^='node_options']:checked", context).parent().each(function() { vals.push(Drupal.checkPlain($(this).text())); }); if (!$('#edit-node-options-status', context).is(':checked')) { vals.unshift(Drupal.t('Not published')); } return vals.join(', '); }); $('fieldset#edit-display', context).drupalSetSummary(function(context) { var vals = []; $('input:checked', context).next('label').each(function() { vals.push(Drupal.checkPlain($(this).text())); }); if (!$('#edit-node-submitted', context).is(':checked')) { vals.unshift(Drupal.t("Don't display post information")); } return vals.join(', '); }); } }; })(jQuery);
JavaScript
(function ($) { /** * Show/hide the 'Email site administrator when updates are available' checkbox * on the install page. */ Drupal.hideEmailAdministratorCheckbox = function () { // Make sure the secondary box is shown / hidden as necessary on page load. if ($('#edit-update-status-module-1').is(':checked')) { $('.form-item-update-status-module-2').show(); } else { $('.form-item-update-status-module-2').hide(); } // Toggle the display as necessary when the checkbox is clicked. $('#edit-update-status-module-1').change( function () { $('.form-item-update-status-module-2').toggle(); }); }; /** * Internal function to check using Ajax if clean URLs can be enabled on the * settings page. * * This function is not used to verify whether or not clean URLs * are currently enabled. */ Drupal.behaviors.cleanURLsSettingsCheck = { attach: function (context, settings) { // This behavior attaches by ID, so is only valid once on a page. // Also skip if we are on an install page, as Drupal.cleanURLsInstallCheck will handle // the processing. if (!($('#edit-clean-url').length) || $('#edit-clean-url.install').once('clean-url').length) { return; } var url = settings.basePath + 'admin/config/search/clean-urls/check'; $.ajax({ url: location.protocol + '//' + location.host + url, dataType: 'json', success: function () { // Check was successful. Redirect using a "clean URL". This will force the form that allows enabling clean URLs. location = settings.basePath +"admin/config/search/clean-urls"; } }); } }; /** * Internal function to check using Ajax if clean URLs can be enabled on the * install page. * * This function is not used to verify whether or not clean URLs * are currently enabled. */ Drupal.cleanURLsInstallCheck = function () { var url = location.protocol + '//' + location.host + Drupal.settings.basePath + 'admin/config/search/clean-urls/check'; // Submit a synchronous request to avoid database errors associated with // concurrent requests during install. $.ajax({ async: false, url: url, dataType: 'json', success: function () { // Check was successful. $('#edit-clean-url').attr('value', 1); } }); }; /** * When a field is filled out, apply its value to other fields that will likely * use the same value. In the installer this is used to populate the * administrator e-mail address with the same value as the site e-mail address. */ Drupal.behaviors.copyFieldValue = { attach: function (context, settings) { for (var sourceId in settings.copyFieldValue) { $('#' + sourceId, context).once('copy-field-values').bind('blur', function () { // Get the list of target fields. var targetIds = settings.copyFieldValue[sourceId]; // Add the behavior to update target fields on blur of the primary field. for (var delta in targetIds) { var targetField = $('#' + targetIds[delta]); if (targetField.val() == '') { targetField.val(this.value); } } }); } } }; /** * Show/hide custom format sections on the regional settings page. */ Drupal.behaviors.dateTime = { attach: function (context, settings) { for (var fieldName in settings.dateTime) { if (settings.dateTime.hasOwnProperty(fieldName)) { (function (fieldSettings, fieldName) { var source = '#edit-' + fieldName; var suffix = source + '-suffix'; // Attach keyup handler to custom format inputs. $('input' + source, context).once('date-time').keyup(function () { var input = $(this); var url = fieldSettings.lookup + (/\?q=/.test(fieldSettings.lookup) ? '&format=' : '?format=') + encodeURIComponent(input.val()); $.getJSON(url, function (data) { $(suffix).empty().append(' ' + fieldSettings.text + ': <em>' + data + '</em>'); }); }); })(settings.dateTime[fieldName], fieldName); } } } }; /** * Show/hide settings for page caching depending on whether page caching is * enabled or not. */ Drupal.behaviors.pageCache = { attach: function (context, settings) { $('#edit-cache-0', context).change(function () { $('#page-compression-wrapper').hide(); $('#cache-error').hide(); }); $('#edit-cache-1', context).change(function () { $('#page-compression-wrapper').show(); $('#cache-error').hide(); }); $('#edit-cache-2', context).change(function () { $('#page-compression-wrapper').show(); $('#cache-error').show(); }); } }; })(jQuery);
JavaScript
(function ($) { /** * Checks to see if the cron should be automatically run. */ Drupal.behaviors.cronCheck = { attach: function(context, settings) { if (settings.cronCheck || false) { $('body').once('cron-check', function() { // Only execute the cron check if its the right time. if (Math.round(new Date().getTime() / 1000.0) > settings.cronCheck) { $.get(settings.basePath + 'system/run-cron-check'); } }); } } }; })(jQuery);
JavaScript
/** * @file * Attaches behaviors for the Contextual module. */ (function ($) { Drupal.contextualLinks = Drupal.contextualLinks || {}; /** * Attaches outline behavior for regions associated with contextual links. */ Drupal.behaviors.contextualLinks = { attach: function (context) { $('div.contextual-links-wrapper', context).once('contextual-links', function () { var $wrapper = $(this); var $region = $wrapper.closest('.contextual-links-region'); var $links = $wrapper.find('ul.contextual-links'); var $trigger = $('<a class="contextual-links-trigger" href="#" />').text(Drupal.t('Configure')).click( function () { $links.stop(true, true).slideToggle(100); $wrapper.toggleClass('contextual-links-active'); return false; } ); // Attach hover behavior to trigger and ul.contextual-links. $trigger.add($links).hover( function () { $region.addClass('contextual-links-region-active'); }, function () { $region.removeClass('contextual-links-region-active'); } ); // Hide the contextual links when user clicks a link or rolls out of the .contextual-links-region. $region.bind('mouseleave click', Drupal.contextualLinks.mouseleave); // Prepend the trigger. $wrapper.prepend($trigger); }); } }; /** * Disables outline for the region contextual links are associated with. */ Drupal.contextualLinks.mouseleave = function () { $(this) .find('.contextual-links-active').removeClass('contextual-links-active') .find('ul.contextual-links').hide(); }; })(jQuery);
JavaScript
/** * @file * Attaches the behaviors for the Field UI module. */ (function($) { Drupal.behaviors.fieldUIFieldOverview = { attach: function (context, settings) { $('table#field-overview', context).once('field-overview', function () { Drupal.fieldUIFieldOverview.attachUpdateSelects(this, settings); }); } }; Drupal.fieldUIFieldOverview = { /** * Implements dependent select dropdowns on the 'Manage fields' screen. */ attachUpdateSelects: function(table, settings) { var widgetTypes = settings.fieldWidgetTypes; var fields = settings.fields; // Store the default text of widget selects. $('.widget-type-select', table).each(function () { this.initialValue = this.options[0].text; }); // 'Field type' select updates its 'Widget' select. $('.field-type-select', table).each(function () { this.targetSelect = $('.widget-type-select', $(this).closest('tr')); $(this).bind('change keyup', function () { var selectedFieldType = this.options[this.selectedIndex].value; var options = (selectedFieldType in widgetTypes ? widgetTypes[selectedFieldType] : []); this.targetSelect.fieldUIPopulateOptions(options); }); // Trigger change on initial pageload to get the right widget options // when field type comes pre-selected (on failed validation). $(this).trigger('change', false); }); // 'Existing field' select updates its 'Widget' select and 'Label' textfield. $('.field-select', table).each(function () { this.targetSelect = $('.widget-type-select', $(this).closest('tr')); this.targetTextfield = $('.label-textfield', $(this).closest('tr')); this.targetTextfield .data('field_ui_edited', false) .bind('keyup', function (e) { $(this).data('field_ui_edited', $(this).val() != ''); }); $(this).bind('change keyup', function (e, updateText) { var updateText = (typeof updateText == 'undefined' ? true : updateText); var selectedField = this.options[this.selectedIndex].value; var selectedFieldType = (selectedField in fields ? fields[selectedField].type : null); var selectedFieldWidget = (selectedField in fields ? fields[selectedField].widget : null); var options = (selectedFieldType && (selectedFieldType in widgetTypes) ? widgetTypes[selectedFieldType] : []); this.targetSelect.fieldUIPopulateOptions(options, selectedFieldWidget); // Only overwrite the "Label" input if it has not been manually // changed, or if it is empty. if (updateText && !this.targetTextfield.data('field_ui_edited')) { this.targetTextfield.val(selectedField in fields ? fields[selectedField].label : ''); } }); // Trigger change on initial pageload to get the right widget options // and label when field type comes pre-selected (on failed validation). $(this).trigger('change', false); }); } }; /** * Populates options in a select input. */ jQuery.fn.fieldUIPopulateOptions = function (options, selected) { return this.each(function () { var disabled = false; if (options.length == 0) { options = [this.initialValue]; disabled = true; } // If possible, keep the same widget selected when changing field type. // This is based on textual value, since the internal value might be // different (options_buttons vs. node_reference_buttons). var previousSelectedText = this.options[this.selectedIndex].text; var html = ''; jQuery.each(options, function (value, text) { // Figure out which value should be selected. The 'selected' param // takes precedence. var is_selected = ((typeof selected != 'undefined' && value == selected) || (typeof selected == 'undefined' && text == previousSelectedText)); html += '<option value="' + value + '"' + (is_selected ? ' selected="selected"' : '') + '>' + text + '</option>'; }); $(this).html(html).attr('disabled', disabled ? 'disabled' : false); }); }; Drupal.behaviors.fieldUIDisplayOverview = { attach: function (context, settings) { $('table#field-display-overview', context).once('field-display-overview', function() { Drupal.fieldUIOverview.attach(this, settings.fieldUIRowsData, Drupal.fieldUIDisplayOverview); }); } }; Drupal.fieldUIOverview = { /** * Attaches the fieldUIOverview behavior. */ attach: function (table, rowsData, rowHandlers) { var tableDrag = Drupal.tableDrag[table.id]; // Add custom tabledrag callbacks. tableDrag.onDrop = this.onDrop; tableDrag.row.prototype.onSwap = this.onSwap; // Create row handlers. $('tr.draggable', table).each(function () { // Extract server-side data for the row. var row = this; if (row.id in rowsData) { var data = rowsData[row.id]; data.tableDrag = tableDrag; // Create the row handler, make it accessible from the DOM row element. var rowHandler = new rowHandlers[data.rowHandler](row, data); $(row).data('fieldUIRowHandler', rowHandler); } }); }, /** * Event handler to be attached to form inputs triggering a region change. */ onChange: function () { var $trigger = $(this); var row = $trigger.closest('tr').get(0); var rowHandler = $(row).data('fieldUIRowHandler'); var refreshRows = {}; refreshRows[rowHandler.name] = $trigger.get(0); // Handle region change. var region = rowHandler.getRegion(); if (region != rowHandler.region) { // Remove parenting. $('select.field-parent', row).val(''); // Let the row handler deal with the region change. $.extend(refreshRows, rowHandler.regionChange(region)); // Update the row region. rowHandler.region = region; } // Ajax-update the rows. Drupal.fieldUIOverview.AJAXRefreshRows(refreshRows); }, /** * Lets row handlers react when a row is dropped into a new region. */ onDrop: function () { var dragObject = this; var row = dragObject.rowObject.element; var rowHandler = $(row).data('fieldUIRowHandler'); if (rowHandler !== undefined) { var regionRow = $(row).prevAll('tr.region-message').get(0); var region = regionRow.className.replace(/([^ ]+[ ]+)*region-([^ ]+)-message([ ]+[^ ]+)*/, '$2'); if (region != rowHandler.region) { // Let the row handler deal with the region change. refreshRows = rowHandler.regionChange(region); // Update the row region. rowHandler.region = region; // Ajax-update the rows. Drupal.fieldUIOverview.AJAXRefreshRows(refreshRows); } } }, /** * Refreshes placeholder rows in empty regions while a row is being dragged. * * Copied from block.js. * * @param table * The table DOM element. * @param rowObject * The tableDrag rowObject for the row being dragged. */ onSwap: function (draggedRow) { var rowObject = this; $('tr.region-message', rowObject.table).each(function () { // If the dragged row is in this region, but above the message row, swap // it down one space. if ($(this).prev('tr').get(0) == rowObject.group[rowObject.group.length - 1]) { // Prevent a recursion problem when using the keyboard to move rows up. if ((rowObject.method != 'keyboard' || rowObject.direction == 'down')) { rowObject.swap('after', this); } } // This region has become empty. if ($(this).next('tr').is(':not(.draggable)') || $(this).next('tr').length == 0) { $(this).removeClass('region-populated').addClass('region-empty'); } // This region has become populated. else if ($(this).is('.region-empty')) { $(this).removeClass('region-empty').addClass('region-populated'); } }); }, /** * Triggers Ajax refresh of selected rows. * * The 'format type' selects can trigger a series of changes in child rows. * The #ajax behavior is therefore not attached directly to the selects, but * triggered manually through a hidden #ajax 'Refresh' button. * * @param rows * A hash object, whose keys are the names of the rows to refresh (they * will receive the 'ajax-new-content' effect on the server side), and * whose values are the DOM element in the row that should get an Ajax * throbber. */ AJAXRefreshRows: function (rows) { // Separate keys and values. var rowNames = []; var ajaxElements = []; $.each(rows, function (rowName, ajaxElement) { rowNames.push(rowName); ajaxElements.push(ajaxElement); }); if (rowNames.length) { // Add a throbber next each of the ajaxElements. var $throbber = $('<div class="ajax-progress ajax-progress-throbber"><div class="throbber">&nbsp;</div></div>'); $(ajaxElements) .addClass('progress-disabled') .after($throbber); // Fire the Ajax update. $('input[name=refresh_rows]').val(rowNames.join(' ')); $('input#edit-refresh').mousedown(); // Disabled elements do not appear in POST ajax data, so we mark the // elements disabled only after firing the request. $(ajaxElements).attr('disabled', true); } } }; /** * Row handlers for the 'Manage display' screen. */ Drupal.fieldUIDisplayOverview = {}; /** * Constructor for a 'field' row handler. * * This handler is used for both fields and 'extra fields' rows. * * @param row * The row DOM element. * @param data * Additional data to be populated in the constructed object. */ Drupal.fieldUIDisplayOverview.field = function (row, data) { this.row = row; this.name = data.name; this.region = data.region; this.tableDrag = data.tableDrag; // Attach change listener to the 'formatter type' select. this.$formatSelect = $('select.field-formatter-type', row); this.$formatSelect.change(Drupal.fieldUIOverview.onChange); return this; }; Drupal.fieldUIDisplayOverview.field.prototype = { /** * Returns the region corresponding to the current form values of the row. */ getRegion: function () { return (this.$formatSelect.val() == 'hidden') ? 'hidden' : 'visible'; }, /** * Reacts to a row being changed regions. * * This function is called when the row is moved to a different region, as a * result of either : * - a drag-and-drop action (the row's form elements then probably need to be * updated accordingly) * - user input in one of the form elements watched by the * Drupal.fieldUIOverview.onChange change listener. * * @param region * The name of the new region for the row. * @return * A hash object indicating which rows should be Ajax-updated as a result * of the change, in the format expected by * Drupal.displayOverview.AJAXRefreshRows(). */ regionChange: function (region) { // When triggered by a row drag, the 'format' select needs to be adjusted // to the new region. var currentValue = this.$formatSelect.val(); switch (region) { case 'visible': if (currentValue == 'hidden') { // Restore the formatter back to the default formatter. Pseudo-fields do // not have default formatters, we just return to 'visible' for those. var value = (this.defaultFormatter != undefined) ? this.defaultFormatter : 'visible'; } break; default: var value = 'hidden'; break; } if (value != undefined) { this.$formatSelect.val(value); } var refreshRows = {}; refreshRows[this.name] = this.$formatSelect.get(0); return refreshRows; } }; })(jQuery);
JavaScript
/** * @file * Attaches the behaviors for the Overlay child pages. */ (function ($) { /** * Attach the child dialog behavior to new content. */ Drupal.behaviors.overlayChild = { attach: function (context, settings) { // Make sure this behavior is not processed more than once. if (this.processed) { return; } this.processed = true; // If we cannot reach the parent window, break out of the overlay. if (!parent.Drupal || !parent.Drupal.overlay) { window.location = window.location.href.replace(/([?&]?)render=overlay&?/g, '$1').replace(/\?$/, ''); } var settings = settings.overlayChild || {}; // If the entire parent window should be refreshed when the overlay is // closed, pass that information to the parent window. if (settings.refreshPage) { parent.Drupal.overlay.refreshPage = true; } // If a form has been submitted successfully, then the server side script // may have decided to tell the parent window to close the popup dialog. if (settings.closeOverlay) { parent.Drupal.overlay.bindChild(window, true); // Use setTimeout to close the child window from a separate thread, // because the current one is busy processing Drupal behaviors. setTimeout(function () { if (typeof settings.redirect == 'string') { parent.Drupal.overlay.redirect(settings.redirect); } else { parent.Drupal.overlay.close(); } }, 1); return; } // If one of the regions displaying outside the overlay needs to be // reloaded immediately, let the parent window know. if (settings.refreshRegions) { parent.Drupal.overlay.refreshRegions(settings.refreshRegions); } // Ok, now we can tell the parent window we're ready. parent.Drupal.overlay.bindChild(window); // IE8 crashes on certain pages if this isn't called; reason unknown. window.scrollTo(window.scrollX, window.scrollY); // Attach child related behaviors to the iframe document. Drupal.overlayChild.attachBehaviors(context, settings); // There are two links within the message that informs people about the // overlay and how to disable it. Make sure both links are visible when // either one has focus and add a class to the wrapper for styling purposes. $('#overlay-disable-message', context) .focusin(function () { $(this).addClass('overlay-disable-message-focused'); $('a.element-focusable', this).removeClass('element-invisible'); }) .focusout(function () { $(this).removeClass('overlay-disable-message-focused'); $('a.element-focusable', this).addClass('element-invisible'); }); } }; /** * Overlay object for child windows. */ Drupal.overlayChild = Drupal.overlayChild || { behaviors: {} }; Drupal.overlayChild.prototype = {}; /** * Attach child related behaviors to the iframe document. */ Drupal.overlayChild.attachBehaviors = function (context, settings) { $.each(this.behaviors, function () { this(context, settings); }); }; /** * Capture and handle clicks. * * Instead of binding a click event handler to every link we bind one to the * document and handle events that bubble up. This also allows other scripts * to bind their own handlers to links and also to prevent overlay's handling. */ Drupal.overlayChild.behaviors.addClickHandler = function (context, settings) { $(document).bind('click.drupal-overlay mouseup.drupal-overlay', $.proxy(parent.Drupal.overlay, 'eventhandlerOverrideLink')); }; /** * Modify forms depending on their relation to the overlay. * * By default, forms are assumed to keep the flow in the overlay. Thus their * action attribute get a ?render=overlay suffix. */ Drupal.overlayChild.behaviors.parseForms = function (context, settings) { $('form', context).once('overlay', function () { // Obtain the action attribute of the form. var action = $(this).attr('action'); // Keep internal forms in the overlay. if (action == undefined || (action.indexOf('http') != 0 && action.indexOf('https') != 0)) { action += (action.indexOf('?') > -1 ? '&' : '?') + 'render=overlay'; $(this).attr('action', action); } // Submit external forms into a new window. else { $(this).attr('target', '_new'); } }); }; /** * Replace the overlay title with a message while loading another page. */ Drupal.overlayChild.behaviors.loading = function (context, settings) { var $title; var text = Drupal.t('Loading'); var dots = ''; $(document).bind('drupalOverlayBeforeLoad.drupal-overlay.drupal-overlay-child-loading', function () { $title = $('#overlay-title').text(text); var id = setInterval(function () { dots = (dots.length > 10) ? '' : dots + '.'; $title.text(text + dots); }, 500); }); }; /** * Switch active tab immediately. */ Drupal.overlayChild.behaviors.tabs = function (context, settings) { var $tabsLinks = $('#overlay-tabs > li > a'); $('#overlay-tabs > li > a').bind('click.drupal-overlay', function () { var active_tab = Drupal.t('(active tab)'); $tabsLinks.parent().siblings().removeClass('active').find('element-invisible:contains(' + active_tab + ')').appendTo(this); $(this).parent().addClass('active'); }); }; /** * If the shortcut add/delete button exists, move it to the overlay titlebar. */ Drupal.overlayChild.behaviors.shortcutAddLink = function (context, settings) { // Remove any existing shortcut button markup from the titlebar. $('#overlay-titlebar').find('.add-or-remove-shortcuts').remove(); // If the shortcut add/delete button exists, move it to the titlebar. var $addToShortcuts = $('.add-or-remove-shortcuts'); if ($addToShortcuts.length) { $addToShortcuts.insertAfter('#overlay-title'); } $(document).bind('drupalOverlayBeforeLoad.drupal-overlay.drupal-overlay-child-loading', function () { $('#overlay-titlebar').find('.add-or-remove-shortcuts').remove(); }); }; /** * Use displacement from parent window. */ Drupal.overlayChild.behaviors.alterTableHeaderOffset = function (context, settings) { if (Drupal.settings.tableHeaderOffset) { Drupal.overlayChild.prevTableHeaderOffset = Drupal.settings.tableHeaderOffset; } Drupal.settings.tableHeaderOffset = 'Drupal.overlayChild.tableHeaderOffset'; }; /** * Callback for Drupal.settings.tableHeaderOffset. */ Drupal.overlayChild.tableHeaderOffset = function () { var topOffset = Drupal.overlayChild.prevTableHeaderOffset ? eval(Drupal.overlayChild.prevTableHeaderOffset + '()') : 0; return topOffset + parseInt($(document.body).css('marginTop')); }; })(jQuery);
JavaScript
/** * @file * Attaches the behaviors for the Overlay parent pages. */ (function ($) { /** * Open the overlay, or load content into it, when an admin link is clicked. */ Drupal.behaviors.overlayParent = { attach: function (context, settings) { if (Drupal.overlay.isOpen) { Drupal.overlay.makeDocumentUntabbable(context); } if (this.processed) { return; } this.processed = true; $(window) // When the hash (URL fragment) changes, open the overlay if needed. .bind('hashchange.drupal-overlay', $.proxy(Drupal.overlay, 'eventhandlerOperateByURLFragment')) // Trigger the hashchange handler once, after the page is loaded, so that // permalinks open the overlay. .triggerHandler('hashchange.drupal-overlay'); $(document) // Instead of binding a click event handler to every link we bind one to // the document and only handle events that bubble up. This allows other // scripts to bind their own handlers to links and also to prevent // overlay's handling. .bind('click.drupal-overlay mouseup.drupal-overlay', $.proxy(Drupal.overlay, 'eventhandlerOverrideLink')); } }; /** * Overlay object for parent windows. * * Events * Overlay triggers a number of events that can be used by other scripts. * - drupalOverlayOpen: This event is triggered when the overlay is opened. * - drupalOverlayBeforeClose: This event is triggered when the overlay attempts * to close. If an event handler returns false, the close will be prevented. * - drupalOverlayClose: This event is triggered when the overlay is closed. * - drupalOverlayBeforeLoad: This event is triggered right before a new URL * is loaded into the overlay. * - drupalOverlayReady: This event is triggered when the DOM of the overlay * child document is fully loaded. * - drupalOverlayLoad: This event is triggered when the overlay is finished * loading. * - drupalOverlayResize: This event is triggered when the overlay is being * resized to match the parent window. */ Drupal.overlay = Drupal.overlay || { isOpen: false, isOpening: false, isClosing: false, isLoading: false }; Drupal.overlay.prototype = {}; /** * Open the overlay. * * @param url * The URL of the page to open in the overlay. * * @return * TRUE if the overlay was opened, FALSE otherwise. */ Drupal.overlay.open = function (url) { // Just one overlay is allowed. if (this.isOpen || this.isOpening) { return this.load(url); } this.isOpening = true; // Store the original document title. this.originalTitle = document.title; // Create the dialog and related DOM elements. this.create(); this.isOpening = false; this.isOpen = true; $(document.documentElement).addClass('overlay-open'); this.makeDocumentUntabbable(); // Allow other scripts to respond to this event. $(document).trigger('drupalOverlayOpen'); return this.load(url); }; /** * Create the underlying markup and behaviors for the overlay. */ Drupal.overlay.create = function () { this.$container = $(Drupal.theme('overlayContainer')) .appendTo(document.body); // Overlay uses transparent iframes that cover the full parent window. // When the overlay is open the scrollbar of the parent window is hidden. // Because some browsers show a white iframe background for a short moment // while loading a page into an iframe, overlay uses two iframes. By loading // the page in a hidden (inactive) iframe the user doesn't see the white // background. When the page is loaded the active and inactive iframes // are switched. this.activeFrame = this.$iframeA = $(Drupal.theme('overlayElement')) .appendTo(this.$container); this.inactiveFrame = this.$iframeB = $(Drupal.theme('overlayElement')) .appendTo(this.$container); this.$iframeA.bind('load.drupal-overlay', { self: this.$iframeA[0], sibling: this.$iframeB }, $.proxy(this, 'loadChild')); this.$iframeB.bind('load.drupal-overlay', { self: this.$iframeB[0], sibling: this.$iframeA }, $.proxy(this, 'loadChild')); // Add a second class "drupal-overlay-open" to indicate these event handlers // should only be bound when the overlay is open. var eventClass = '.drupal-overlay.drupal-overlay-open'; $(window) .bind('resize' + eventClass, $.proxy(this, 'eventhandlerOuterResize')); $(document) .bind('drupalOverlayLoad' + eventClass, $.proxy(this, 'eventhandlerOuterResize')) .bind('drupalOverlayReady' + eventClass + ' drupalOverlayClose' + eventClass, $.proxy(this, 'eventhandlerSyncURLFragment')) .bind('drupalOverlayClose' + eventClass, $.proxy(this, 'eventhandlerRefreshPage')) .bind('drupalOverlayBeforeClose' + eventClass + ' drupalOverlayBeforeLoad' + eventClass + ' drupalOverlayResize' + eventClass, $.proxy(this, 'eventhandlerDispatchEvent')); if ($('.overlay-displace-top, .overlay-displace-bottom').length) { $(document) .bind('drupalOverlayResize' + eventClass, $.proxy(this, 'eventhandlerAlterDisplacedElements')) .bind('drupalOverlayClose' + eventClass, $.proxy(this, 'eventhandlerRestoreDisplacedElements')); } }; /** * Load the given URL into the overlay iframe. * * Use this method to change the URL being loaded in the overlay if it is * already open. * * @return * TRUE if URL is loaded into the overlay, FALSE otherwise. */ Drupal.overlay.load = function (url) { if (!this.isOpen) { return false; } // Allow other scripts to respond to this event. $(document).trigger('drupalOverlayBeforeLoad'); $(document.documentElement).addClass('overlay-loading'); // The contentDocument property is not supported in IE until IE8. var iframeDocument = this.inactiveFrame[0].contentDocument || this.inactiveFrame[0].contentWindow.document; // location.replace doesn't create a history entry. location.href does. // In this case, we want location.replace, as we're creating the history // entry using URL fragments. iframeDocument.location.replace(url); return true; }; /** * Close the overlay and remove markup related to it from the document. * * @return * TRUE if the overlay was closed, FALSE otherwise. */ Drupal.overlay.close = function () { // Prevent double execution when close is requested more than once. if (!this.isOpen || this.isClosing) { return false; } // Allow other scripts to respond to this event. var event = $.Event('drupalOverlayBeforeClose'); $(document).trigger(event); // If a handler returned false, the close will be prevented. if (event.isDefaultPrevented()) { return false; } this.isClosing = true; this.isOpen = false; $(document.documentElement).removeClass('overlay-open'); // Restore the original document title. document.title = this.originalTitle; this.makeDocumentTabbable(); // Allow other scripts to respond to this event. $(document).trigger('drupalOverlayClose'); // When the iframe is still loading don't destroy it immediately but after // the content is loaded (see Drupal.overlay.loadChild). if (!this.isLoading) { this.destroy(); this.isClosing = false; } return true; }; /** * Destroy the overlay. */ Drupal.overlay.destroy = function () { $([document, window]).unbind('.drupal-overlay-open'); this.$container.remove(); this.$container = null; this.$iframeA = null; this.$iframeB = null; this.iframeWindow = null; }; /** * Redirect the overlay parent window to the given URL. * * @param url * Can be an absolute URL or a relative link to the domain root. */ Drupal.overlay.redirect = function (url) { // Create a native Link object, so we can use its object methods. var link = $(url.link(url)).get(0); // If the link is already open, force the hashchange event to simulate reload. if (window.location.href == link.href) { $(window).triggerHandler('hashchange.drupal-overlay'); } window.location.href = link.href; return true; }; /** * Bind the child window. * * Note that this function is fired earlier than Drupal.overlay.loadChild. */ Drupal.overlay.bindChild = function (iframeWindow, isClosing) { this.iframeWindow = iframeWindow; // We are done if the child window is closing. if (isClosing || this.isClosing || !this.isOpen) { return; } // Allow other scripts to respond to this event. $(document).trigger('drupalOverlayReady'); }; /** * Event handler: load event handler for the overlay iframe. * * @param event * Event being triggered, with the following restrictions: * - event.type: load * - event.currentTarget: iframe */ Drupal.overlay.loadChild = function (event) { var iframe = event.data.self; var iframeDocument = iframe.contentDocument || iframe.contentWindow.document; var iframeWindow = iframeDocument.defaultView || iframeDocument.parentWindow; if (iframeWindow.location == 'about:blank') { return; } this.isLoading = false; $(document.documentElement).removeClass('overlay-loading'); event.data.sibling.removeClass('overlay-active').attr({ 'tabindex': -1 }); // Only continue when overlay is still open and not closing. if (this.isOpen && !this.isClosing) { // And child document is an actual overlayChild. if (iframeWindow.Drupal && iframeWindow.Drupal.overlayChild) { // Replace the document title with title of iframe. document.title = iframeWindow.document.title; this.activeFrame = $(iframe) .addClass('overlay-active') // Add a title attribute to the iframe for accessibility. .attr('title', Drupal.t('@title dialog', { '@title': iframeWindow.jQuery('#overlay-title').text() })).removeAttr('tabindex'); this.inactiveFrame = event.data.sibling; // Load an empty document into the inactive iframe. (this.inactiveFrame[0].contentDocument || this.inactiveFrame[0].contentWindow.document).location.replace('about:blank'); // Move the focus to just before the "skip to main content" link inside // the overlay. this.activeFrame.focus(); var skipLink = iframeWindow.jQuery('a:first'); Drupal.overlay.setFocusBefore(skipLink, iframeWindow.document); // Allow other scripts to respond to this event. $(document).trigger('drupalOverlayLoad'); } else { window.location = iframeWindow.location.href.replace(/([?&]?)render=overlay&?/g, '$1').replace(/\?$/, ''); } } else { this.destroy(); } }; /** * Creates a placeholder element to receive document focus. * * Setting the document focus to a link will make it visible, even if it's a * "skip to main content" link that should normally be visible only when the * user tabs to it. This function can be used to set the document focus to * just before such an invisible link. * * @param $element * The jQuery element that should receive focus on the next tab press. * @param document * The iframe window element to which the placeholder should be added. The * placeholder element has to be created inside the same iframe as the element * it precedes, to keep IE happy. (http://bugs.jquery.com/ticket/4059) */ Drupal.overlay.setFocusBefore = function ($element, document) { // Create an anchor inside the placeholder document. var placeholder = document.createElement('a'); var $placeholder = $(placeholder).addClass('element-invisible').attr('href', '#'); // Put the placeholder where it belongs, and set the document focus to it. $placeholder.insertBefore($element); $placeholder.focus(); // Make the placeholder disappear as soon as it loses focus, so that it // doesn't appear in the tab order again. $placeholder.one('blur', function () { $(this).remove(); }); }; /** * Check if the given link is in the administrative section of the site. * * @param url * The URL to be tested. * * @return boolean * TRUE if the URL represents an administrative link, FALSE otherwise. */ Drupal.overlay.isAdminLink = function (url) { if (Drupal.overlay.isExternalLink(url)) { return false; } var path = this.getPath(url); // Turn the list of administrative paths into a regular expression. if (!this.adminPathRegExp) { var prefix = ''; if (Drupal.settings.overlay.pathPrefixes.length) { // Allow path prefixes used for language negatiation followed by slash, // and the empty string. prefix = '(' + Drupal.settings.overlay.pathPrefixes.join('/|') + '/|)'; } var adminPaths = '^' + prefix + '(' + Drupal.settings.overlay.paths.admin.replace(/\s+/g, '|') + ')$'; var nonAdminPaths = '^' + prefix + '(' + Drupal.settings.overlay.paths.non_admin.replace(/\s+/g, '|') + ')$'; adminPaths = adminPaths.replace(/\*/g, '.*'); nonAdminPaths = nonAdminPaths.replace(/\*/g, '.*'); this.adminPathRegExp = new RegExp(adminPaths); this.nonAdminPathRegExp = new RegExp(nonAdminPaths); } return this.adminPathRegExp.exec(path) && !this.nonAdminPathRegExp.exec(path); }; /** * Determine whether a link is external to the site. * * @param url * The URL to be tested. * * @return boolean * TRUE if the URL is external to the site, FALSE otherwise. */ Drupal.overlay.isExternalLink = function (url) { var re = RegExp('^((f|ht)tps?:)?//(?!' + window.location.host + ')'); return re.test(url); }; /** * Event handler: resizes overlay according to the size of the parent window. * * @param event * Event being triggered, with the following restrictions: * - event.type: any * - event.currentTarget: any */ Drupal.overlay.eventhandlerOuterResize = function (event) { // Proceed only if the overlay still exists. if (!(this.isOpen || this.isOpening) || this.isClosing || !this.iframeWindow) { return; } // IE6 uses position:absolute instead of position:fixed. if (typeof document.body.style.maxHeight != 'string') { this.activeFrame.height($(window).height()); } // Allow other scripts to respond to this event. $(document).trigger('drupalOverlayResize'); }; /** * Event handler: resizes displaced elements so they won't overlap the scrollbar * of overlay's iframe. * * @param event * Event being triggered, with the following restrictions: * - event.type: any * - event.currentTarget: any */ Drupal.overlay.eventhandlerAlterDisplacedElements = function (event) { // Proceed only if the overlay still exists. if (!(this.isOpen || this.isOpening) || this.isClosing || !this.iframeWindow) { return; } $(this.iframeWindow.document.body).css({ marginTop: Drupal.overlay.getDisplacement('top'), marginBottom: Drupal.overlay.getDisplacement('bottom') }) // IE7 isn't reflowing the document immediately. // @todo This might be fixed in a cleaner way. .addClass('overlay-trigger-reflow').removeClass('overlay-trigger-reflow'); var documentHeight = this.iframeWindow.document.body.clientHeight; var documentWidth = this.iframeWindow.document.body.clientWidth; // IE6 doesn't support maxWidth, use width instead. var maxWidthName = (typeof document.body.style.maxWidth == 'string') ? 'maxWidth' : 'width'; if (Drupal.overlay.leftSidedScrollbarOffset === undefined && $(document.documentElement).attr('dir') === 'rtl') { // We can't use element.clientLeft to detect whether scrollbars are placed // on the left side of the element when direction is set to "rtl" as most // browsers dont't support it correctly. // http://www.gtalbot.org/BugzillaSection/DocumentAllDHTMLproperties.html // There seems to be absolutely no way to detect whether the scrollbar // is on the left side in Opera; always expect scrollbar to be on the left. if ($.browser.opera) { Drupal.overlay.leftSidedScrollbarOffset = document.documentElement.clientWidth - this.iframeWindow.document.documentElement.clientWidth + this.iframeWindow.document.documentElement.clientLeft; } else if (this.iframeWindow.document.documentElement.clientLeft) { Drupal.overlay.leftSidedScrollbarOffset = this.iframeWindow.document.documentElement.clientLeft; } else { var el1 = $('<div style="direction: rtl; overflow: scroll;"></div>').appendTo(document.body); var el2 = $('<div></div>').appendTo(el1); Drupal.overlay.leftSidedScrollbarOffset = parseInt(el2[0].offsetLeft - el1[0].offsetLeft); el1.remove(); } } // Consider any element that should be visible above the overlay (such as // a toolbar). $('.overlay-displace-top, .overlay-displace-bottom').each(function () { var data = $(this).data(); var maxWidth = documentWidth; // In IE, Shadow filter makes element to overlap the scrollbar with 1px. if (this.filters && this.filters.length && this.filters.item('DXImageTransform.Microsoft.Shadow')) { maxWidth -= 1; } if (Drupal.overlay.leftSidedScrollbarOffset) { $(this).css('left', Drupal.overlay.leftSidedScrollbarOffset); } // Prevent displaced elements overlapping window's scrollbar. var currentMaxWidth = parseInt($(this).css(maxWidthName)); if ((data.drupalOverlay && data.drupalOverlay.maxWidth) || isNaN(currentMaxWidth) || currentMaxWidth > maxWidth || currentMaxWidth <= 0) { $(this).css(maxWidthName, maxWidth); (data.drupalOverlay = data.drupalOverlay || {}).maxWidth = true; } // Use a more rigorous approach if the displaced element still overlaps // window's scrollbar; clip the element on the right. var offset = $(this).offset(); var offsetRight = offset.left + $(this).outerWidth(); if ((data.drupalOverlay && data.drupalOverlay.clip) || offsetRight > maxWidth) { if (Drupal.overlay.leftSidedScrollbarOffset) { $(this).css('clip', 'rect(auto, auto, ' + (documentHeight - offset.top) + 'px, ' + (Drupal.overlay.leftSidedScrollbarOffset + 2) + 'px)'); } else { $(this).css('clip', 'rect(auto, ' + (maxWidth - offset.left) + 'px, ' + (documentHeight - offset.top) + 'px, auto)'); } (data.drupalOverlay = data.drupalOverlay || {}).clip = true; } }); }; /** * Event handler: restores size of displaced elements as they were before * overlay was opened. * * @param event * Event being triggered, with the following restrictions: * - event.type: any * - event.currentTarget: any */ Drupal.overlay.eventhandlerRestoreDisplacedElements = function (event) { var $displacedElements = $('.overlay-displace-top, .overlay-displace-bottom'); try { $displacedElements.css({ maxWidth: '', clip: '' }); } // IE bug that doesn't allow unsetting style.clip (http://dev.jquery.com/ticket/6512). catch (err) { $displacedElements.attr('style', function (index, attr) { return attr.replace(/clip\s*:\s*rect\([^)]+\);?/i, ''); }); } }; /** * Event handler: overrides href of administrative links to be opened in * the overlay. * * This click event handler should be bound to any document (for example the * overlay iframe) of which you want links to open in the overlay. * * @param event * Event being triggered, with the following restrictions: * - event.type: click, mouseup * - event.currentTarget: document * * @see Drupal.overlayChild.behaviors.addClickHandler */ Drupal.overlay.eventhandlerOverrideLink = function (event) { // In some browsers the click event isn't fired for right-clicks. Use the // mouseup event for right-clicks and the click event for everything else. if ((event.type == 'click' && event.button == 2) || (event.type == 'mouseup' && event.button != 2)) { return; } var $target = $(event.target); // Only continue if clicked target (or one of its parents) is a link. if (!$target.is('a')) { $target = $target.closest('a'); if (!$target.length) { return; } } // Never open links in the overlay that contain the overlay-exclude class. if ($target.hasClass('overlay-exclude')) { return; } // Close the overlay when the link contains the overlay-close class. if ($target.hasClass('overlay-close')) { // Clearing the overlay URL fragment will close the overlay. $.bbq.removeState('overlay'); return; } var target = $target[0]; var href = target.href; // Only handle links that have an href attribute and use the HTTP(S) protocol. if (href != undefined && href != '' && target.protocol.match(/^https?\:/)) { var anchor = href.replace(target.ownerDocument.location.href, ''); // Skip anchor links. if (anchor.length == 0 || anchor.charAt(0) == '#') { return; } // Open admin links in the overlay. else if (this.isAdminLink(href)) { // If the link contains the overlay-restore class and the overlay-context // state is set, also update the parent window's location. var parentLocation = ($target.hasClass('overlay-restore') && typeof $.bbq.getState('overlay-context') == 'string') ? Drupal.settings.basePath + $.bbq.getState('overlay-context') : null; href = this.fragmentizeLink($target.get(0), parentLocation); // Only override default behavior when left-clicking and user is not // pressing the ALT, CTRL, META (Command key on the Macintosh keyboard) // or SHIFT key. if (event.button == 0 && !event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey) { // Redirect to a fragmentized href. This will trigger a hashchange event. this.redirect(href); // Prevent default action and further propagation of the event. return false; } // Otherwise alter clicked link's href. This is being picked up by // the default action handler. else { $target // Restore link's href attribute on blur or next click. .one('blur mousedown', { target: target, href: target.href }, function (event) { $(event.data.target).attr('href', event.data.href); }) .attr('href', href); } } // Non-admin links should close the overlay and open in the main window, // which is the default action for a link. We only need to handle them // if the overlay is open and the clicked link is inside the overlay iframe. else if (this.isOpen && target.ownerDocument === this.iframeWindow.document) { // Open external links in the immediate parent of the frame, unless the // link already has a different target. if (target.hostname != window.location.hostname) { if (!$target.attr('target')) { $target.attr('target', '_parent'); } } else { // Add the overlay-context state to the link, so "overlay-restore" links // can restore the context. if ($target[0].hash) { // Leave links with an existing fragment alone. Adding an extra // parameter to a link like "node/1#section-1" breaks the link. } else { // For links with no existing fragment, add the overlay context. $target.attr('href', $.param.fragment(href, { 'overlay-context': this.getPath(window.location) + window.location.search })); } // When the link has a destination query parameter and that destination // is an admin link we need to fragmentize it. This will make it reopen // in the overlay. var params = $.deparam.querystring(href); if (params.destination && this.isAdminLink(params.destination)) { var fragmentizedDestination = $.param.fragment(this.getPath(window.location), { overlay: params.destination }); $target.attr('href', $.param.querystring(href, { destination: fragmentizedDestination })); } // Make the link open in the immediate parent of the frame. $target.attr('target', '_parent'); } } } }; /** * Event handler: opens or closes the overlay based on the current URL fragment. * * @param event * Event being triggered, with the following restrictions: * - event.type: hashchange * - event.currentTarget: document */ Drupal.overlay.eventhandlerOperateByURLFragment = function (event) { // If we changed the hash to reflect an internal redirect in the overlay, // its location has already been changed, so don't do anything. if ($.data(window.location, window.location.href) === 'redirect') { $.data(window.location, window.location.href, null); return; } // Get the overlay URL from the current URL fragment. var state = $.bbq.getState('overlay'); if (state) { // Append render variable, so the server side can choose the right // rendering and add child frame code to the page if needed. var url = $.param.querystring(Drupal.settings.basePath + state, { render: 'overlay' }); this.open(url); this.resetActiveClass(this.getPath(Drupal.settings.basePath + state)); } // If there is no overlay URL in the fragment and the overlay is (still) // open, close the overlay. else if (this.isOpen && !this.isClosing) { this.close(); this.resetActiveClass(this.getPath(window.location)); } }; /** * Event handler: makes sure the internal overlay URL is reflected in the parent * URL fragment. * * Normally the parent URL fragment determines the overlay location. However, if * the overlay redirects internally, the parent doesn't get informed, and the * parent URL fragment will be out of date. This is a sanity check to make * sure we're in the right place. * * The parent URL fragment is also not updated automatically when overlay's * open, close or load functions are used directly (instead of through * eventhandlerOperateByURLFragment). * * @param event * Event being triggered, with the following restrictions: * - event.type: drupalOverlayReady, drupalOverlayClose * - event.currentTarget: document */ Drupal.overlay.eventhandlerSyncURLFragment = function (event) { if (this.isOpen) { var expected = $.bbq.getState('overlay'); // This is just a sanity check, so we're comparing paths, not query strings. if (this.getPath(Drupal.settings.basePath + expected) != this.getPath(this.iframeWindow.document.location)) { // There may have been a redirect inside the child overlay window that the // parent wasn't aware of. Update the parent URL fragment appropriately. var newLocation = Drupal.overlay.fragmentizeLink(this.iframeWindow.document.location); // Set a 'redirect' flag on the new location so the hashchange event handler // knows not to change the overlay's content. $.data(window.location, newLocation, 'redirect'); // Use location.replace() so we don't create an extra history entry. window.location.replace(newLocation); } } else { $.bbq.removeState('overlay'); } }; /** * Event handler: if the child window suggested that the parent refresh on * close, force a page refresh. * * @param event * Event being triggered, with the following restrictions: * - event.type: drupalOverlayClose * - event.currentTarget: document */ Drupal.overlay.eventhandlerRefreshPage = function (event) { if (Drupal.overlay.refreshPage) { window.location.reload(true); } }; /** * Event handler: dispatches events to the overlay document. * * @param event * Event being triggered, with the following restrictions: * - event.type: any * - event.currentTarget: any */ Drupal.overlay.eventhandlerDispatchEvent = function (event) { if (this.iframeWindow && this.iframeWindow.document) { this.iframeWindow.jQuery(this.iframeWindow.document).trigger(event); } }; /** * Make a regular admin link into a URL that will trigger the overlay to open. * * @param link * A JavaScript Link object (i.e. an <a> element). * @param parentLocation * (optional) URL to override the parent window's location with. * * @return * A URL that will trigger the overlay (in the form * /node/1#overlay=admin/config). */ Drupal.overlay.fragmentizeLink = function (link, parentLocation) { // Don't operate on links that are already overlay-ready. var params = $.deparam.fragment(link.href); if (params.overlay) { return link.href; } // Determine the link's original destination. Set ignorePathFromQueryString to // true to prevent transforming this link into a clean URL while clean URLs // may be disabled. var path = this.getPath(link, true); // Preserve existing query and fragment parameters in the URL, except for // "render=overlay" which is re-added in Drupal.overlay.eventhandlerOperateByURLFragment. var destination = path + link.search.replace(/&?render=overlay/, '').replace(/\?$/, '') + link.hash; // Assemble and return the overlay-ready link. return $.param.fragment(parentLocation || window.location.href, { overlay: destination }); }; /** * Refresh any regions of the page that are displayed outside the overlay. * * @param data * An array of objects with information on the page regions to be refreshed. * For each object, the key is a CSS class identifying the region to be * refreshed, and the value represents the section of the Drupal $page array * corresponding to this region. */ Drupal.overlay.refreshRegions = function (data) { $.each(data, function () { var region_info = this; $.each(region_info, function (regionClass) { var regionName = region_info[regionClass]; var regionSelector = '.' + regionClass; // Allow special behaviors to detach. Drupal.detachBehaviors($(regionSelector)); $.get(Drupal.settings.basePath + Drupal.settings.overlay.ajaxCallback + '/' + regionName, function (newElement) { $(regionSelector).replaceWith($(newElement)); Drupal.attachBehaviors($(regionSelector), Drupal.settings); }); }); }); }; /** * Reset the active class on links in displaced elements according to * given path. * * @param activePath * Path to match links against. */ Drupal.overlay.resetActiveClass = function(activePath) { var self = this; var windowDomain = window.location.protocol + window.location.hostname; $('.overlay-displace-top, .overlay-displace-bottom') .find('a[href]') // Remove active class from all links in displaced elements. .removeClass('active') // Add active class to links that match activePath. .each(function () { var linkDomain = this.protocol + this.hostname; var linkPath = self.getPath(this); // A link matches if it is part of the active trail of activePath, except // for frontpage links. if (linkDomain == windowDomain && (activePath + '/').indexOf(linkPath + '/') === 0 && (linkPath !== '' || activePath === '')) { $(this).addClass('active'); } }); }; /** * Helper function to get the (corrected) Drupal path of a link. * * @param link * Link object or string to get the Drupal path from. * @param ignorePathFromQueryString * Boolean whether to ignore path from query string if path appears empty. * * @return * The Drupal path. */ Drupal.overlay.getPath = function (link, ignorePathFromQueryString) { if (typeof link == 'string') { // Create a native Link object, so we can use its object methods. link = $(link.link(link)).get(0); } var path = link.pathname; // Ensure a leading slash on the path, omitted in some browsers. if (path.charAt(0) != '/') { path = '/' + path; } path = path.replace(new RegExp(Drupal.settings.basePath + '(?:index.php)?'), ''); if (path == '' && !ignorePathFromQueryString) { // If the path appears empty, it might mean the path is represented in the // query string (clean URLs are not used). var match = new RegExp('([?&])q=(.+)([&#]|$)').exec(link.search); if (match && match.length == 4) { path = match[2]; } } return path; }; /** * Get the total displacement of given region. * * @param region * Region name. Either "top" or "bottom". * * @return * The total displacement of given region in pixels. */ Drupal.overlay.getDisplacement = function (region) { var displacement = 0; var lastDisplaced = $('.overlay-displace-' + region + ':last'); if (lastDisplaced.length) { displacement = lastDisplaced.offset().top + lastDisplaced.outerHeight(); // In modern browsers (including IE9), when box-shadow is defined, use the // normal height. var cssBoxShadowValue = lastDisplaced.css('box-shadow'); var boxShadow = (typeof cssBoxShadowValue !== 'undefined' && cssBoxShadowValue !== 'none'); // In IE8 and below, we use the shadow filter to apply box-shadow styles to // the toolbar. It adds some extra height that we need to remove. if (!boxShadow && /DXImageTransform\.Microsoft\.Shadow/.test(lastDisplaced.css('filter'))) { displacement -= lastDisplaced[0].filters.item('DXImageTransform.Microsoft.Shadow').strength; displacement = Math.max(0, displacement); } } return displacement; }; /** * Makes elements outside the overlay unreachable via the tab key. * * @param context * The part of the DOM that should have its tabindexes changed. Defaults to * the entire page. */ Drupal.overlay.makeDocumentUntabbable = function (context) { // Manipulating tabindexes for the entire document is unacceptably slow in IE6 // and IE7, so in those browsers, the underlying page will still be reachable // via the tab key. However, we still make the links within the Disable // message unreachable, because the same message also exists within the // child document. The duplicate copy in the underlying document is only for // assisting screen-reader users navigating the document with reading commands // that follow markup order rather than tab order. if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 8) { $('#overlay-disable-message a', context).attr('tabindex', -1); return; } context = context || document.body; var $overlay, $tabbable, $hasTabindex; // Determine which elements on the page already have a tabindex. $hasTabindex = $('[tabindex] :not(.overlay-element)', context); // Record the tabindex for each element, so we can restore it later. $hasTabindex.each(Drupal.overlay._recordTabindex); // Add the tabbable elements from the current context to any that we might // have previously recorded. Drupal.overlay._hasTabindex = $hasTabindex.add(Drupal.overlay._hasTabindex); // Set tabindex to -1 on everything outside the overlay and toolbars, so that // the underlying page is unreachable. // By default, browsers make a, area, button, input, object, select, textarea, // and iframe elements reachable via the tab key. $tabbable = $('a, area, button, input, object, select, textarea, iframe'); // If another element (like a div) has a tabindex, it's also tabbable. $tabbable = $tabbable.add($hasTabindex); // Leave links inside the overlay and toolbars alone. $overlay = $('.overlay-element, #overlay-container, .overlay-displace-top, .overlay-displace-bottom').find('*'); $tabbable = $tabbable.not($overlay); // We now have a list of everything in the underlying document that could // possibly be reachable via the tab key. Make it all unreachable. $tabbable.attr('tabindex', -1); }; /** * Restores the original tabindex value of a group of elements. * * @param context * The part of the DOM that should have its tabindexes restored. Defaults to * the entire page. */ Drupal.overlay.makeDocumentTabbable = function (context) { // Manipulating tabindexes is unacceptably slow in IE6 and IE7. In those // browsers, the underlying page was never made unreachable via tab, so // there is no work to be done here. if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 8) { return; } var $needsTabindex; context = context || document.body; // Make the underlying document tabbable again by removing all existing // tabindex attributes. var $tabindex = $('[tabindex]', context); if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 8) { // removeAttr('tabindex') is broken in IE6-7, but the DOM function // removeAttribute works. var i; var length = $tabindex.length; for (i = 0; i < length; i++) { $tabindex[i].removeAttribute('tabIndex'); } } else { $tabindex.removeAttr('tabindex'); } // Restore the tabindex attributes that existed before the overlay was opened. $needsTabindex = $(Drupal.overlay._hasTabindex, context); $needsTabindex.each(Drupal.overlay._restoreTabindex); Drupal.overlay._hasTabindex = Drupal.overlay._hasTabindex.not($needsTabindex); }; /** * Record the tabindex for an element, using $.data. * * Meant to be used as a jQuery.fn.each callback. */ Drupal.overlay._recordTabindex = function () { var $element = $(this); var tabindex = $(this).attr('tabindex'); $element.data('drupalOverlayOriginalTabIndex', tabindex); }; /** * Restore an element's original tabindex. * * Meant to be used as a jQuery.fn.each callback. */ Drupal.overlay._restoreTabindex = function () { var $element = $(this); var tabindex = $element.data('drupalOverlayOriginalTabIndex'); $element.attr('tabindex', tabindex); }; /** * Theme function to create the overlay iframe element. */ Drupal.theme.prototype.overlayContainer = function () { return '<div id="overlay-container"><div class="overlay-modal-background"></div></div>'; }; /** * Theme function to create an overlay iframe element. */ Drupal.theme.prototype.overlayElement = function (url) { return '<iframe class="overlay-element" frameborder="0" scrolling="auto" allowtransparency="true"></iframe>'; }; })(jQuery);
JavaScript
(function ($) { /** * Add functionality to the profile drag and drop table. * * This behavior is dependent on the tableDrag behavior, since it uses the * objects initialized in that behavior to update the row. It shows and hides * a warning message when removing the last field from a profile category. */ Drupal.behaviors.profileDrag = { attach: function (context, settings) { var table = $('#profile-fields'); var tableDrag = Drupal.tableDrag['profile-fields']; // Get the profile tableDrag object. // Add a handler for when a row is swapped, update empty categories. tableDrag.row.prototype.onSwap = function (swappedRow) { var rowObject = this; $('tr.category-message', table).each(function () { // If the dragged row is in this category, but above the message row, swap it down one space. if ($(this).prev('tr').get(0) == rowObject.element) { // Prevent a recursion problem when using the keyboard to move rows up. if ((rowObject.method != 'keyboard' || rowObject.direction == 'down')) { rowObject.swap('after', this); } } // This category has become empty if ($(this).next('tr').is(':not(.draggable)') || $(this).next('tr').length == 0) { $(this).removeClass('category-populated').addClass('category-empty'); } // This category has become populated. else if ($(this).is('.category-empty')) { $(this).removeClass('category-empty').addClass('category-populated'); } }); }; // Add a handler so when a row is dropped, update fields dropped into new categories. tableDrag.onDrop = function () { dragObject = this; if ($(dragObject.rowObject.element).prev('tr').is('.category-message')) { var categoryRow = $(dragObject.rowObject.element).prev('tr').get(0); var categoryNum = categoryRow.className.replace(/([^ ]+[ ]+)*category-([^ ]+)-message([ ]+[^ ]+)*/, '$2'); var categoryField = $('select.profile-category', dragObject.rowObject.element); var weightField = $('select.profile-weight', dragObject.rowObject.element); var oldcategoryNum = weightField[0].className.replace(/([^ ]+[ ]+)*profile-weight-([^ ]+)([ ]+[^ ]+)*/, '$2'); if (!categoryField.is('.profile-category-' + categoryNum)) { categoryField.removeClass('profile-category-' + oldcategoryNum).addClass('profile-category-' + categoryNum); weightField.removeClass('profile-weight-' + oldcategoryNum).addClass('profile-weight-' + categoryNum); categoryField.val(categoryField[0].options[categoryNum].value); } } }; } }; })(jQuery);
JavaScript
(function ($) { Drupal.behaviors.menuFieldsetSummaries = { attach: function (context) { $('fieldset.menu-link-form', context).drupalSetSummary(function (context) { if ($('.form-item-menu-enabled input', context).is(':checked')) { return Drupal.checkPlain($('.form-item-menu-link-title input', context).val()); } else { return Drupal.t('Not in menu'); } }); } }; /** * Automatically fill in a menu link title, if possible. */ Drupal.behaviors.menuLinkAutomaticTitle = { attach: function (context) { $('fieldset.menu-link-form', context).each(function () { // Try to find menu settings widget elements as well as a 'title' field in // the form, but play nicely with user permissions and form alterations. var $checkbox = $('.form-item-menu-enabled input', this); var $link_title = $('.form-item-menu-link-title input', context); var $title = $(this).closest('form').find('.form-item-title input'); // Bail out if we do not have all required fields. if (!($checkbox.length && $link_title.length && $title.length)) { return; } // If there is a link title already, mark it as overridden. The user expects // that toggling the checkbox twice will take over the node's title. if ($checkbox.is(':checked') && $link_title.val().length) { $link_title.data('menuLinkAutomaticTitleOveridden', true); } // Whenever the value is changed manually, disable this behavior. $link_title.keyup(function () { $link_title.data('menuLinkAutomaticTitleOveridden', true); }); // Global trigger on checkbox (do not fill-in a value when disabled). $checkbox.change(function () { if ($checkbox.is(':checked')) { if (!$link_title.data('menuLinkAutomaticTitleOveridden')) { $link_title.val($title.val()); } } else { $link_title.val(''); $link_title.removeData('menuLinkAutomaticTitleOveridden'); } $checkbox.closest('fieldset.vertical-tabs-pane').trigger('summaryUpdated'); $checkbox.trigger('formUpdated'); }); // Take over any title change. $title.keyup(function () { if (!$link_title.data('menuLinkAutomaticTitleOveridden') && $checkbox.is(':checked')) { $link_title.val($title.val()); $link_title.val($title.val()).trigger('formUpdated'); } }); }); } }; })(jQuery);
JavaScript
(function ($) { Drupal.behaviors.menuChangeParentItems = { attach: function (context, settings) { $('fieldset#edit-menu input').each(function () { $(this).change(function () { // Update list of available parent menu items. Drupal.menu_update_parent_list(); }); }); } }; /** * Function to set the options of the menu parent item dropdown. */ Drupal.menu_update_parent_list = function () { var values = []; $('input:checked', $('fieldset#edit-menu')).each(function () { // Get the names of all checked menus. values.push(Drupal.checkPlain($.trim($(this).val()))); }); var url = Drupal.settings.basePath + 'admin/structure/menu/parents'; $.ajax({ url: location.protocol + '//' + location.host + url, type: 'POST', data: {'menus[]' : values}, dataType: 'json', success: function (options) { // Save key of last selected element. var selected = $('fieldset#edit-menu #edit-menu-parent :selected').val(); // Remove all exisiting options from dropdown. $('fieldset#edit-menu #edit-menu-parent').children().remove(); // Add new options to dropdown. jQuery.each(options, function(index, value) { $('fieldset#edit-menu #edit-menu-parent').append( $('<option ' + (index == selected ? ' selected="selected"' : '') + '></option>').val(index).text(value) ); }); } }); }; })(jQuery);
JavaScript
/** * @file * Attaches behaviors for the Dashboard module. */ (function ($) { /** * Implements Drupal.behaviors for the Dashboard module. */ Drupal.behaviors.dashboard = { attach: function (context, settings) { $('#dashboard', context).once(function () { $(this).prepend('<div class="customize clearfix"><ul class="action-links"><li><a href="#">' + Drupal.t('Customize dashboard') + '</a></li></ul><div class="canvas"></div></div>'); $('.customize .action-links a', this).click(Drupal.behaviors.dashboard.enterCustomizeMode); }); Drupal.behaviors.dashboard.addPlaceholders(); if (Drupal.settings.dashboard.launchCustomize) { Drupal.behaviors.dashboard.enterCustomizeMode(); } }, addPlaceholders: function() { $('#dashboard .dashboard-region .region').each(function () { var empty_text = ""; // If the region is empty if ($('.block', this).length == 0) { // Check if we are in customize mode and grab the correct empty text if ($('#dashboard').hasClass('customize-mode')) { empty_text = Drupal.settings.dashboard.emptyRegionTextActive; } else { empty_text = Drupal.settings.dashboard.emptyRegionTextInactive; } // We need a placeholder. if ($('.placeholder', this).length == 0) { $(this).append('<div class="placeholder"></div>'); } $('.placeholder', this).html(empty_text); } else { $('.placeholder', this).remove(); } }); }, /** * Enters "customize" mode by displaying disabled blocks. */ enterCustomizeMode: function () { $('#dashboard').addClass('customize-mode customize-inactive'); Drupal.behaviors.dashboard.addPlaceholders(); // Hide the customize link $('#dashboard .customize .action-links').hide(); // Load up the disabled blocks $('div.customize .canvas').load(Drupal.settings.dashboard.drawer, Drupal.behaviors.dashboard.setupDrawer); }, /** * Exits "customize" mode by simply forcing a page refresh. */ exitCustomizeMode: function () { $('#dashboard').removeClass('customize-mode customize-inactive'); Drupal.behaviors.dashboard.addPlaceholders(); location.href = Drupal.settings.dashboard.dashboard; }, /** * Sets up the drag-and-drop behavior and the 'close' button. */ setupDrawer: function () { $('div.customize .canvas-content input').click(Drupal.behaviors.dashboard.exitCustomizeMode); $('div.customize .canvas-content').append('<a class="button" href="' + Drupal.settings.dashboard.dashboard + '">' + Drupal.t('Done') + '</a>'); // Initialize drag-and-drop. var regions = $('#dashboard div.region'); regions.sortable({ connectWith: regions, cursor: 'move', cursorAt: {top:0}, dropOnEmpty: true, items: '> div.block, > div.disabled-block', placeholder: 'block-placeholder clearfix', tolerance: 'pointer', start: Drupal.behaviors.dashboard.start, over: Drupal.behaviors.dashboard.over, sort: Drupal.behaviors.dashboard.sort, update: Drupal.behaviors.dashboard.update }); }, /** * Makes the block appear as a disabled block while dragging. * * This function is called on the jQuery UI Sortable "start" event. * * @param event * The event that triggered this callback. * @param ui * An object containing information about the item that is being dragged. */ start: function (event, ui) { $('#dashboard').removeClass('customize-inactive'); var item = $(ui.item); // If the block is already in disabled state, don't do anything. if (!item.hasClass('disabled-block')) { item.css({height: 'auto'}); } }, /** * Adapts block's width to the region it is moved into while dragging. * * This function is called on the jQuery UI Sortable "over" event. * * @param event * The event that triggered this callback. * @param ui * An object containing information about the item that is being dragged. */ over: function (event, ui) { var item = $(ui.item); // If the block is in disabled state, remove width. if ($(this).closest('#disabled-blocks').length) { item.css('width', ''); } else { item.css('width', $(this).width()); } }, /** * Adapts a block's position to stay connected with the mouse pointer. * * This function is called on the jQuery UI Sortable "sort" event. * * @param event * The event that triggered this callback. * @param ui * An object containing information about the item that is being dragged. */ sort: function (event, ui) { var item = $(ui.item); if (event.pageX > ui.offset.left + item.width()) { item.css('left', event.pageX); } }, /** * Sends block order to the server, and expand previously disabled blocks. * * This function is called on the jQuery UI Sortable "update" event. * * @param event * The event that triggered this callback. * @param ui * An object containing information about the item that was just dropped. */ update: function (event, ui) { $('#dashboard').addClass('customize-inactive'); var item = $(ui.item); // If the user dragged a disabled block, load the block contents. if (item.hasClass('disabled-block')) { var module, delta, itemClass; itemClass = item.attr('class'); // Determine the block module and delta. module = itemClass.match(/\bmodule-(\S+)\b/)[1]; delta = itemClass.match(/\bdelta-(\S+)\b/)[1]; // Load the newly enabled block's content. $.get(Drupal.settings.dashboard.blockContent + '/' + module + '/' + delta, {}, function (block) { if (block) { item.html(block); } if (item.find('div.content').is(':empty')) { item.find('div.content').html(Drupal.settings.dashboard.emptyBlockText); } Drupal.attachBehaviors(item); }, 'html' ); // Remove the "disabled-block" class, so we don't reload its content the // next time it's dragged. item.removeClass("disabled-block"); } Drupal.behaviors.dashboard.addPlaceholders(); // Let the server know what the new block order is. $.post(Drupal.settings.dashboard.updatePath, { 'form_token': Drupal.settings.dashboard.formToken, 'regions': Drupal.behaviors.dashboard.getOrder } ); }, /** * Returns the current order of the blocks in each of the sortable regions. * * @return * The current order of the blocks, in query string format. */ getOrder: function () { var order = []; $('#dashboard div.region').each(function () { var region = $(this).parent().attr('id').replace(/-/g, '_'); var blocks = $(this).sortable('toArray'); $.each(blocks, function() { order.push(region + '[]=' + this); }); }); order = order.join('&'); return order; } }; })(jQuery);
JavaScript
(function ($) { /** * Attaches language support to the jQuery UI datepicker component. */ Drupal.behaviors.localeDatepicker = { attach: function(context, settings) { // This code accesses Drupal.settings and localized strings via Drupal.t(). // So this code should run after these are initialized. By placing it in an // attach behavior this is assured. $.datepicker.regional['drupal-locale'] = $.extend({ closeText: Drupal.t('Done'), prevText: Drupal.t('Prev'), nextText: Drupal.t('Next'), currentText: Drupal.t('Today'), monthNames: [ Drupal.t('January'), Drupal.t('February'), Drupal.t('March'), Drupal.t('April'), Drupal.t('May'), Drupal.t('June'), Drupal.t('July'), Drupal.t('August'), Drupal.t('September'), Drupal.t('October'), Drupal.t('November'), Drupal.t('December') ], monthNamesShort: [ Drupal.t('Jan'), Drupal.t('Feb'), Drupal.t('Mar'), Drupal.t('Apr'), Drupal.t('May'), Drupal.t('Jun'), Drupal.t('Jul'), Drupal.t('Aug'), Drupal.t('Sep'), Drupal.t('Oct'), Drupal.t('Nov'), Drupal.t('Dec') ], dayNames: [ Drupal.t('Sunday'), Drupal.t('Monday'), Drupal.t('Tuesday'), Drupal.t('Wednesday'), Drupal.t('Thursday'), Drupal.t('Friday'), Drupal.t('Saturday') ], dayNamesShort: [ Drupal.t('Sun'), Drupal.t('Mon'), Drupal.t('Tue'), Drupal.t('Wed'), Drupal.t('Thu'), Drupal.t('Fri'), Drupal.t('Sat') ], dayNamesMin: [ Drupal.t('Su'), Drupal.t('Mo'), Drupal.t('Tu'), Drupal.t('We'), Drupal.t('Th'), Drupal.t('Fr'), Drupal.t('Sa') ], dateFormat: Drupal.t('mm/dd/yy'), firstDay: 0, isRTL: 0 }, Drupal.settings.jquery.ui.datepicker); $.datepicker.setDefaults($.datepicker.regional['drupal-locale']); } }; })(jQuery);
JavaScript
Drupal.t("Standard Call t"); Drupal . t ( "Whitespace Call t" ) ; Drupal.t('Single Quote t'); Drupal.t('Single Quote \'Escaped\' t'); Drupal.t('Single Quote ' + 'Concat ' + 'strings ' + 't'); Drupal.t("Double Quote t"); Drupal.t("Double Quote \"Escaped\" t"); Drupal.t("Double Quote " + "Concat " + "strings " + "t"); Drupal.t("Context Unquoted t", {}, {context: "Context string unquoted"}); Drupal.t("Context Single Quoted t", {}, {'context': "Context string single quoted"}); Drupal.t("Context Double Quoted t", {}, {"context": "Context string double quoted"}); Drupal.t("Context !key Args t", {'!key': 'value'}, {context: "Context string"}); Drupal.formatPlural(1, "Standard Call plural", "Standard Call @count plural"); Drupal . formatPlural ( 1, "Whitespace Call plural", "Whitespace Call @count plural" ) ; Drupal.formatPlural(1, 'Single Quote plural', 'Single Quote @count plural'); Drupal.formatPlural(1, 'Single Quote \'Escaped\' plural', 'Single Quote \'Escaped\' @count plural'); Drupal.formatPlural(1, "Double Quote plural", "Double Quote @count plural"); Drupal.formatPlural(1, "Double Quote \"Escaped\" plural", "Double Quote \"Escaped\" @count plural"); Drupal.formatPlural(1, "Context Unquoted plural", "Context Unquoted @count plural", {}, {context: "Context string unquoted"}); Drupal.formatPlural(1, "Context Single Quoted plural", "Context Single Quoted @count plural", {}, {'context': "Context string single quoted"}); Drupal.formatPlural(1, "Context Double Quoted plural", "Context Double Quoted @count plural", {}, {"context": "Context string double quoted"}); Drupal.formatPlural(1, "Context !key Args plural", "Context !key Args @count plural", {'!key': 'value'}, {context: "Context string"});
JavaScript
/** * @file * Attaches the behaviors for the Color module. */ (function ($) { Drupal.behaviors.color = { attach: function (context, settings) { var i, j, colors, field_name; // This behavior attaches by ID, so is only valid once on a page. var form = $('#system-theme-settings .color-form', context).once('color'); if (form.length == 0) { return; } var inputs = []; var hooks = []; var locks = []; var focused = null; // Add Farbtastic. $(form).prepend('<div id="placeholder"></div>').addClass('color-processed'); var farb = $.farbtastic('#placeholder'); // Decode reference colors to HSL. var reference = settings.color.reference; for (i in reference) { reference[i] = farb.RGBToHSL(farb.unpack(reference[i])); } // Build a preview. var height = []; var width = []; // Loop through all defined gradients. for (i in settings.gradients) { // Add element to display the gradient. $('#preview').once('color').append('<div id="gradient-' + i + '"></div>'); var gradient = $('#preview #gradient-' + i); // Add height of current gradient to the list (divided by 10). height.push(parseInt(gradient.css('height'), 10) / 10); // Add width of current gradient to the list (divided by 10). width.push(parseInt(gradient.css('width'), 10) / 10); // Add rows (or columns for horizontal gradients). // Each gradient line should have a height (or width for horizontal // gradients) of 10px (because we divided the height/width by 10 above). for (j = 0; j < (settings.gradients[i]['direction'] == 'vertical' ? height[i] : width[i]); ++j) { gradient.append('<div class="gradient-line"></div>'); } } // Fix preview background in IE6. if (navigator.appVersion.match(/MSIE [0-6]\./)) { var e = $('#preview #img')[0]; var image = e.currentStyle.backgroundImage; e.style.backgroundImage = 'none'; e.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image.substring(5, image.length - 2) + "')"; } // Set up colorScheme selector. $('#edit-scheme', form).change(function () { var schemes = settings.color.schemes, colorScheme = this.options[this.selectedIndex].value; if (colorScheme != '' && schemes[colorScheme]) { // Get colors of active scheme. colors = schemes[colorScheme]; for (field_name in colors) { callback($('#edit-palette-' + field_name), colors[field_name], false, true); } preview(); } }); /** * Renders the preview. */ function preview() { Drupal.color.callback(context, settings, form, farb, height, width); } /** * Shifts a given color, using a reference pair (ref in HSL). * * This algorithm ensures relative ordering on the saturation and luminance * axes is preserved, and performs a simple hue shift. * * It is also symmetrical. If: shift_color(c, a, b) == d, then * shift_color(d, b, a) == c. */ function shift_color(given, ref1, ref2) { // Convert to HSL. given = farb.RGBToHSL(farb.unpack(given)); // Hue: apply delta. given[0] += ref2[0] - ref1[0]; // Saturation: interpolate. if (ref1[1] == 0 || ref2[1] == 0) { given[1] = ref2[1]; } else { var d = ref1[1] / ref2[1]; if (d > 1) { given[1] /= d; } else { given[1] = 1 - (1 - given[1]) * d; } } // Luminance: interpolate. if (ref1[2] == 0 || ref2[2] == 0) { given[2] = ref2[2]; } else { var d = ref1[2] / ref2[2]; if (d > 1) { given[2] /= d; } else { given[2] = 1 - (1 - given[2]) * d; } } return farb.pack(farb.HSLToRGB(given)); } /** * Callback for Farbtastic when a new color is chosen. */ function callback(input, color, propagate, colorScheme) { var matched; // Set background/foreground colors. $(input).css({ backgroundColor: color, 'color': farb.RGBToHSL(farb.unpack(color))[2] > 0.5 ? '#000' : '#fff' }); // Change input value. if ($(input).val() && $(input).val() != color) { $(input).val(color); // Update locked values. if (propagate) { i = input.i; for (j = i + 1; ; ++j) { if (!locks[j - 1] || $(locks[j - 1]).is('.unlocked')) break; matched = shift_color(color, reference[input.key], reference[inputs[j].key]); callback(inputs[j], matched, false); } for (j = i - 1; ; --j) { if (!locks[j] || $(locks[j]).is('.unlocked')) break; matched = shift_color(color, reference[input.key], reference[inputs[j].key]); callback(inputs[j], matched, false); } // Update preview. preview(); } // Reset colorScheme selector. if (!colorScheme) { resetScheme(); } } } /** * Resets the color scheme selector. */ function resetScheme() { $('#edit-scheme', form).each(function () { this.selectedIndex = this.options.length - 1; }); } /** * Focuses Farbtastic on a particular field. */ function focus() { var input = this; // Remove old bindings. focused && $(focused).unbind('keyup', farb.updateValue) .unbind('keyup', preview).unbind('keyup', resetScheme) .parent().removeClass('item-selected'); // Add new bindings. focused = this; farb.linkTo(function (color) { callback(input, color, true, false); }); farb.setColor(this.value); $(focused).keyup(farb.updateValue).keyup(preview).keyup(resetScheme) .parent().addClass('item-selected'); } // Initialize color fields. $('#palette input.form-text', form) .each(function () { // Extract palette field name this.key = this.id.substring(13); // Link to color picker temporarily to initialize. farb.linkTo(function () {}).setColor('#000').linkTo(this); // Add lock. var i = inputs.length; if (inputs.length) { var lock = $('<div class="lock"></div>').toggle( function () { $(this).addClass('unlocked'); $(hooks[i - 1]).attr('class', locks[i - 2] && $(locks[i - 2]).is(':not(.unlocked)') ? 'hook up' : 'hook' ); $(hooks[i]).attr('class', locks[i] && $(locks[i]).is(':not(.unlocked)') ? 'hook down' : 'hook' ); }, function () { $(this).removeClass('unlocked'); $(hooks[i - 1]).attr('class', locks[i - 2] && $(locks[i - 2]).is(':not(.unlocked)') ? 'hook both' : 'hook down' ); $(hooks[i]).attr('class', locks[i] && $(locks[i]).is(':not(.unlocked)') ? 'hook both' : 'hook up' ); } ); $(this).after(lock); locks.push(lock); }; // Add hook. var hook = $('<div class="hook"></div>'); $(this).after(hook); hooks.push(hook); $(this).parent().find('.lock').click(); this.i = i; inputs.push(this); }) .focus(focus); $('#palette label', form); // Focus first color. focus.call(inputs[0]); // Render preview. preview(); } }; })(jQuery);
JavaScript
/** * @file * Attaches preview-related behavior for the Color module. */ (function ($) { Drupal.color = { callback: function(context, settings, form, farb, height, width) { // Solid background. $('#preview', form).css('backgroundColor', $('#palette input[name="palette[base]"]', form).val()); // Text preview $('#text', form).css('color', $('#palette input[name="palette[text]"]', form).val()); $('#text a, #text h2', form).css('color', $('#palette input[name="palette[link]"]', form).val()); // Set up gradients if there are some. var color_start, color_end; for (i in settings.gradients) { color_start = farb.unpack($('#palette input[name="palette[' + settings.gradients[i]['colors'][0] + ']"]', form).val()); color_end = farb.unpack($('#palette input[name="palette[' + settings.gradients[i]['colors'][1] + ']"]', form).val()); if (color_start && color_end) { var delta = []; for (j in color_start) { delta[j] = (color_end[j] - color_start[j]) / (settings.gradients[i]['vertical'] ? height[i] : width[i]); } var accum = color_start; // Render gradient lines. $('#gradient-' + i + ' > div', form).each(function () { for (j in accum) { accum[j] += delta[j]; } this.style.backgroundColor = farb.pack(accum); }); } } } }; })(jQuery);
JavaScript
(function ($) { /** * Provide the summary information for the block settings vertical tabs. */ Drupal.behaviors.blockSettingsSummary = { attach: function (context) { // The drupalSetSummary method required for this behavior is not available // on the Blocks administration page, so we need to make sure this // behavior is processed only if drupalSetSummary is defined. if (typeof jQuery.fn.drupalSetSummary == 'undefined') { return; } $('fieldset#edit-path', context).drupalSetSummary(function (context) { if (!$('textarea[name="pages"]', context).val()) { return Drupal.t('Not restricted'); } else { return Drupal.t('Restricted to certain pages'); } }); $('fieldset#edit-node-type', context).drupalSetSummary(function (context) { var vals = []; $('input[type="checkbox"]:checked', context).each(function () { vals.push($.trim($(this).next('label').text())); }); if (!vals.length) { vals.push(Drupal.t('Not restricted')); } return vals.join(', '); }); $('fieldset#edit-role', context).drupalSetSummary(function (context) { var vals = []; $('input[type="checkbox"]:checked', context).each(function () { vals.push($.trim($(this).next('label').text())); }); if (!vals.length) { vals.push(Drupal.t('Not restricted')); } return vals.join(', '); }); $('fieldset#edit-user', context).drupalSetSummary(function (context) { var $radio = $('input[name="custom"]:checked', context); if ($radio.val() == 0) { return Drupal.t('Not customizable'); } else { return $radio.next('label').text(); } }); } }; /** * Move a block in the blocks table from one region to another via select list. * * This behavior is dependent on the tableDrag behavior, since it uses the * objects initialized in that behavior to update the row. */ Drupal.behaviors.blockDrag = { attach: function (context, settings) { // tableDrag is required and we should be on the blocks admin page. if (typeof Drupal.tableDrag == 'undefined' || typeof Drupal.tableDrag.blocks == 'undefined') { return; } var table = $('table#blocks'); var tableDrag = Drupal.tableDrag.blocks; // Get the blocks tableDrag object. // Add a handler for when a row is swapped, update empty regions. tableDrag.row.prototype.onSwap = function (swappedRow) { checkEmptyRegions(table, this); }; // A custom message for the blocks page specifically. Drupal.theme.tableDragChangedWarning = function () { return '<div class="messages warning">' + Drupal.theme('tableDragChangedMarker') + ' ' + Drupal.t('The changes to these blocks will not be saved until the <em>Save blocks</em> button is clicked.') + '</div>'; }; // Add a handler so when a row is dropped, update fields dropped into new regions. tableDrag.onDrop = function () { dragObject = this; // Use "region-message" row instead of "region" row because // "region-{region_name}-message" is less prone to regexp match errors. var regionRow = $(dragObject.rowObject.element).prevAll('tr.region-message').get(0); var regionName = regionRow.className.replace(/([^ ]+[ ]+)*region-([^ ]+)-message([ ]+[^ ]+)*/, '$2'); var regionField = $('select.block-region-select', dragObject.rowObject.element); // Check whether the newly picked region is available for this block. if ($('option[value=' + regionName + ']', regionField).length == 0) { // If not, alert the user and keep the block in its old region setting. alert(Drupal.t('The block cannot be placed in this region.')); // Simulate that there was a selected element change, so the row is put // back to from where the user tried to drag it. regionField.change(); } else if ($(dragObject.rowObject.element).prev('tr').is('.region-message')) { var weightField = $('select.block-weight', dragObject.rowObject.element); var oldRegionName = weightField[0].className.replace(/([^ ]+[ ]+)*block-weight-([^ ]+)([ ]+[^ ]+)*/, '$2'); if (!regionField.is('.block-region-' + regionName)) { regionField.removeClass('block-region-' + oldRegionName).addClass('block-region-' + regionName); weightField.removeClass('block-weight-' + oldRegionName).addClass('block-weight-' + regionName); regionField.val(regionName); } } }; // Add the behavior to each region select list. $('select.block-region-select', context).once('block-region-select', function () { $(this).change(function (event) { // Make our new row and select field. var row = $(this).closest('tr'); var select = $(this); tableDrag.rowObject = new tableDrag.row(row); // Find the correct region and insert the row as the last in the region. table.find('.region-' + select[0].value + '-message').nextUntil('.region-message').last().before(row); // Modify empty regions with added or removed fields. checkEmptyRegions(table, row); // Remove focus from selectbox. select.get(0).blur(); }); }); var checkEmptyRegions = function (table, rowObject) { $('tr.region-message', table).each(function () { // If the dragged row is in this region, but above the message row, swap it down one space. if ($(this).prev('tr').get(0) == rowObject.element) { // Prevent a recursion problem when using the keyboard to move rows up. if ((rowObject.method != 'keyboard' || rowObject.direction == 'down')) { rowObject.swap('after', this); } } // This region has become empty. if ($(this).next('tr').is(':not(.draggable)') || $(this).next('tr').length == 0) { $(this).removeClass('region-populated').addClass('region-empty'); } // This region has become populated. else if ($(this).is('.region-empty')) { $(this).removeClass('region-empty').addClass('region-populated'); } }); }; } }; })(jQuery);
JavaScript
(function ($) { /** * Add the cool table collapsing on the testing overview page. */ Drupal.behaviors.simpleTestMenuCollapse = { attach: function (context, settings) { var timeout = null; // Adds expand-collapse functionality. $('div.simpletest-image').once('simpletest-image', function () { var $this = $(this); var direction = settings.simpleTest[this.id].imageDirection; $this.html(settings.simpleTest.images[direction]); // Adds group toggling functionality to arrow images. $this.click(function () { var trs = $this.closest('tbody').children('.' + settings.simpleTest[this.id].testClass); var direction = settings.simpleTest[this.id].imageDirection; var row = direction ? trs.length - 1 : 0; // If clicked in the middle of expanding a group, stop so we can switch directions. if (timeout) { clearTimeout(timeout); } // Function to toggle an individual row according to the current direction. // We set a timeout of 20 ms until the next row will be shown/hidden to // create a sliding effect. function rowToggle() { if (direction) { if (row >= 0) { $(trs[row]).hide(); row--; timeout = setTimeout(rowToggle, 20); } } else { if (row < trs.length) { $(trs[row]).removeClass('js-hide').show(); row++; timeout = setTimeout(rowToggle, 20); } } } // Kick-off the toggling upon a new click. rowToggle(); // Toggle the arrow image next to the test group title. $this.html(settings.simpleTest.images[(direction ? 0 : 1)]); settings.simpleTest[this.id].imageDirection = !direction; }); }); } }; /** * Select/deselect all the inner checkboxes when the outer checkboxes are * selected/deselected. */ Drupal.behaviors.simpleTestSelectAll = { attach: function (context, settings) { $('td.simpletest-select-all').once('simpletest-select-all', function () { var testCheckboxes = settings.simpleTest['simpletest-test-group-' + $(this).attr('id')].testNames; var groupCheckbox = $('<input type="checkbox" class="form-checkbox" id="' + $(this).attr('id') + '-select-all" />'); // Each time a single-test checkbox is checked or unchecked, make sure // that the associated group checkbox gets the right state too. var updateGroupCheckbox = function () { var checkedTests = 0; for (var i = 0; i < testCheckboxes.length; i++) { $('#' + testCheckboxes[i]).each(function () { if (($(this).attr('checked'))) { checkedTests++; } }); } $(groupCheckbox).attr('checked', (checkedTests == testCheckboxes.length)); }; // Have the single-test checkboxes follow the group checkbox. groupCheckbox.change(function () { var checked = !!($(this).attr('checked')); for (var i = 0; i < testCheckboxes.length; i++) { $('#' + testCheckboxes[i]).attr('checked', checked); } }); // Have the group checkbox follow the single-test checkboxes. for (var i = 0; i < testCheckboxes.length; i++) { $('#' + testCheckboxes[i]).change(function () { updateGroupCheckbox(); }); } // Initialize status for the group checkbox correctly. updateGroupCheckbox(); $(this).append(groupCheckbox); }); } }; })(jQuery);
JavaScript
(function ($) { /** * Attaches sticky table headers. */ Drupal.behaviors.tableHeader = { attach: function (context, settings) { if (!$.support.positionFixed) { return; } $('table.sticky-enabled', context).once('tableheader', function () { $(this).data("drupal-tableheader", new Drupal.tableHeader(this)); }); } }; /** * Constructor for the tableHeader object. Provides sticky table headers. * * @param table * DOM object for the table to add a sticky header to. */ Drupal.tableHeader = function (table) { var self = this; this.originalTable = $(table); this.originalHeader = $(table).children('thead'); this.originalHeaderCells = this.originalHeader.find('> tr > th'); this.displayWeight = null; // React to columns change to avoid making checks in the scroll callback. this.originalTable.bind('columnschange', function (e, display) { // This will force header size to be calculated on scroll. self.widthCalculated = (self.displayWeight !== null && self.displayWeight === display); self.displayWeight = display; }); // Clone the table header so it inherits original jQuery properties. Hide // the table to avoid a flash of the header clone upon page load. this.stickyTable = $('<table class="sticky-header"/>') .insertBefore(this.originalTable) .css({ position: 'fixed', top: '0px' }); this.stickyHeader = this.originalHeader.clone(true) .hide() .appendTo(this.stickyTable); this.stickyHeaderCells = this.stickyHeader.find('> tr > th'); this.originalTable.addClass('sticky-table'); $(window) .bind('scroll.drupal-tableheader', $.proxy(this, 'eventhandlerRecalculateStickyHeader')) .bind('resize.drupal-tableheader', { calculateWidth: true }, $.proxy(this, 'eventhandlerRecalculateStickyHeader')) // Make sure the anchor being scrolled into view is not hidden beneath the // sticky table header. Adjust the scrollTop if it does. .bind('drupalDisplaceAnchor.drupal-tableheader', function () { window.scrollBy(0, -self.stickyTable.outerHeight()); }) // Make sure the element being focused is not hidden beneath the sticky // table header. Adjust the scrollTop if it does. .bind('drupalDisplaceFocus.drupal-tableheader', function (event) { if (self.stickyVisible && event.clientY < (self.stickyOffsetTop + self.stickyTable.outerHeight()) && event.$target.closest('sticky-header').length === 0) { window.scrollBy(0, -self.stickyTable.outerHeight()); } }) .triggerHandler('resize.drupal-tableheader'); // We hid the header to avoid it showing up erroneously on page load; // we need to unhide it now so that it will show up when expected. this.stickyHeader.show(); }; /** * Event handler: recalculates position of the sticky table header. * * @param event * Event being triggered. */ Drupal.tableHeader.prototype.eventhandlerRecalculateStickyHeader = function (event) { var self = this; var calculateWidth = event.data && event.data.calculateWidth; // Reset top position of sticky table headers to the current top offset. this.stickyOffsetTop = Drupal.settings.tableHeaderOffset ? eval(Drupal.settings.tableHeaderOffset + '()') : 0; this.stickyTable.css('top', this.stickyOffsetTop + 'px'); // Save positioning data. var viewHeight = document.documentElement.scrollHeight || document.body.scrollHeight; if (calculateWidth || this.viewHeight !== viewHeight) { this.viewHeight = viewHeight; this.vPosition = this.originalTable.offset().top - 4 - this.stickyOffsetTop; this.hPosition = this.originalTable.offset().left; this.vLength = this.originalTable[0].clientHeight - 100; calculateWidth = true; } // Track horizontal positioning relative to the viewport and set visibility. var hScroll = document.documentElement.scrollLeft || document.body.scrollLeft; var vOffset = (document.documentElement.scrollTop || document.body.scrollTop) - this.vPosition; this.stickyVisible = vOffset > 0 && vOffset < this.vLength; this.stickyTable.css({ left: (-hScroll + this.hPosition) + 'px', visibility: this.stickyVisible ? 'visible' : 'hidden' }); // Only perform expensive calculations if the sticky header is actually // visible or when forced. if (this.stickyVisible && (calculateWidth || !this.widthCalculated)) { this.widthCalculated = true; var $that = null; var $stickyCell = null; var display = null; var cellWidth = null; // Resize header and its cell widths. // Only apply width to visible table cells. This prevents the header from // displaying incorrectly when the sticky header is no longer visible. for (var i = 0, il = this.originalHeaderCells.length; i < il; i += 1) { $that = $(this.originalHeaderCells[i]); $stickyCell = this.stickyHeaderCells.eq($that.index()); display = $that.css('display'); if (display !== 'none') { cellWidth = $that.css('width'); // Exception for IE7. if (cellWidth === 'auto') { cellWidth = $that[0].clientWidth + 'px'; } $stickyCell.css({'width': cellWidth, 'display': display}); } else { $stickyCell.css('display', 'none'); } } this.stickyTable.css('width', this.originalTable.css('width')); } }; })(jQuery);
JavaScript
/** * @file * Conditionally hide or show the appropriate settings and saved defaults * on the file transfer connection settings form used by authorize.php. */ (function ($) { Drupal.behaviors.authorizeFileTransferForm = { attach: function(context) { $('#edit-connection-settings-authorize-filetransfer-default').change(function() { $('.filetransfer').hide().filter('.filetransfer-' + $(this).val()).show(); }); $('.filetransfer').hide().filter('.filetransfer-' + $('#edit-connection-settings-authorize-filetransfer-default').val()).show(); // Removes the float on the select box (used for non-JS interface). if ($('.connection-settings-update-filetransfer-default-wrapper').length > 0) { $('.connection-settings-update-filetransfer-default-wrapper').css('float', 'none'); } // Hides the submit button for non-js users. $('#edit-submit-connection').hide(); $('#edit-submit-process').show(); } }; })(jQuery);
JavaScript
(function ($) { /** * Drag and drop table rows with field manipulation. * * Using the drupal_add_tabledrag() function, any table with weights or parent * relationships may be made into draggable tables. Columns containing a field * may optionally be hidden, providing a better user experience. * * Created tableDrag instances may be modified with custom behaviors by * overriding the .onDrag, .onDrop, .row.onSwap, and .row.onIndent methods. * See blocks.js for an example of adding additional functionality to tableDrag. */ Drupal.behaviors.tableDrag = { attach: function (context, settings) { for (var base in settings.tableDrag) { $('#' + base, context).once('tabledrag', function () { // Create the new tableDrag instance. Save in the Drupal variable // to allow other scripts access to the object. Drupal.tableDrag[base] = new Drupal.tableDrag(this, settings.tableDrag[base]); }); } } }; /** * Constructor for the tableDrag object. Provides table and field manipulation. * * @param table * DOM object for the table to be made draggable. * @param tableSettings * Settings for the table added via drupal_add_dragtable(). */ Drupal.tableDrag = function (table, tableSettings) { var self = this; // Required object variables. this.table = table; this.tableSettings = tableSettings; this.dragObject = null; // Used to hold information about a current drag operation. this.rowObject = null; // Provides operations for row manipulation. this.oldRowElement = null; // Remember the previous element. this.oldY = 0; // Used to determine up or down direction from last mouse move. this.changed = false; // Whether anything in the entire table has changed. this.maxDepth = 0; // Maximum amount of allowed parenting. this.rtl = $(this.table).css('direction') == 'rtl' ? -1 : 1; // Direction of the table. // Configure the scroll settings. this.scrollSettings = { amount: 4, interval: 50, trigger: 70 }; this.scrollInterval = null; this.scrollY = 0; this.windowHeight = 0; // Check this table's settings to see if there are parent relationships in // this table. For efficiency, large sections of code can be skipped if we // don't need to track horizontal movement and indentations. this.indentEnabled = false; for (var group in tableSettings) { for (var n in tableSettings[group]) { if (tableSettings[group][n].relationship == 'parent') { this.indentEnabled = true; } if (tableSettings[group][n].limit > 0) { this.maxDepth = tableSettings[group][n].limit; } } } if (this.indentEnabled) { this.indentCount = 1; // Total width of indents, set in makeDraggable. // Find the width of indentations to measure mouse movements against. // Because the table doesn't need to start with any indentations, we // manually append 2 indentations in the first draggable row, measure // the offset, then remove. var indent = Drupal.theme('tableDragIndentation'); var testRow = $('<tr/>').addClass('draggable').appendTo(table); var testCell = $('<td/>').appendTo(testRow).prepend(indent).prepend(indent); this.indentAmount = $('.indentation', testCell).get(1).offsetLeft - $('.indentation', testCell).get(0).offsetLeft; testRow.remove(); } // Make each applicable row draggable. // Match immediate children of the parent element to allow nesting. $('> tr.draggable, > tbody > tr.draggable', table).each(function () { self.makeDraggable(this); }); // Add a link before the table for users to show or hide weight columns. $(table).before($('<a href="#" class="tabledrag-toggle-weight"></a>') .attr('title', Drupal.t('Re-order rows by numerical weight instead of dragging.')) .click(function () { if ($.cookie('Drupal.tableDrag.showWeight') == 1) { self.hideColumns(); } else { self.showColumns(); } return false; }) .wrap('<div class="tabledrag-toggle-weight-wrapper"></div>') .parent() ); // Initialize the specified columns (for example, weight or parent columns) // to show or hide according to user preference. This aids accessibility // so that, e.g., screen reader users can choose to enter weight values and // manipulate form elements directly, rather than using drag-and-drop.. self.initColumns(); // Add mouse bindings to the document. The self variable is passed along // as event handlers do not have direct access to the tableDrag object. $(document).bind('mousemove', function (event) { return self.dragRow(event, self); }); $(document).bind('mouseup', function (event) { return self.dropRow(event, self); }); }; /** * Initialize columns containing form elements to be hidden by default, * according to the settings for this tableDrag instance. * * Identify and mark each cell with a CSS class so we can easily toggle * show/hide it. Finally, hide columns if user does not have a * 'Drupal.tableDrag.showWeight' cookie. */ Drupal.tableDrag.prototype.initColumns = function () { for (var group in this.tableSettings) { // Find the first field in this group. for (var d in this.tableSettings[group]) { var field = $('.' + this.tableSettings[group][d].target + ':first', this.table); if (field.length && this.tableSettings[group][d].hidden) { var hidden = this.tableSettings[group][d].hidden; var cell = field.closest('td'); break; } } // Mark the column containing this field so it can be hidden. if (hidden && cell[0]) { // Add 1 to our indexes. The nth-child selector is 1 based, not 0 based. // Match immediate children of the parent element to allow nesting. var columnIndex = $('> td', cell.parent()).index(cell.get(0)) + 1; $('> thead > tr, > tbody > tr, > tr', this.table).each(function () { // Get the columnIndex and adjust for any colspans in this row. var index = columnIndex; var cells = $(this).children(); cells.each(function (n) { if (n < index && this.colSpan && this.colSpan > 1) { index -= this.colSpan - 1; } }); if (index > 0) { cell = cells.filter(':nth-child(' + index + ')'); if (cell[0].colSpan && cell[0].colSpan > 1) { // If this cell has a colspan, mark it so we can reduce the colspan. cell.addClass('tabledrag-has-colspan'); } else { // Mark this cell so we can hide it. cell.addClass('tabledrag-hide'); } } }); } } // Now hide cells and reduce colspans unless cookie indicates previous choice. // Set a cookie if it is not already present. if ($.cookie('Drupal.tableDrag.showWeight') === null) { $.cookie('Drupal.tableDrag.showWeight', 0, { path: Drupal.settings.basePath, // The cookie expires in one year. expires: 365 }); this.hideColumns(); } // Check cookie value and show/hide weight columns accordingly. else { if ($.cookie('Drupal.tableDrag.showWeight') == 1) { this.showColumns(); } else { this.hideColumns(); } } }; /** * Hide the columns containing weight/parent form elements. * Undo showColumns(). */ Drupal.tableDrag.prototype.hideColumns = function () { // Hide weight/parent cells and headers. $('.tabledrag-hide', 'table.tabledrag-processed').css('display', 'none'); // Show TableDrag handles. $('.tabledrag-handle', 'table.tabledrag-processed').css('display', ''); // Reduce the colspan of any effected multi-span columns. $('.tabledrag-has-colspan', 'table.tabledrag-processed').each(function () { this.colSpan = this.colSpan - 1; }); // Change link text. $('.tabledrag-toggle-weight').text(Drupal.t('Show row weights')); // Change cookie. $.cookie('Drupal.tableDrag.showWeight', 0, { path: Drupal.settings.basePath, // The cookie expires in one year. expires: 365 }); // Trigger an event to allow other scripts to react to this display change. $('table.tabledrag-processed').trigger('columnschange', 'hide'); }; /** * Show the columns containing weight/parent form elements * Undo hideColumns(). */ Drupal.tableDrag.prototype.showColumns = function () { // Show weight/parent cells and headers. $('.tabledrag-hide', 'table.tabledrag-processed').css('display', ''); // Hide TableDrag handles. $('.tabledrag-handle', 'table.tabledrag-processed').css('display', 'none'); // Increase the colspan for any columns where it was previously reduced. $('.tabledrag-has-colspan', 'table.tabledrag-processed').each(function () { this.colSpan = this.colSpan + 1; }); // Change link text. $('.tabledrag-toggle-weight').text(Drupal.t('Hide row weights')); // Change cookie. $.cookie('Drupal.tableDrag.showWeight', 1, { path: Drupal.settings.basePath, // The cookie expires in one year. expires: 365 }); // Trigger an event to allow other scripts to react to this display change. $('table.tabledrag-processed').trigger('columnschange', 'show'); }; /** * Find the target used within a particular row and group. */ Drupal.tableDrag.prototype.rowSettings = function (group, row) { var field = $('.' + group, row); for (var delta in this.tableSettings[group]) { var targetClass = this.tableSettings[group][delta].target; if (field.is('.' + targetClass)) { // Return a copy of the row settings. var rowSettings = {}; for (var n in this.tableSettings[group][delta]) { rowSettings[n] = this.tableSettings[group][delta][n]; } return rowSettings; } } }; /** * Take an item and add event handlers to make it become draggable. */ Drupal.tableDrag.prototype.makeDraggable = function (item) { var self = this; // Create the handle. var handle = $('<a href="#" class="tabledrag-handle"><div class="handle">&nbsp;</div></a>').attr('title', Drupal.t('Drag to re-order')); // Insert the handle after indentations (if any). if ($('td:first .indentation:last', item).length) { $('td:first .indentation:last', item).after(handle); // Update the total width of indentation in this entire table. self.indentCount = Math.max($('.indentation', item).length, self.indentCount); } else { $('td:first', item).prepend(handle); } // Add hover action for the handle. handle.hover(function () { self.dragObject == null ? $(this).addClass('tabledrag-handle-hover') : null; }, function () { self.dragObject == null ? $(this).removeClass('tabledrag-handle-hover') : null; }); // Add the mousedown action for the handle. handle.mousedown(function (event) { // Create a new dragObject recording the event information. self.dragObject = {}; self.dragObject.initMouseOffset = self.getMouseOffset(item, event); self.dragObject.initMouseCoords = self.mouseCoords(event); if (self.indentEnabled) { self.dragObject.indentMousePos = self.dragObject.initMouseCoords; } // If there's a lingering row object from the keyboard, remove its focus. if (self.rowObject) { $('a.tabledrag-handle', self.rowObject.element).blur(); } // Create a new rowObject for manipulation of this row. self.rowObject = new self.row(item, 'mouse', self.indentEnabled, self.maxDepth, true); // Save the position of the table. self.table.topY = $(self.table).offset().top; self.table.bottomY = self.table.topY + self.table.offsetHeight; // Add classes to the handle and row. $(this).addClass('tabledrag-handle-hover'); $(item).addClass('drag'); // Set the document to use the move cursor during drag. $('body').addClass('drag'); if (self.oldRowElement) { $(self.oldRowElement).removeClass('drag-previous'); } // Hack for IE6 that flickers uncontrollably if select lists are moved. if (navigator.userAgent.indexOf('MSIE 6.') != -1) { $('select', this.table).css('display', 'none'); } // Hack for Konqueror, prevent the blur handler from firing. // Konqueror always gives links focus, even after returning false on mousedown. self.safeBlur = false; // Call optional placeholder function. self.onDrag(); return false; }); // Prevent the anchor tag from jumping us to the top of the page. handle.click(function () { return false; }); // Similar to the hover event, add a class when the handle is focused. handle.focus(function () { $(this).addClass('tabledrag-handle-hover'); self.safeBlur = true; }); // Remove the handle class on blur and fire the same function as a mouseup. handle.blur(function (event) { $(this).removeClass('tabledrag-handle-hover'); if (self.rowObject && self.safeBlur) { self.dropRow(event, self); } }); // Add arrow-key support to the handle. handle.keydown(function (event) { // If a rowObject doesn't yet exist and this isn't the tab key. if (event.keyCode != 9 && !self.rowObject) { self.rowObject = new self.row(item, 'keyboard', self.indentEnabled, self.maxDepth, true); } var keyChange = false; switch (event.keyCode) { case 37: // Left arrow. case 63234: // Safari left arrow. keyChange = true; self.rowObject.indent(-1 * self.rtl); break; case 38: // Up arrow. case 63232: // Safari up arrow. var previousRow = $(self.rowObject.element).prev('tr').get(0); while (previousRow && $(previousRow).is(':hidden')) { previousRow = $(previousRow).prev('tr').get(0); } if (previousRow) { self.safeBlur = false; // Do not allow the onBlur cleanup. self.rowObject.direction = 'up'; keyChange = true; if ($(item).is('.tabledrag-root')) { // Swap with the previous top-level row. var groupHeight = 0; while (previousRow && $('.indentation', previousRow).length) { previousRow = $(previousRow).prev('tr').get(0); groupHeight += $(previousRow).is(':hidden') ? 0 : previousRow.offsetHeight; } if (previousRow) { self.rowObject.swap('before', previousRow); // No need to check for indentation, 0 is the only valid one. window.scrollBy(0, -groupHeight); } } else if (self.table.tBodies[0].rows[0] != previousRow || $(previousRow).is('.draggable')) { // Swap with the previous row (unless previous row is the first one // and undraggable). self.rowObject.swap('before', previousRow); self.rowObject.interval = null; self.rowObject.indent(0); window.scrollBy(0, -parseInt(item.offsetHeight, 10)); } handle.get(0).focus(); // Regain focus after the DOM manipulation. } break; case 39: // Right arrow. case 63235: // Safari right arrow. keyChange = true; self.rowObject.indent(1 * self.rtl); break; case 40: // Down arrow. case 63233: // Safari down arrow. var nextRow = $(self.rowObject.group).filter(':last').next('tr').get(0); while (nextRow && $(nextRow).is(':hidden')) { nextRow = $(nextRow).next('tr').get(0); } if (nextRow) { self.safeBlur = false; // Do not allow the onBlur cleanup. self.rowObject.direction = 'down'; keyChange = true; if ($(item).is('.tabledrag-root')) { // Swap with the next group (necessarily a top-level one). var groupHeight = 0; var nextGroup = new self.row(nextRow, 'keyboard', self.indentEnabled, self.maxDepth, false); if (nextGroup) { $(nextGroup.group).each(function () { groupHeight += $(this).is(':hidden') ? 0 : this.offsetHeight; }); var nextGroupRow = $(nextGroup.group).filter(':last').get(0); self.rowObject.swap('after', nextGroupRow); // No need to check for indentation, 0 is the only valid one. window.scrollBy(0, parseInt(groupHeight, 10)); } } else { // Swap with the next row. self.rowObject.swap('after', nextRow); self.rowObject.interval = null; self.rowObject.indent(0); window.scrollBy(0, parseInt(item.offsetHeight, 10)); } handle.get(0).focus(); // Regain focus after the DOM manipulation. } break; } if (self.rowObject && self.rowObject.changed == true) { $(item).addClass('drag'); if (self.oldRowElement) { $(self.oldRowElement).removeClass('drag-previous'); } self.oldRowElement = item; self.restripeTable(); self.onDrag(); } // Returning false if we have an arrow key to prevent scrolling. if (keyChange) { return false; } }); // Compatibility addition, return false on keypress to prevent unwanted scrolling. // IE and Safari will suppress scrolling on keydown, but all other browsers // need to return false on keypress. http://www.quirksmode.org/js/keys.html handle.keypress(function (event) { switch (event.keyCode) { case 37: // Left arrow. case 38: // Up arrow. case 39: // Right arrow. case 40: // Down arrow. return false; } }); }; /** * Mousemove event handler, bound to document. */ Drupal.tableDrag.prototype.dragRow = function (event, self) { if (self.dragObject) { self.currentMouseCoords = self.mouseCoords(event); var y = self.currentMouseCoords.y - self.dragObject.initMouseOffset.y; var x = self.currentMouseCoords.x - self.dragObject.initMouseOffset.x; // Check for row swapping and vertical scrolling. if (y != self.oldY) { self.rowObject.direction = y > self.oldY ? 'down' : 'up'; self.oldY = y; // Update the old value. // Check if the window should be scrolled (and how fast). var scrollAmount = self.checkScroll(self.currentMouseCoords.y); // Stop any current scrolling. clearInterval(self.scrollInterval); // Continue scrolling if the mouse has moved in the scroll direction. if (scrollAmount > 0 && self.rowObject.direction == 'down' || scrollAmount < 0 && self.rowObject.direction == 'up') { self.setScroll(scrollAmount); } // If we have a valid target, perform the swap and restripe the table. var currentRow = self.findDropTargetRow(x, y); if (currentRow) { if (self.rowObject.direction == 'down') { self.rowObject.swap('after', currentRow, self); } else { self.rowObject.swap('before', currentRow, self); } self.restripeTable(); } } // Similar to row swapping, handle indentations. if (self.indentEnabled) { var xDiff = self.currentMouseCoords.x - self.dragObject.indentMousePos.x; // Set the number of indentations the mouse has been moved left or right. var indentDiff = Math.round(xDiff / self.indentAmount * self.rtl); // Indent the row with our estimated diff, which may be further // restricted according to the rows around this row. var indentChange = self.rowObject.indent(indentDiff); // Update table and mouse indentations. self.dragObject.indentMousePos.x += self.indentAmount * indentChange * self.rtl; self.indentCount = Math.max(self.indentCount, self.rowObject.indents); } return false; } }; /** * Mouseup event handler, bound to document. * Blur event handler, bound to drag handle for keyboard support. */ Drupal.tableDrag.prototype.dropRow = function (event, self) { // Drop row functionality shared between mouseup and blur events. if (self.rowObject != null) { var droppedRow = self.rowObject.element; // The row is already in the right place so we just release it. if (self.rowObject.changed == true) { // Update the fields in the dropped row. self.updateFields(droppedRow); // If a setting exists for affecting the entire group, update all the // fields in the entire dragged group. for (var group in self.tableSettings) { var rowSettings = self.rowSettings(group, droppedRow); if (rowSettings.relationship == 'group') { for (var n in self.rowObject.children) { self.updateField(self.rowObject.children[n], group); } } } self.rowObject.markChanged(); if (self.changed == false) { $(Drupal.theme('tableDragChangedWarning')).insertBefore(self.table).hide().fadeIn('slow'); self.changed = true; } } if (self.indentEnabled) { self.rowObject.removeIndentClasses(); } if (self.oldRowElement) { $(self.oldRowElement).removeClass('drag-previous'); } $(droppedRow).removeClass('drag').addClass('drag-previous'); self.oldRowElement = droppedRow; self.onDrop(); self.rowObject = null; } // Functionality specific only to mouseup event. if (self.dragObject != null) { $('.tabledrag-handle', droppedRow).removeClass('tabledrag-handle-hover'); self.dragObject = null; $('body').removeClass('drag'); clearInterval(self.scrollInterval); // Hack for IE6 that flickers uncontrollably if select lists are moved. if (navigator.userAgent.indexOf('MSIE 6.') != -1) { $('select', this.table).css('display', 'block'); } } }; /** * Get the mouse coordinates from the event (allowing for browser differences). */ Drupal.tableDrag.prototype.mouseCoords = function (event) { if (event.pageX || event.pageY) { return { x: event.pageX, y: event.pageY }; } return { x: event.clientX + document.body.scrollLeft - document.body.clientLeft, y: event.clientY + document.body.scrollTop - document.body.clientTop }; }; /** * Given a target element and a mouse event, get the mouse offset from that * element. To do this we need the element's position and the mouse position. */ Drupal.tableDrag.prototype.getMouseOffset = function (target, event) { var docPos = $(target).offset(); var mousePos = this.mouseCoords(event); return { x: mousePos.x - docPos.left, y: mousePos.y - docPos.top }; }; /** * Find the row the mouse is currently over. This row is then taken and swapped * with the one being dragged. * * @param x * The x coordinate of the mouse on the page (not the screen). * @param y * The y coordinate of the mouse on the page (not the screen). */ Drupal.tableDrag.prototype.findDropTargetRow = function (x, y) { var rows = $(this.table.tBodies[0].rows).not(':hidden'); for (var n = 0; n < rows.length; n++) { var row = rows[n]; var indentDiff = 0; var rowY = $(row).offset().top; // Because Safari does not report offsetHeight on table rows, but does on // table cells, grab the firstChild of the row and use that instead. // http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari. if (row.offsetHeight == 0) { var rowHeight = parseInt(row.firstChild.offsetHeight, 10) / 2; } // Other browsers. else { var rowHeight = parseInt(row.offsetHeight, 10) / 2; } // Because we always insert before, we need to offset the height a bit. if ((y > (rowY - rowHeight)) && (y < (rowY + rowHeight))) { if (this.indentEnabled) { // Check that this row is not a child of the row being dragged. for (var n in this.rowObject.group) { if (this.rowObject.group[n] == row) { return null; } } } else { // Do not allow a row to be swapped with itself. if (row == this.rowObject.element) { return null; } } // Check that swapping with this row is allowed. if (!this.rowObject.isValidSwap(row)) { return null; } // We may have found the row the mouse just passed over, but it doesn't // take into account hidden rows. Skip backwards until we find a draggable // row. while ($(row).is(':hidden') && $(row).prev('tr').is(':hidden')) { row = $(row).prev('tr').get(0); } return row; } } return null; }; /** * After the row is dropped, update the table fields according to the settings * set for this table. * * @param changedRow * DOM object for the row that was just dropped. */ Drupal.tableDrag.prototype.updateFields = function (changedRow) { for (var group in this.tableSettings) { // Each group may have a different setting for relationship, so we find // the source rows for each separately. this.updateField(changedRow, group); } }; /** * After the row is dropped, update a single table field according to specific * settings. * * @param changedRow * DOM object for the row that was just dropped. * @param group * The settings group on which field updates will occur. */ Drupal.tableDrag.prototype.updateField = function (changedRow, group) { var rowSettings = this.rowSettings(group, changedRow); // Set the row as its own target. if (rowSettings.relationship == 'self' || rowSettings.relationship == 'group') { var sourceRow = changedRow; } // Siblings are easy, check previous and next rows. else if (rowSettings.relationship == 'sibling') { var previousRow = $(changedRow).prev('tr').get(0); var nextRow = $(changedRow).next('tr').get(0); var sourceRow = changedRow; if ($(previousRow).is('.draggable') && $('.' + group, previousRow).length) { if (this.indentEnabled) { if ($('.indentations', previousRow).length == $('.indentations', changedRow)) { sourceRow = previousRow; } } else { sourceRow = previousRow; } } else if ($(nextRow).is('.draggable') && $('.' + group, nextRow).length) { if (this.indentEnabled) { if ($('.indentations', nextRow).length == $('.indentations', changedRow)) { sourceRow = nextRow; } } else { sourceRow = nextRow; } } } // Parents, look up the tree until we find a field not in this group. // Go up as many parents as indentations in the changed row. else if (rowSettings.relationship == 'parent') { var previousRow = $(changedRow).prev('tr'); while (previousRow.length && $('.indentation', previousRow).length >= this.rowObject.indents) { previousRow = previousRow.prev('tr'); } // If we found a row. if (previousRow.length) { sourceRow = previousRow[0]; } // Otherwise we went all the way to the left of the table without finding // a parent, meaning this item has been placed at the root level. else { // Use the first row in the table as source, because it's guaranteed to // be at the root level. Find the first item, then compare this row // against it as a sibling. sourceRow = $(this.table).find('tr.draggable:first').get(0); if (sourceRow == this.rowObject.element) { sourceRow = $(this.rowObject.group[this.rowObject.group.length - 1]).next('tr.draggable').get(0); } var useSibling = true; } } // Because we may have moved the row from one category to another, // take a look at our sibling and borrow its sources and targets. this.copyDragClasses(sourceRow, changedRow, group); rowSettings = this.rowSettings(group, changedRow); // In the case that we're looking for a parent, but the row is at the top // of the tree, copy our sibling's values. if (useSibling) { rowSettings.relationship = 'sibling'; rowSettings.source = rowSettings.target; } var targetClass = '.' + rowSettings.target; var targetElement = $(targetClass, changedRow).get(0); // Check if a target element exists in this row. if (targetElement) { var sourceClass = '.' + rowSettings.source; var sourceElement = $(sourceClass, sourceRow).get(0); switch (rowSettings.action) { case 'depth': // Get the depth of the target row. targetElement.value = $('.indentation', $(sourceElement).closest('tr')).length; break; case 'match': // Update the value. targetElement.value = sourceElement.value; break; case 'order': var siblings = this.rowObject.findSiblings(rowSettings); if ($(targetElement).is('select')) { // Get a list of acceptable values. var values = []; $('option', targetElement).each(function () { values.push(this.value); }); var maxVal = values[values.length - 1]; // Populate the values in the siblings. $(targetClass, siblings).each(function () { // If there are more items than possible values, assign the maximum value to the row. if (values.length > 0) { this.value = values.shift(); } else { this.value = maxVal; } }); } else { // Assume a numeric input field. var weight = parseInt($(targetClass, siblings[0]).val(), 10) || 0; $(targetClass, siblings).each(function () { this.value = weight; weight++; }); } break; } } }; /** * Copy all special tableDrag classes from one row's form elements to a * different one, removing any special classes that the destination row * may have had. */ Drupal.tableDrag.prototype.copyDragClasses = function (sourceRow, targetRow, group) { var sourceElement = $('.' + group, sourceRow); var targetElement = $('.' + group, targetRow); if (sourceElement.length && targetElement.length) { targetElement[0].className = sourceElement[0].className; } }; Drupal.tableDrag.prototype.checkScroll = function (cursorY) { var de = document.documentElement; var b = document.body; var windowHeight = this.windowHeight = window.innerHeight || (de.clientHeight && de.clientWidth != 0 ? de.clientHeight : b.offsetHeight); var scrollY = this.scrollY = (document.all ? (!de.scrollTop ? b.scrollTop : de.scrollTop) : (window.pageYOffset ? window.pageYOffset : window.scrollY)); var trigger = this.scrollSettings.trigger; var delta = 0; // Return a scroll speed relative to the edge of the screen. if (cursorY - scrollY > windowHeight - trigger) { delta = trigger / (windowHeight + scrollY - cursorY); delta = (delta > 0 && delta < trigger) ? delta : trigger; return delta * this.scrollSettings.amount; } else if (cursorY - scrollY < trigger) { delta = trigger / (cursorY - scrollY); delta = (delta > 0 && delta < trigger) ? delta : trigger; return -delta * this.scrollSettings.amount; } }; Drupal.tableDrag.prototype.setScroll = function (scrollAmount) { var self = this; this.scrollInterval = setInterval(function () { // Update the scroll values stored in the object. self.checkScroll(self.currentMouseCoords.y); var aboveTable = self.scrollY > self.table.topY; var belowTable = self.scrollY + self.windowHeight < self.table.bottomY; if (scrollAmount > 0 && belowTable || scrollAmount < 0 && aboveTable) { window.scrollBy(0, scrollAmount); } }, this.scrollSettings.interval); }; Drupal.tableDrag.prototype.restripeTable = function () { // :even and :odd are reversed because jQuery counts from 0 and // we count from 1, so we're out of sync. // Match immediate children of the parent element to allow nesting. $('> tbody > tr.draggable:visible, > tr.draggable:visible', this.table) .removeClass('odd even') .filter(':odd').addClass('even').end() .filter(':even').addClass('odd'); }; /** * Stub function. Allows a custom handler when a row begins dragging. */ Drupal.tableDrag.prototype.onDrag = function () { return null; }; /** * Stub function. Allows a custom handler when a row is dropped. */ Drupal.tableDrag.prototype.onDrop = function () { return null; }; /** * Constructor to make a new object to manipulate a table row. * * @param tableRow * The DOM element for the table row we will be manipulating. * @param method * The method in which this row is being moved. Either 'keyboard' or 'mouse'. * @param indentEnabled * Whether the containing table uses indentations. Used for optimizations. * @param maxDepth * The maximum amount of indentations this row may contain. * @param addClasses * Whether we want to add classes to this row to indicate child relationships. */ Drupal.tableDrag.prototype.row = function (tableRow, method, indentEnabled, maxDepth, addClasses) { this.element = tableRow; this.method = method; this.group = [tableRow]; this.groupDepth = $('.indentation', tableRow).length; this.changed = false; this.table = $(tableRow).closest('table').get(0); this.indentEnabled = indentEnabled; this.maxDepth = maxDepth; this.direction = ''; // Direction the row is being moved. if (this.indentEnabled) { this.indents = $('.indentation', tableRow).length; this.children = this.findChildren(addClasses); this.group = $.merge(this.group, this.children); // Find the depth of this entire group. for (var n = 0; n < this.group.length; n++) { this.groupDepth = Math.max($('.indentation', this.group[n]).length, this.groupDepth); } } }; /** * Find all children of rowObject by indentation. * * @param addClasses * Whether we want to add classes to this row to indicate child relationships. */ Drupal.tableDrag.prototype.row.prototype.findChildren = function (addClasses) { var parentIndentation = this.indents; var currentRow = $(this.element, this.table).next('tr.draggable'); var rows = []; var child = 0; while (currentRow.length) { var rowIndentation = $('.indentation', currentRow).length; // A greater indentation indicates this is a child. if (rowIndentation > parentIndentation) { child++; rows.push(currentRow[0]); if (addClasses) { $('.indentation', currentRow).each(function (indentNum) { if (child == 1 && (indentNum == parentIndentation)) { $(this).addClass('tree-child-first'); } if (indentNum == parentIndentation) { $(this).addClass('tree-child'); } else if (indentNum > parentIndentation) { $(this).addClass('tree-child-horizontal'); } }); } } else { break; } currentRow = currentRow.next('tr.draggable'); } if (addClasses && rows.length) { $('.indentation:nth-child(' + (parentIndentation + 1) + ')', rows[rows.length - 1]).addClass('tree-child-last'); } return rows; }; /** * Ensure that two rows are allowed to be swapped. * * @param row * DOM object for the row being considered for swapping. */ Drupal.tableDrag.prototype.row.prototype.isValidSwap = function (row) { if (this.indentEnabled) { var prevRow, nextRow; if (this.direction == 'down') { prevRow = row; nextRow = $(row).next('tr').get(0); } else { prevRow = $(row).prev('tr').get(0); nextRow = row; } this.interval = this.validIndentInterval(prevRow, nextRow); // We have an invalid swap if the valid indentations interval is empty. if (this.interval.min > this.interval.max) { return false; } } // Do not let an un-draggable first row have anything put before it. if (this.table.tBodies[0].rows[0] == row && $(row).is(':not(.draggable)')) { return false; } return true; }; /** * Perform the swap between two rows. * * @param position * Whether the swap will occur 'before' or 'after' the given row. * @param row * DOM element what will be swapped with the row group. */ Drupal.tableDrag.prototype.row.prototype.swap = function (position, row) { Drupal.detachBehaviors(this.group, Drupal.settings, 'move'); $(row)[position](this.group); Drupal.attachBehaviors(this.group, Drupal.settings); this.changed = true; this.onSwap(row); }; /** * Determine the valid indentations interval for the row at a given position * in the table. * * @param prevRow * DOM object for the row before the tested position * (or null for first position in the table). * @param nextRow * DOM object for the row after the tested position * (or null for last position in the table). */ Drupal.tableDrag.prototype.row.prototype.validIndentInterval = function (prevRow, nextRow) { var minIndent, maxIndent; // Minimum indentation: // Do not orphan the next row. minIndent = nextRow ? $('.indentation', nextRow).length : 0; // Maximum indentation: if (!prevRow || $(prevRow).is(':not(.draggable)') || $(this.element).is('.tabledrag-root')) { // Do not indent: // - the first row in the table, // - rows dragged below a non-draggable row, // - 'root' rows. maxIndent = 0; } else { // Do not go deeper than as a child of the previous row. maxIndent = $('.indentation', prevRow).length + ($(prevRow).is('.tabledrag-leaf') ? 0 : 1); // Limit by the maximum allowed depth for the table. if (this.maxDepth) { maxIndent = Math.min(maxIndent, this.maxDepth - (this.groupDepth - this.indents)); } } return { 'min': minIndent, 'max': maxIndent }; }; /** * Indent a row within the legal bounds of the table. * * @param indentDiff * The number of additional indentations proposed for the row (can be * positive or negative). This number will be adjusted to nearest valid * indentation level for the row. */ Drupal.tableDrag.prototype.row.prototype.indent = function (indentDiff) { // Determine the valid indentations interval if not available yet. if (!this.interval) { var prevRow = $(this.element).prev('tr').get(0); var nextRow = $(this.group).filter(':last').next('tr').get(0); this.interval = this.validIndentInterval(prevRow, nextRow); } // Adjust to the nearest valid indentation. var indent = this.indents + indentDiff; indent = Math.max(indent, this.interval.min); indent = Math.min(indent, this.interval.max); indentDiff = indent - this.indents; for (var n = 1; n <= Math.abs(indentDiff); n++) { // Add or remove indentations. if (indentDiff < 0) { $('.indentation:first', this.group).remove(); this.indents--; } else { $('td:first', this.group).prepend(Drupal.theme('tableDragIndentation')); this.indents++; } } if (indentDiff) { // Update indentation for this row. this.changed = true; this.groupDepth += indentDiff; this.onIndent(); } return indentDiff; }; /** * Find all siblings for a row, either according to its subgroup or indentation. * Note that the passed-in row is included in the list of siblings. * * @param settings * The field settings we're using to identify what constitutes a sibling. */ Drupal.tableDrag.prototype.row.prototype.findSiblings = function (rowSettings) { var siblings = []; var directions = ['prev', 'next']; var rowIndentation = this.indents; for (var d = 0; d < directions.length; d++) { var checkRow = $(this.element)[directions[d]](); while (checkRow.length) { // Check that the sibling contains a similar target field. if ($('.' + rowSettings.target, checkRow)) { // Either add immediately if this is a flat table, or check to ensure // that this row has the same level of indentation. if (this.indentEnabled) { var checkRowIndentation = $('.indentation', checkRow).length; } if (!(this.indentEnabled) || (checkRowIndentation == rowIndentation)) { siblings.push(checkRow[0]); } else if (checkRowIndentation < rowIndentation) { // No need to keep looking for siblings when we get to a parent. break; } } else { break; } checkRow = $(checkRow)[directions[d]](); } // Since siblings are added in reverse order for previous, reverse the // completed list of previous siblings. Add the current row and continue. if (directions[d] == 'prev') { siblings.reverse(); siblings.push(this.element); } } return siblings; }; /** * Remove indentation helper classes from the current row group. */ Drupal.tableDrag.prototype.row.prototype.removeIndentClasses = function () { for (var n in this.children) { $('.indentation', this.children[n]) .removeClass('tree-child') .removeClass('tree-child-first') .removeClass('tree-child-last') .removeClass('tree-child-horizontal'); } }; /** * Add an asterisk or other marker to the changed row. */ Drupal.tableDrag.prototype.row.prototype.markChanged = function () { var marker = Drupal.theme('tableDragChangedMarker'); var cell = $('td:first', this.element); if ($('span.tabledrag-changed', cell).length == 0) { cell.append(marker); } }; /** * Stub function. Allows a custom handler when a row is indented. */ Drupal.tableDrag.prototype.row.prototype.onIndent = function () { return null; }; /** * Stub function. Allows a custom handler when a row is swapped. */ Drupal.tableDrag.prototype.row.prototype.onSwap = function (swappedRow) { return null; }; Drupal.theme.prototype.tableDragChangedMarker = function () { return '<span class="warning tabledrag-changed">*</span>'; }; Drupal.theme.prototype.tableDragIndentation = function () { return '<div class="indentation">&nbsp;</div>'; }; Drupal.theme.prototype.tableDragChangedWarning = function () { return '<div class="tabledrag-changed-warning messages warning">' + Drupal.theme('tableDragChangedMarker') + ' ' + Drupal.t('Changes made in this table will not be saved until the form is submitted.') + '</div>'; }; })(jQuery);
JavaScript
(function ($) { Drupal.behaviors.textarea = { attach: function (context, settings) { $('.form-textarea-wrapper.resizable', context).once('textarea', function () { var staticOffset = null; var textarea = $(this).addClass('resizable-textarea').find('textarea'); var grippie = $('<div class="grippie"></div>').mousedown(startDrag); grippie.insertAfter(textarea); function startDrag(e) { staticOffset = textarea.height() - e.pageY; textarea.css('opacity', 0.25); $(document).mousemove(performDrag).mouseup(endDrag); return false; } function performDrag(e) { textarea.height(Math.max(32, staticOffset + e.pageY) + 'px'); return false; } function endDrag(e) { $(document).unbind('mousemove', performDrag).unbind('mouseup', endDrag); textarea.css('opacity', 1); } }); } }; })(jQuery);
JavaScript
(function ($) { /** * Toggle the visibility of a fieldset using smooth animations. */ Drupal.toggleFieldset = function (fieldset) { var $fieldset = $(fieldset); if ($fieldset.is('.collapsed')) { var $content = $('> .fieldset-wrapper', fieldset).hide(); $fieldset .removeClass('collapsed') .trigger({ type: 'collapsed', value: false }) .find('> legend span.fieldset-legend-prefix').html(Drupal.t('Hide')); $content.slideDown({ duration: 'fast', easing: 'linear', complete: function () { Drupal.collapseScrollIntoView(fieldset); fieldset.animating = false; }, step: function () { // Scroll the fieldset into view. Drupal.collapseScrollIntoView(fieldset); } }); } else { $fieldset.trigger({ type: 'collapsed', value: true }); $('> .fieldset-wrapper', fieldset).slideUp('fast', function () { $fieldset .addClass('collapsed') .find('> legend span.fieldset-legend-prefix').html(Drupal.t('Show')); fieldset.animating = false; }); } }; /** * Scroll a given fieldset into view as much as possible. */ Drupal.collapseScrollIntoView = function (node) { var h = document.documentElement.clientHeight || document.body.clientHeight || 0; var offset = document.documentElement.scrollTop || document.body.scrollTop || 0; var posY = $(node).offset().top; var fudge = 55; if (posY + node.offsetHeight + fudge > h + offset) { if (node.offsetHeight > h) { window.scrollTo(0, posY); } else { window.scrollTo(0, posY + node.offsetHeight - h + fudge); } } }; Drupal.behaviors.collapse = { attach: function (context, settings) { $('fieldset.collapsible', context).once('collapse', function () { var $fieldset = $(this); // Expand fieldset if there are errors inside, or if it contains an // element that is targeted by the URI fragment identifier. var anchor = location.hash && location.hash != '#' ? ', ' + location.hash : ''; if ($fieldset.find('.error' + anchor).length) { $fieldset.removeClass('collapsed'); } var summary = $('<span class="summary"></span>'); $fieldset. bind('summaryUpdated', function () { var text = $.trim($fieldset.drupalGetSummary()); summary.html(text ? ' (' + text + ')' : ''); }) .trigger('summaryUpdated'); // Turn the legend into a clickable link, but retain span.fieldset-legend // for CSS positioning. var $legend = $('> legend .fieldset-legend', this); $('<span class="fieldset-legend-prefix element-invisible"></span>') .append($fieldset.hasClass('collapsed') ? Drupal.t('Show') : Drupal.t('Hide')) .prependTo($legend) .after(' '); // .wrapInner() does not retain bound events. var $link = $('<a class="fieldset-title" href="#"></a>') .prepend($legend.contents()) .appendTo($legend) .click(function () { var fieldset = $fieldset.get(0); // Don't animate multiple times. if (!fieldset.animating) { fieldset.animating = true; Drupal.toggleFieldset(fieldset); } return false; }); $legend.append(summary); }); } }; })(jQuery);
JavaScript
(function ($) { /** * The base States namespace. * * Having the local states variable allows us to use the States namespace * without having to always declare "Drupal.states". */ var states = Drupal.states = { // An array of functions that should be postponed. postponed: [] }; /** * Attaches the states. */ Drupal.behaviors.states = { attach: function (context, settings) { var $context = $(context); for (var selector in settings.states) { for (var state in settings.states[selector]) { new states.Dependent({ element: $context.find(selector), state: states.State.sanitize(state), constraints: settings.states[selector][state] }); } } // Execute all postponed functions now. while (states.postponed.length) { (states.postponed.shift())(); } } }; /** * Object representing an element that depends on other elements. * * @param args * Object with the following keys (all of which are required): * - element: A jQuery object of the dependent element * - state: A State object describing the state that is dependent * - constraints: An object with dependency specifications. Lists all elements * that this element depends on. It can be nested and can contain arbitrary * AND and OR clauses. */ states.Dependent = function (args) { $.extend(this, { values: {}, oldValue: null }, args); this.dependees = this.getDependees(); for (var selector in this.dependees) { this.initializeDependee(selector, this.dependees[selector]); } }; /** * Comparison functions for comparing the value of an element with the * specification from the dependency settings. If the object type can't be * found in this list, the === operator is used by default. */ states.Dependent.comparisons = { 'RegExp': function (reference, value) { return reference.test(value); }, 'Function': function (reference, value) { // The "reference" variable is a comparison function. return reference(value); }, 'Number': function (reference, value) { // If "reference" is a number and "value" is a string, then cast reference // as a string before applying the strict comparison in compare(). Otherwise // numeric keys in the form's #states array fail to match string values // returned from jQuery's val(). return (typeof value === 'string') ? compare(reference.toString(), value) : compare(reference, value); } }; states.Dependent.prototype = { /** * Initializes one of the elements this dependent depends on. * * @param selector * The CSS selector describing the dependee. * @param dependeeStates * The list of states that have to be monitored for tracking the * dependee's compliance status. */ initializeDependee: function (selector, dependeeStates) { var state; // Cache for the states of this dependee. this.values[selector] = {}; for (var i in dependeeStates) { if (dependeeStates.hasOwnProperty(i)) { state = dependeeStates[i]; // Make sure we're not initializing this selector/state combination twice. if ($.inArray(state, dependeeStates) === -1) { continue; } state = states.State.sanitize(state); // Initialize the value of this state. this.values[selector][state.name] = null; // Monitor state changes of the specified state for this dependee. $(selector).bind('state:' + state, $.proxy(function (e) { this.update(selector, state, e.value); }, this)); // Make sure the event we just bound ourselves to is actually fired. new states.Trigger({ selector: selector, state: state }); } } }, /** * Compares a value with a reference value. * * @param reference * The value used for reference. * @param selector * CSS selector describing the dependee. * @param state * A State object describing the dependee's updated state. * * @return * true or false. */ compare: function (reference, selector, state) { var value = this.values[selector][state.name]; if (reference.constructor.name in states.Dependent.comparisons) { // Use a custom compare function for certain reference value types. return states.Dependent.comparisons[reference.constructor.name](reference, value); } else { // Do a plain comparison otherwise. return compare(reference, value); } }, /** * Update the value of a dependee's state. * * @param selector * CSS selector describing the dependee. * @param state * A State object describing the dependee's updated state. * @param value * The new value for the dependee's updated state. */ update: function (selector, state, value) { // Only act when the 'new' value is actually new. if (value !== this.values[selector][state.name]) { this.values[selector][state.name] = value; this.reevaluate(); } }, /** * Triggers change events in case a state changed. */ reevaluate: function () { // Check whether any constraint for this dependent state is satisifed. var value = this.verifyConstraints(this.constraints); // Only invoke a state change event when the value actually changed. if (value !== this.oldValue) { // Store the new value so that we can compare later whether the value // actually changed. this.oldValue = value; // Normalize the value to match the normalized state name. value = invert(value, this.state.invert); // By adding "trigger: true", we ensure that state changes don't go into // infinite loops. this.element.trigger({ type: 'state:' + this.state, value: value, trigger: true }); } }, /** * Evaluates child constraints to determine if a constraint is satisfied. * * @param constraints * A constraint object or an array of constraints. * @param selector * The selector for these constraints. If undefined, there isn't yet a * selector that these constraints apply to. In that case, the keys of the * object are interpreted as the selector if encountered. * * @return * true or false, depending on whether these constraints are satisfied. */ verifyConstraints: function(constraints, selector) { var result; if ($.isArray(constraints)) { // This constraint is an array (OR or XOR). var hasXor = $.inArray('xor', constraints) === -1; for (var i = 0, len = constraints.length; i < len; i++) { if (constraints[i] != 'xor') { var constraint = this.checkConstraints(constraints[i], selector, i); // Return if this is OR and we have a satisfied constraint or if this // is XOR and we have a second satisfied constraint. if (constraint && (hasXor || result)) { return hasXor; } result = result || constraint; } } } // Make sure we don't try to iterate over things other than objects. This // shouldn't normally occur, but in case the condition definition is bogus, // we don't want to end up with an infinite loop. else if ($.isPlainObject(constraints)) { // This constraint is an object (AND). for (var n in constraints) { if (constraints.hasOwnProperty(n)) { result = ternary(result, this.checkConstraints(constraints[n], selector, n)); // False and anything else will evaluate to false, so return when any // false condition is found. if (result === false) { return false; } } } } return result; }, /** * Checks whether the value matches the requirements for this constraint. * * @param value * Either the value of a state or an array/object of constraints. In the * latter case, resolving the constraint continues. * @param selector * The selector for this constraint. If undefined, there isn't yet a * selector that this constraint applies to. In that case, the state key is * propagates to a selector and resolving continues. * @param state * The state to check for this constraint. If undefined, resolving * continues. * If both selector and state aren't undefined and valid non-numeric * strings, a lookup for the actual value of that selector's state is * performed. This parameter is not a State object but a pristine state * string. * * @return * true or false, depending on whether this constraint is satisfied. */ checkConstraints: function(value, selector, state) { // Normalize the last parameter. If it's non-numeric, we treat it either as // a selector (in case there isn't one yet) or as a trigger/state. if (typeof state !== 'string' || (/[0-9]/).test(state[0])) { state = null; } else if (typeof selector === 'undefined') { // Propagate the state to the selector when there isn't one yet. selector = state; state = null; } if (state !== null) { // constraints is the actual constraints of an element to check for. state = states.State.sanitize(state); return invert(this.compare(value, selector, state), state.invert); } else { // Resolve this constraint as an AND/OR operator. return this.verifyConstraints(value, selector); } }, /** * Gathers information about all required triggers. */ getDependees: function() { var cache = {}; // Swivel the lookup function so that we can record all available selector- // state combinations for initialization. var _compare = this.compare; this.compare = function(reference, selector, state) { (cache[selector] || (cache[selector] = [])).push(state.name); // Return nothing (=== undefined) so that the constraint loops are not // broken. }; // This call doesn't actually verify anything but uses the resolving // mechanism to go through the constraints array, trying to look up each // value. Since we swivelled the compare function, this comparison returns // undefined and lookup continues until the very end. Instead of lookup up // the value, we record that combination of selector and state so that we // can initialize all triggers. this.verifyConstraints(this.constraints); // Restore the original function. this.compare = _compare; return cache; } }; states.Trigger = function (args) { $.extend(this, args); if (this.state in states.Trigger.states) { this.element = $(this.selector); // Only call the trigger initializer when it wasn't yet attached to this // element. Otherwise we'd end up with duplicate events. if (!this.element.data('trigger:' + this.state)) { this.initialize(); } } }; states.Trigger.prototype = { initialize: function () { var trigger = states.Trigger.states[this.state]; if (typeof trigger == 'function') { // We have a custom trigger initialization function. trigger.call(window, this.element); } else { for (var event in trigger) { if (trigger.hasOwnProperty(event)) { this.defaultTrigger(event, trigger[event]); } } } // Mark this trigger as initialized for this element. this.element.data('trigger:' + this.state, true); }, defaultTrigger: function (event, valueFn) { var oldValue = valueFn.call(this.element); // Attach the event callback. this.element.bind(event, $.proxy(function (e) { var value = valueFn.call(this.element, e); // Only trigger the event if the value has actually changed. if (oldValue !== value) { this.element.trigger({ type: 'state:' + this.state, value: value, oldValue: oldValue }); oldValue = value; } }, this)); states.postponed.push($.proxy(function () { // Trigger the event once for initialization purposes. this.element.trigger({ type: 'state:' + this.state, value: oldValue, oldValue: null }); }, this)); } }; /** * This list of states contains functions that are used to monitor the state * of an element. Whenever an element depends on the state of another element, * one of these trigger functions is added to the dependee so that the * dependent element can be updated. */ states.Trigger.states = { // 'empty' describes the state to be monitored empty: { // 'keyup' is the (native DOM) event that we watch for. 'keyup': function () { // The function associated to that trigger returns the new value for the // state. return this.val() == ''; } }, checked: { 'change': function () { return this.attr('checked'); } }, // For radio buttons, only return the value if the radio button is selected. value: { 'keyup': function () { // Radio buttons share the same :input[name="key"] selector. if (this.length > 1) { // Initial checked value of radios is undefined, so we return false. return this.filter(':checked').val() || false; } return this.val(); }, 'change': function () { // Radio buttons share the same :input[name="key"] selector. if (this.length > 1) { // Initial checked value of radios is undefined, so we return false. return this.filter(':checked').val() || false; } return this.val(); } }, collapsed: { 'collapsed': function(e) { return (typeof e !== 'undefined' && 'value' in e) ? e.value : this.is('.collapsed'); } } }; /** * A state object is used for describing the state and performing aliasing. */ states.State = function(state) { // We may need the original unresolved name later. this.pristine = this.name = state; // Normalize the state name. while (true) { // Iteratively remove exclamation marks and invert the value. while (this.name.charAt(0) == '!') { this.name = this.name.substring(1); this.invert = !this.invert; } // Replace the state with its normalized name. if (this.name in states.State.aliases) { this.name = states.State.aliases[this.name]; } else { break; } } }; /** * Creates a new State object by sanitizing the passed value. */ states.State.sanitize = function (state) { if (state instanceof states.State) { return state; } else { return new states.State(state); } }; /** * This list of aliases is used to normalize states and associates negated names * with their respective inverse state. */ states.State.aliases = { 'enabled': '!disabled', 'invisible': '!visible', 'invalid': '!valid', 'untouched': '!touched', 'optional': '!required', 'filled': '!empty', 'unchecked': '!checked', 'irrelevant': '!relevant', 'expanded': '!collapsed', 'readwrite': '!readonly' }; states.State.prototype = { invert: false, /** * Ensures that just using the state object returns the name. */ toString: function() { return this.name; } }; /** * Global state change handlers. These are bound to "document" to cover all * elements whose state changes. Events sent to elements within the page * bubble up to these handlers. We use this system so that themes and modules * can override these state change handlers for particular parts of a page. */ $(document).bind('state:disabled', function(e) { // Only act when this change was triggered by a dependency and not by the // element monitoring itself. if (e.trigger) { $(e.target) .attr('disabled', e.value) .closest('.form-item, .form-submit, .form-wrapper').toggleClass('form-disabled', e.value) .find('select, input, textarea').attr('disabled', e.value); // Note: WebKit nightlies don't reflect that change correctly. // See https://bugs.webkit.org/show_bug.cgi?id=23789 } }); $(document).bind('state:required', function(e) { if (e.trigger) { if (e.value) { $(e.target).closest('.form-item, .form-wrapper').find('label').append('<span class="form-required">*</span>'); } else { $(e.target).closest('.form-item, .form-wrapper').find('label .form-required').remove(); } } }); $(document).bind('state:visible', function(e) { if (e.trigger) { $(e.target).closest('.form-item, .form-submit, .form-wrapper').toggle(e.value); } }); $(document).bind('state:checked', function(e) { if (e.trigger) { $(e.target).attr('checked', e.value); } }); $(document).bind('state:collapsed', function(e) { if (e.trigger) { if ($(e.target).is('.collapsed') !== e.value) { $('> legend a', e.target).click(); } } }); /** * These are helper functions implementing addition "operators" and don't * implement any logic that is particular to states. */ // Bitwise AND with a third undefined state. function ternary (a, b) { return typeof a === 'undefined' ? b : (typeof b === 'undefined' ? a : a && b); } // Inverts a (if it's not undefined) when invert is true. function invert (a, invert) { return (invert && typeof a !== 'undefined') ? !a : a; } // Compares two values while ignoring undefined values. function compare (a, b) { return (a === b) ? (typeof a === 'undefined' ? a : true) : (typeof a === 'undefined' || typeof b === 'undefined'); } })(jQuery);
JavaScript
(function ($) { /** * Attaches the batch behavior to progress bars. */ Drupal.behaviors.batch = { attach: function (context, settings) { $('#progress', context).once('batch', function () { var holder = $(this); // Success: redirect to the summary. var updateCallback = function (progress, status, pb) { if (progress == 100) { pb.stopMonitoring(); window.location = settings.batch.uri + '&op=finished'; } }; var errorCallback = function (pb) { holder.prepend($('<p class="error"></p>').html(settings.batch.errorMessage)); $('#wait').hide(); }; var progress = new Drupal.progressBar('updateprogress', updateCallback, 'POST', errorCallback); progress.setProgress(-1, settings.batch.initMessage); holder.append(progress.element); progress.startMonitoring(settings.batch.uri + '&op=do', 10); }); } }; })(jQuery);
JavaScript
(function ($) { /** * Set the client's system time zone as default values of form fields. */ Drupal.behaviors.setTimezone = { attach: function (context, settings) { $('select.timezone-detect', context).once('timezone', function () { var dateString = Date(); // In some client environments, date strings include a time zone // abbreviation, between 3 and 5 letters enclosed in parentheses, // which can be interpreted by PHP. var matches = dateString.match(/\(([A-Z]{3,5})\)/); var abbreviation = matches ? matches[1] : 0; // For all other client environments, the abbreviation is set to "0" // and the current offset from UTC and daylight saving time status are // used to guess the time zone. var dateNow = new Date(); var offsetNow = dateNow.getTimezoneOffset() * -60; // Use January 1 and July 1 as test dates for determining daylight // saving time status by comparing their offsets. var dateJan = new Date(dateNow.getFullYear(), 0, 1, 12, 0, 0, 0); var dateJul = new Date(dateNow.getFullYear(), 6, 1, 12, 0, 0, 0); var offsetJan = dateJan.getTimezoneOffset() * -60; var offsetJul = dateJul.getTimezoneOffset() * -60; var isDaylightSavingTime; // If the offset from UTC is identical on January 1 and July 1, // assume daylight saving time is not used in this time zone. if (offsetJan == offsetJul) { isDaylightSavingTime = ''; } // If the maximum annual offset is equivalent to the current offset, // assume daylight saving time is in effect. else if (Math.max(offsetJan, offsetJul) == offsetNow) { isDaylightSavingTime = 1; } // Otherwise, assume daylight saving time is not in effect. else { isDaylightSavingTime = 0; } // Submit request to the system/timezone callback and set the form field // to the response time zone. The client date is passed to the callback // for debugging purposes. Submit a synchronous request to avoid database // errors associated with concurrent requests during install. var path = 'system/timezone/' + abbreviation + '/' + offsetNow + '/' + isDaylightSavingTime; var element = this; $.ajax({ async: false, url: settings.basePath, data: { q: path, date: dateString }, dataType: 'json', success: function (data) { if (data) { $(element).val(data); } } }); }); } }; })(jQuery);
JavaScript
(function ($) { /** * Retrieves the summary for the first element. */ $.fn.drupalGetSummary = function () { var callback = this.data('summaryCallback'); return (this[0] && callback) ? $.trim(callback(this[0])) : ''; }; /** * Sets the summary for all matched elements. * * @param callback * Either a function that will be called each time the summary is * retrieved or a string (which is returned each time). */ $.fn.drupalSetSummary = function (callback) { var self = this; // To facilitate things, the callback should always be a function. If it's // not, we wrap it into an anonymous function which just returns the value. if (typeof callback != 'function') { var val = callback; callback = function () { return val; }; } return this .data('summaryCallback', callback) // To prevent duplicate events, the handlers are first removed and then // (re-)added. .unbind('formUpdated.summary') .bind('formUpdated.summary', function () { self.trigger('summaryUpdated'); }) // The actual summaryUpdated handler doesn't fire when the callback is // changed, so we have to do this manually. .trigger('summaryUpdated'); }; /** * Sends a 'formUpdated' event each time a form element is modified. */ Drupal.behaviors.formUpdated = { attach: function (context) { // These events are namespaced so that we can remove them later. var events = 'change.formUpdated click.formUpdated blur.formUpdated keyup.formUpdated'; $(context) // Since context could be an input element itself, it's added back to // the jQuery object and filtered again. .find(':input').andSelf().filter(':input') // To prevent duplicate events, the handlers are first removed and then // (re-)added. .unbind(events).bind(events, function () { $(this).trigger('formUpdated'); }); } }; /** * Prepopulate form fields with information from the visitor cookie. */ Drupal.behaviors.fillUserInfoFromCookie = { attach: function (context, settings) { $('form.user-info-from-cookie').once('user-info-from-cookie', function () { var formContext = this; $.each(['name', 'mail', 'homepage'], function () { var $element = $('[name=' + this + ']', formContext); var cookie = $.cookie('Drupal.visitor.' + this); if ($element.length && cookie) { $element.val(cookie); } }); }); } }; })(jQuery);
JavaScript
var Drupal = Drupal || { 'settings': {}, 'behaviors': {}, 'locale': {} }; // Allow other JavaScript libraries to use $. jQuery.noConflict(); (function ($) { /** * Override jQuery.fn.init to guard against XSS attacks. * * See http://bugs.jquery.com/ticket/9521 */ var jquery_init = $.fn.init; $.fn.init = function (selector, context, rootjQuery) { // If the string contains a "#" before a "<", treat it as invalid HTML. if (selector && typeof selector === 'string') { var hash_position = selector.indexOf('#'); if (hash_position >= 0) { var bracket_position = selector.indexOf('<'); if (bracket_position > hash_position) { throw 'Syntax error, unrecognized expression: ' + selector; } } } return jquery_init.call(this, selector, context, rootjQuery); }; $.fn.init.prototype = jquery_init.prototype; /** * Attach all registered behaviors to a page element. * * Behaviors are event-triggered actions that attach to page elements, enhancing * default non-JavaScript UIs. Behaviors are registered in the Drupal.behaviors * object using the method 'attach' and optionally also 'detach' as follows: * @code * Drupal.behaviors.behaviorName = { * attach: function (context, settings) { * ... * }, * detach: function (context, settings, trigger) { * ... * } * }; * @endcode * * Drupal.attachBehaviors is added below to the jQuery ready event and so * runs on initial page load. Developers implementing AHAH/Ajax in their * solutions should also call this function after new page content has been * loaded, feeding in an element to be processed, in order to attach all * behaviors to the new content. * * Behaviors should use * @code * $(selector).once('behavior-name', function () { * ... * }); * @endcode * to ensure the behavior is attached only once to a given element. (Doing so * enables the reprocessing of given elements, which may be needed on occasion * despite the ability to limit behavior attachment to a particular element.) * * @param context * An element to attach behaviors to. If none is given, the document element * is used. * @param settings * An object containing settings for the current context. If none given, the * global Drupal.settings object is used. */ Drupal.attachBehaviors = function (context, settings) { context = context || document; settings = settings || Drupal.settings; // Execute all of them. $.each(Drupal.behaviors, function () { if ($.isFunction(this.attach)) { this.attach(context, settings); } }); }; /** * Detach registered behaviors from a page element. * * Developers implementing AHAH/Ajax in their solutions should call this * function before page content is about to be removed, feeding in an element * to be processed, in order to allow special behaviors to detach from the * content. * * Such implementations should look for the class name that was added in their * corresponding Drupal.behaviors.behaviorName.attach implementation, i.e. * behaviorName-processed, to ensure the behavior is detached only from * previously processed elements. * * @param context * An element to detach behaviors from. If none is given, the document element * is used. * @param settings * An object containing settings for the current context. If none given, the * global Drupal.settings object is used. * @param trigger * A string containing what's causing the behaviors to be detached. The * possible triggers are: * - unload: (default) The context element is being removed from the DOM. * - move: The element is about to be moved within the DOM (for example, * during a tabledrag row swap). After the move is completed, * Drupal.attachBehaviors() is called, so that the behavior can undo * whatever it did in response to the move. Many behaviors won't need to * do anything simply in response to the element being moved, but because * IFRAME elements reload their "src" when being moved within the DOM, * behaviors bound to IFRAME elements (like WYSIWYG editors) may need to * take some action. * - serialize: When an Ajax form is submitted, this is called with the * form as the context. This provides every behavior within the form an * opportunity to ensure that the field elements have correct content * in them before the form is serialized. The canonical use-case is so * that WYSIWYG editors can update the hidden textarea to which they are * bound. * * @see Drupal.attachBehaviors */ Drupal.detachBehaviors = function (context, settings, trigger) { context = context || document; settings = settings || Drupal.settings; trigger = trigger || 'unload'; // Execute all of them. $.each(Drupal.behaviors, function () { if ($.isFunction(this.detach)) { this.detach(context, settings, trigger); } }); }; /** * Encode special characters in a plain-text string for display as HTML. * * @ingroup sanitization */ Drupal.checkPlain = function (str) { var character, regex, replace = { '&': '&amp;', '"': '&quot;', '<': '&lt;', '>': '&gt;' }; str = String(str); for (character in replace) { if (replace.hasOwnProperty(character)) { regex = new RegExp(character, 'g'); str = str.replace(regex, replace[character]); } } return str; }; /** * Replace placeholders with sanitized values in a string. * * @param str * A string with placeholders. * @param args * An object of replacements pairs to make. Incidences of any key in this * array are replaced with the corresponding value. Based on the first * character of the key, the value is escaped and/or themed: * - !variable: inserted as is * - @variable: escape plain text to HTML (Drupal.checkPlain) * - %variable: escape text and theme as a placeholder for user-submitted * content (checkPlain + Drupal.theme('placeholder')) * * @see Drupal.t() * @ingroup sanitization */ Drupal.formatString = function(str, args) { // Transform arguments before inserting them. for (var key in args) { switch (key.charAt(0)) { // Escaped only. case '@': args[key] = Drupal.checkPlain(args[key]); break; // Pass-through. case '!': break; // Escaped and placeholder. case '%': default: args[key] = Drupal.theme('placeholder', args[key]); break; } str = str.replace(key, args[key]); } return str; }; /** * Translate strings to the page language or a given language. * * See the documentation of the server-side t() function for further details. * * @param str * A string containing the English string to translate. * @param args * An object of replacements pairs to make after translation. Incidences * of any key in this array are replaced with the corresponding value. * See Drupal.formatString(). * * @param options * - 'context' (defaults to the empty context): The context the source string * belongs to. * * @return * The translated string. */ Drupal.t = function (str, args, options) { options = options || {}; options.context = options.context || ''; // Fetch the localized version of the string. if (Drupal.locale.strings && Drupal.locale.strings[options.context] && Drupal.locale.strings[options.context][str]) { str = Drupal.locale.strings[options.context][str]; } if (args) { str = Drupal.formatString(str, args); } return str; }; /** * Format a string containing a count of items. * * This function ensures that the string is pluralized correctly. Since Drupal.t() is * called by this function, make sure not to pass already-localized strings to it. * * See the documentation of the server-side format_plural() function for further details. * * @param count * The item count to display. * @param singular * The string for the singular case. Please make sure it is clear this is * singular, to ease translation (e.g. use "1 new comment" instead of "1 new"). * Do not use @count in the singular string. * @param plural * The string for the plural case. Please make sure it is clear this is plural, * to ease translation. Use @count in place of the item count, as in "@count * new comments". * @param args * An object of replacements pairs to make after translation. Incidences * of any key in this array are replaced with the corresponding value. * See Drupal.formatString(). * Note that you do not need to include @count in this array. * This replacement is done automatically for the plural case. * @param options * The options to pass to the Drupal.t() function. * @return * A translated string. */ Drupal.formatPlural = function (count, singular, plural, args, options) { var args = args || {}; args['@count'] = count; // Determine the index of the plural form. var index = Drupal.locale.pluralFormula ? Drupal.locale.pluralFormula(args['@count']) : ((args['@count'] == 1) ? 0 : 1); if (index == 0) { return Drupal.t(singular, args, options); } else if (index == 1) { return Drupal.t(plural, args, options); } else { args['@count[' + index + ']'] = args['@count']; delete args['@count']; return Drupal.t(plural.replace('@count', '@count[' + index + ']'), args, options); } }; /** * Generate the themed representation of a Drupal object. * * All requests for themed output must go through this function. It examines * the request and routes it to the appropriate theme function. If the current * theme does not provide an override function, the generic theme function is * called. * * For example, to retrieve the HTML for text that should be emphasized and * displayed as a placeholder inside a sentence, call * Drupal.theme('placeholder', text). * * @param func * The name of the theme function to call. * @param ... * Additional arguments to pass along to the theme function. * @return * Any data the theme function returns. This could be a plain HTML string, * but also a complex object. */ Drupal.theme = function (func) { var args = Array.prototype.slice.apply(arguments, [1]); return (Drupal.theme[func] || Drupal.theme.prototype[func]).apply(this, args); }; /** * Freeze the current body height (as minimum height). Used to prevent * unnecessary upwards scrolling when doing DOM manipulations. */ Drupal.freezeHeight = function () { Drupal.unfreezeHeight(); $('<div id="freeze-height"></div>').css({ position: 'absolute', top: '0px', left: '0px', width: '1px', height: $('body').css('height') }).appendTo('body'); }; /** * Unfreeze the body height. */ Drupal.unfreezeHeight = function () { $('#freeze-height').remove(); }; /** * Encodes a Drupal path for use in a URL. * * For aesthetic reasons slashes are not escaped. */ Drupal.encodePath = function (item, uri) { uri = uri || location.href; return encodeURIComponent(item).replace(/%2F/g, '/'); }; /** * Get the text selection in a textarea. */ Drupal.getSelection = function (element) { if (typeof element.selectionStart != 'number' && document.selection) { // The current selection. var range1 = document.selection.createRange(); var range2 = range1.duplicate(); // Select all text. range2.moveToElementText(element); // Now move 'dummy' end point to end point of original range. range2.setEndPoint('EndToEnd', range1); // Now we can calculate start and end points. var start = range2.text.length - range1.text.length; var end = start + range1.text.length; return { 'start': start, 'end': end }; } return { 'start': element.selectionStart, 'end': element.selectionEnd }; }; /** * Build an error message from an Ajax response. */ Drupal.ajaxError = function (xmlhttp, uri) { var statusCode, statusText, pathText, responseText, readyStateText, message; if (xmlhttp.status) { statusCode = "\n" + Drupal.t("An AJAX HTTP error occurred.") + "\n" + Drupal.t("HTTP Result Code: !status", {'!status': xmlhttp.status}); } else { statusCode = "\n" + Drupal.t("An AJAX HTTP request terminated abnormally."); } statusCode += "\n" + Drupal.t("Debugging information follows."); pathText = "\n" + Drupal.t("Path: !uri", {'!uri': uri} ); statusText = ''; // In some cases, when statusCode == 0, xmlhttp.statusText may not be defined. // Unfortunately, testing for it with typeof, etc, doesn't seem to catch that // and the test causes an exception. So we need to catch the exception here. try { statusText = "\n" + Drupal.t("StatusText: !statusText", {'!statusText': $.trim(xmlhttp.statusText)}); } catch (e) {} responseText = ''; // Again, we don't have a way to know for sure whether accessing // xmlhttp.responseText is going to throw an exception. So we'll catch it. try { responseText = "\n" + Drupal.t("ResponseText: !responseText", {'!responseText': $.trim(xmlhttp.responseText) } ); } catch (e) {} // Make the responseText more readable by stripping HTML tags and newlines. responseText = responseText.replace(/<("[^"]*"|'[^']*'|[^'">])*>/gi,""); responseText = responseText.replace(/[\n]+\s+/g,"\n"); // We don't need readyState except for status == 0. readyStateText = xmlhttp.status == 0 ? ("\n" + Drupal.t("ReadyState: !readyState", {'!readyState': xmlhttp.readyState})) : ""; message = statusCode + pathText + statusText + responseText + readyStateText; return message; }; // Class indicating that JS is enabled; used for styling purpose. $('html').addClass('js'); // 'js enabled' cookie. document.cookie = 'has_js=1; path=/'; /** * Additions to jQuery.support. */ $(function () { /** * Boolean indicating whether or not position:fixed is supported. */ if (jQuery.support.positionFixed === undefined) { var el = $('<div style="position:fixed; top:10px" />').appendTo(document.body); jQuery.support.positionFixed = el[0].offsetTop === 10; el.remove(); } }); //Attach all behaviors. $(function () { Drupal.attachBehaviors(document, Drupal.settings); }); /** * The default themes. */ Drupal.theme.prototype = { /** * Formats text for emphasized display in a placeholder inside a sentence. * * @param str * The text to format (plain-text). * @return * The formatted text (html). */ placeholder: function (str) { return '<em class="placeholder">' + Drupal.checkPlain(str) + '</em>'; } }; })(jQuery);
JavaScript
(function ($) { /** * Provides Ajax page updating via jQuery $.ajax (Asynchronous JavaScript and XML). * * Ajax is a method of making a request via JavaScript while viewing an HTML * page. The request returns an array of commands encoded in JSON, which is * then executed to make any changes that are necessary to the page. * * Drupal uses this file to enhance form elements with #ajax['path'] and * #ajax['wrapper'] properties. If set, this file will automatically be included * to provide Ajax capabilities. */ Drupal.ajax = Drupal.ajax || {}; /** * Attaches the Ajax behavior to each Ajax form element. */ Drupal.behaviors.AJAX = { attach: function (context, settings) { // Load all Ajax behaviors specified in the settings. for (var base in settings.ajax) { if (!$('#' + base + '.ajax-processed').length) { var element_settings = settings.ajax[base]; if (typeof element_settings.selector == 'undefined') { element_settings.selector = '#' + base; } $(element_settings.selector).each(function () { element_settings.element = this; Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings); }); $('#' + base).addClass('ajax-processed'); } } // Bind Ajax behaviors to all items showing the class. $('.use-ajax:not(.ajax-processed)').addClass('ajax-processed').each(function () { var element_settings = {}; // Clicked links look better with the throbber than the progress bar. element_settings.progress = { 'type': 'throbber' }; // For anchor tags, these will go to the target of the anchor rather // than the usual location. if ($(this).attr('href')) { element_settings.url = $(this).attr('href'); element_settings.event = 'click'; } var base = $(this).attr('id'); Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings); }); // This class means to submit the form to the action using Ajax. $('.use-ajax-submit:not(.ajax-processed)').addClass('ajax-processed').each(function () { var element_settings = {}; // Ajax submits specified in this manner automatically submit to the // normal form action. element_settings.url = $(this.form).attr('action'); // Form submit button clicks need to tell the form what was clicked so // it gets passed in the POST request. element_settings.setClick = true; // Form buttons use the 'click' event rather than mousedown. element_settings.event = 'click'; // Clicked form buttons look better with the throbber than the progress bar. element_settings.progress = { 'type': 'throbber' }; var base = $(this).attr('id'); Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings); }); } }; /** * Ajax object. * * All Ajax objects on a page are accessible through the global Drupal.ajax * object and are keyed by the submit button's ID. You can access them from * your module's JavaScript file to override properties or functions. * * For example, if your Ajax enabled button has the ID 'edit-submit', you can * redefine the function that is called to insert the new content like this * (inside a Drupal.behaviors attach block): * @code * Drupal.behaviors.myCustomAJAXStuff = { * attach: function (context, settings) { * Drupal.ajax['edit-submit'].commands.insert = function (ajax, response, status) { * new_content = $(response.data); * $('#my-wrapper').append(new_content); * alert('New content was appended to #my-wrapper'); * } * } * }; * @endcode */ Drupal.ajax = function (base, element, element_settings) { var defaults = { url: 'system/ajax', event: 'mousedown', keypress: true, selector: '#' + base, effect: 'none', speed: 'none', method: 'replaceWith', progress: { type: 'throbber', message: Drupal.t('Please wait...') }, submit: { 'js': true } }; $.extend(this, defaults, element_settings); this.element = element; this.element_settings = element_settings; // Replacing 'nojs' with 'ajax' in the URL allows for an easy method to let // the server detect when it needs to degrade gracefully. // There are five scenarios to check for: // 1. /nojs/ // 2. /nojs$ - The end of a URL string. // 3. /nojs? - Followed by a query (with clean URLs enabled). // E.g.: path/nojs?destination=foobar // 4. /nojs& - Followed by a query (without clean URLs enabled). // E.g.: ?q=path/nojs&destination=foobar // 5. /nojs# - Followed by a fragment. // E.g.: path/nojs#myfragment this.url = element_settings.url.replace(/\/nojs(\/|$|\?|&|#)/g, '/ajax$1'); this.wrapper = '#' + element_settings.wrapper; // If there isn't a form, jQuery.ajax() will be used instead, allowing us to // bind Ajax to links as well. if (this.element.form) { this.form = $(this.element.form); } // Set the options for the ajaxSubmit function. // The 'this' variable will not persist inside of the options object. var ajax = this; ajax.options = { url: ajax.url, data: ajax.submit, beforeSerialize: function (element_settings, options) { return ajax.beforeSerialize(element_settings, options); }, beforeSubmit: function (form_values, element_settings, options) { ajax.ajaxing = true; return ajax.beforeSubmit(form_values, element_settings, options); }, beforeSend: function (xmlhttprequest, options) { ajax.ajaxing = true; return ajax.beforeSend(xmlhttprequest, options); }, success: function (response, status) { // Sanity check for browser support (object expected). // When using iFrame uploads, responses must be returned as a string. if (typeof response == 'string') { response = $.parseJSON(response); } return ajax.success(response, status); }, complete: function (response, status) { ajax.ajaxing = false; if (status == 'error' || status == 'parsererror') { return ajax.error(response, ajax.url); } }, dataType: 'json', type: 'POST' }; // Bind the ajaxSubmit function to the element event. $(ajax.element).bind(element_settings.event, function (event) { return ajax.eventResponse(this, event); }); // If necessary, enable keyboard submission so that Ajax behaviors // can be triggered through keyboard input as well as e.g. a mousedown // action. if (element_settings.keypress) { $(ajax.element).keypress(function (event) { return ajax.keypressResponse(this, event); }); } // If necessary, prevent the browser default action of an additional event. // For example, prevent the browser default action of a click, even if the // AJAX behavior binds to mousedown. if (element_settings.prevent) { $(ajax.element).bind(element_settings.prevent, false); } }; /** * Handle a key press. * * The Ajax object will, if instructed, bind to a key press response. This * will test to see if the key press is valid to trigger this event and * if it is, trigger it for us and prevent other keypresses from triggering. * In this case we're handling RETURN and SPACEBAR keypresses (event codes 13 * and 32. RETURN is often used to submit a form when in a textfield, and * SPACE is often used to activate an element without submitting. */ Drupal.ajax.prototype.keypressResponse = function (element, event) { // Create a synonym for this to reduce code confusion. var ajax = this; // Detect enter key and space bar and allow the standard response for them, // except for form elements of type 'text' and 'textarea', where the // spacebar activation causes inappropriate activation if #ajax['keypress'] is // TRUE. On a text-type widget a space should always be a space. if (event.which == 13 || (event.which == 32 && element.type != 'text' && element.type != 'textarea')) { $(ajax.element_settings.element).trigger(ajax.element_settings.event); return false; } }; /** * Handle an event that triggers an Ajax response. * * When an event that triggers an Ajax response happens, this method will * perform the actual Ajax call. It is bound to the event using * bind() in the constructor, and it uses the options specified on the * ajax object. */ Drupal.ajax.prototype.eventResponse = function (element, event) { // Create a synonym for this to reduce code confusion. var ajax = this; // Do not perform another ajax command if one is already in progress. if (ajax.ajaxing) { return false; } try { if (ajax.form) { // If setClick is set, we must set this to ensure that the button's // value is passed. if (ajax.setClick) { // Mark the clicked button. 'form.clk' is a special variable for // ajaxSubmit that tells the system which element got clicked to // trigger the submit. Without it there would be no 'op' or // equivalent. element.form.clk = element; } ajax.form.ajaxSubmit(ajax.options); } else { ajax.beforeSerialize(ajax.element, ajax.options); $.ajax(ajax.options); } } catch (e) { // Unset the ajax.ajaxing flag here because it won't be unset during // the complete response. ajax.ajaxing = false; alert("An error occurred while attempting to process " + ajax.options.url + ": " + e.message); } // For radio/checkbox, allow the default event. On IE, this means letting // it actually check the box. if (typeof element.type != 'undefined' && (element.type == 'checkbox' || element.type == 'radio')) { return true; } else { return false; } }; /** * Handler for the form serialization. * * Runs before the beforeSend() handler (see below), and unlike that one, runs * before field data is collected. */ Drupal.ajax.prototype.beforeSerialize = function (element, options) { // Allow detaching behaviors to update field values before collecting them. // This is only needed when field values are added to the POST data, so only // when there is a form such that this.form.ajaxSubmit() is used instead of // $.ajax(). When there is no form and $.ajax() is used, beforeSerialize() // isn't called, but don't rely on that: explicitly check this.form. if (this.form) { var settings = this.settings || Drupal.settings; Drupal.detachBehaviors(this.form, settings, 'serialize'); } // Prevent duplicate HTML ids in the returned markup. // @see drupal_html_id() options.data['ajax_html_ids[]'] = []; $('[id]').each(function () { options.data['ajax_html_ids[]'].push(this.id); }); // Allow Drupal to return new JavaScript and CSS files to load without // returning the ones already loaded. // @see ajax_base_page_theme() // @see drupal_get_css() // @see drupal_get_js() options.data['ajax_page_state[theme]'] = Drupal.settings.ajaxPageState.theme; options.data['ajax_page_state[theme_token]'] = Drupal.settings.ajaxPageState.theme_token; for (var key in Drupal.settings.ajaxPageState.css) { options.data['ajax_page_state[css][' + key + ']'] = 1; } for (var key in Drupal.settings.ajaxPageState.js) { options.data['ajax_page_state[js][' + key + ']'] = 1; } }; /** * Modify form values prior to form submission. */ Drupal.ajax.prototype.beforeSubmit = function (form_values, element, options) { // This function is left empty to make it simple to override for modules // that wish to add functionality here. }; /** * Prepare the Ajax request before it is sent. */ Drupal.ajax.prototype.beforeSend = function (xmlhttprequest, options) { // For forms without file inputs, the jQuery Form plugin serializes the form // values, and then calls jQuery's $.ajax() function, which invokes this // handler. In this circumstance, options.extraData is never used. For forms // with file inputs, the jQuery Form plugin uses the browser's normal form // submission mechanism, but captures the response in a hidden IFRAME. In this // circumstance, it calls this handler first, and then appends hidden fields // to the form to submit the values in options.extraData. There is no simple // way to know which submission mechanism will be used, so we add to extraData // regardless, and allow it to be ignored in the former case. if (this.form) { options.extraData = options.extraData || {}; // Let the server know when the IFRAME submission mechanism is used. The // server can use this information to wrap the JSON response in a TEXTAREA, // as per http://jquery.malsup.com/form/#file-upload. options.extraData.ajax_iframe_upload = '1'; // The triggering element is about to be disabled (see below), but if it // contains a value (e.g., a checkbox, textfield, select, etc.), ensure that // value is included in the submission. As per above, submissions that use // $.ajax() are already serialized prior to the element being disabled, so // this is only needed for IFRAME submissions. var v = $.fieldValue(this.element); if (v !== null) { options.extraData[this.element.name] = v; } } // Disable the element that received the change to prevent user interface // interaction while the Ajax request is in progress. ajax.ajaxing prevents // the element from triggering a new request, but does not prevent the user // from changing its value. $(this.element).addClass('progress-disabled').attr('disabled', true); // Insert progressbar or throbber. if (this.progress.type == 'bar') { var progressBar = new Drupal.progressBar('ajax-progress-' + this.element.id, eval(this.progress.update_callback), this.progress.method, eval(this.progress.error_callback)); if (this.progress.message) { progressBar.setProgress(-1, this.progress.message); } if (this.progress.url) { progressBar.startMonitoring(this.progress.url, this.progress.interval || 1500); } this.progress.element = $(progressBar.element).addClass('ajax-progress ajax-progress-bar'); this.progress.object = progressBar; $(this.element).after(this.progress.element); } else if (this.progress.type == 'throbber') { this.progress.element = $('<div class="ajax-progress ajax-progress-throbber"><div class="throbber">&nbsp;</div></div>'); if (this.progress.message) { $('.throbber', this.progress.element).after('<div class="message">' + this.progress.message + '</div>'); } $(this.element).after(this.progress.element); } }; /** * Handler for the form redirection completion. */ Drupal.ajax.prototype.success = function (response, status) { // Remove the progress element. if (this.progress.element) { $(this.progress.element).remove(); } if (this.progress.object) { this.progress.object.stopMonitoring(); } $(this.element).removeClass('progress-disabled').removeAttr('disabled'); Drupal.freezeHeight(); for (var i in response) { if (response[i]['command'] && this.commands[response[i]['command']]) { this.commands[response[i]['command']](this, response[i], status); } } // Reattach behaviors, if they were detached in beforeSerialize(). The // attachBehaviors() called on the new content from processing the response // commands is not sufficient, because behaviors from the entire form need // to be reattached. if (this.form) { var settings = this.settings || Drupal.settings; Drupal.attachBehaviors(this.form, settings); } Drupal.unfreezeHeight(); // Remove any response-specific settings so they don't get used on the next // call by mistake. this.settings = null; }; /** * Build an effect object which tells us how to apply the effect when adding new HTML. */ Drupal.ajax.prototype.getEffect = function (response) { var type = response.effect || this.effect; var speed = response.speed || this.speed; var effect = {}; if (type == 'none') { effect.showEffect = 'show'; effect.hideEffect = 'hide'; effect.showSpeed = ''; } else if (type == 'fade') { effect.showEffect = 'fadeIn'; effect.hideEffect = 'fadeOut'; effect.showSpeed = speed; } else { effect.showEffect = type + 'Toggle'; effect.hideEffect = type + 'Toggle'; effect.showSpeed = speed; } return effect; }; /** * Handler for the form redirection error. */ Drupal.ajax.prototype.error = function (response, uri) { alert(Drupal.ajaxError(response, uri)); // Remove the progress element. if (this.progress.element) { $(this.progress.element).remove(); } if (this.progress.object) { this.progress.object.stopMonitoring(); } // Undo hide. $(this.wrapper).show(); // Re-enable the element. $(this.element).removeClass('progress-disabled').removeAttr('disabled'); // Reattach behaviors, if they were detached in beforeSerialize(). if (this.form) { var settings = response.settings || this.settings || Drupal.settings; Drupal.attachBehaviors(this.form, settings); } }; /** * Provide a series of commands that the server can request the client perform. */ Drupal.ajax.prototype.commands = { /** * Command to insert new content into the DOM. */ insert: function (ajax, response, status) { // Get information from the response. If it is not there, default to // our presets. var wrapper = response.selector ? $(response.selector) : $(ajax.wrapper); var method = response.method || ajax.method; var effect = ajax.getEffect(response); // We don't know what response.data contains: it might be a string of text // without HTML, so don't rely on jQuery correctly iterpreting // $(response.data) as new HTML rather than a CSS selector. Also, if // response.data contains top-level text nodes, they get lost with either // $(response.data) or $('<div></div>').replaceWith(response.data). var new_content_wrapped = $('<div></div>').html(response.data); var new_content = new_content_wrapped.contents(); // For legacy reasons, the effects processing code assumes that new_content // consists of a single top-level element. Also, it has not been // sufficiently tested whether attachBehaviors() can be successfully called // with a context object that includes top-level text nodes. However, to // give developers full control of the HTML appearing in the page, and to // enable Ajax content to be inserted in places where DIV elements are not // allowed (e.g., within TABLE, TR, and SPAN parents), we check if the new // content satisfies the requirement of a single top-level element, and // only use the container DIV created above when it doesn't. For more // information, please see http://drupal.org/node/736066. if (new_content.length != 1 || new_content.get(0).nodeType != 1) { new_content = new_content_wrapped; } // If removing content from the wrapper, detach behaviors first. switch (method) { case 'html': case 'replaceWith': case 'replaceAll': case 'empty': case 'remove': var settings = response.settings || ajax.settings || Drupal.settings; Drupal.detachBehaviors(wrapper, settings); } // Add the new content to the page. wrapper[method](new_content); // Immediately hide the new content if we're using any effects. if (effect.showEffect != 'show') { new_content.hide(); } // Determine which effect to use and what content will receive the // effect, then show the new content. if ($('.ajax-new-content', new_content).length > 0) { $('.ajax-new-content', new_content).hide(); new_content.show(); $('.ajax-new-content', new_content)[effect.showEffect](effect.showSpeed); } else if (effect.showEffect != 'show') { new_content[effect.showEffect](effect.showSpeed); } // Attach all JavaScript behaviors to the new content, if it was successfully // added to the page, this if statement allows #ajax['wrapper'] to be // optional. if (new_content.parents('html').length > 0) { // Apply any settings from the returned JSON if available. var settings = response.settings || ajax.settings || Drupal.settings; Drupal.attachBehaviors(new_content, settings); } }, /** * Command to remove a chunk from the page. */ remove: function (ajax, response, status) { var settings = response.settings || ajax.settings || Drupal.settings; Drupal.detachBehaviors($(response.selector), settings); $(response.selector).remove(); }, /** * Command to mark a chunk changed. */ changed: function (ajax, response, status) { if (!$(response.selector).hasClass('ajax-changed')) { $(response.selector).addClass('ajax-changed'); if (response.asterisk) { $(response.selector).find(response.asterisk).append(' <span class="ajax-changed">*</span> '); } } }, /** * Command to provide an alert. */ alert: function (ajax, response, status) { alert(response.text, response.title); }, /** * Command to provide the jQuery css() function. */ css: function (ajax, response, status) { $(response.selector).css(response.argument); }, /** * Command to set the settings that will be used for other commands in this response. */ settings: function (ajax, response, status) { if (response.merge) { $.extend(true, Drupal.settings, response.settings); } else { ajax.settings = response.settings; } }, /** * Command to attach data using jQuery's data API. */ data: function (ajax, response, status) { $(response.selector).data(response.name, response.value); }, /** * Command to apply a jQuery method. */ invoke: function (ajax, response, status) { var $element = $(response.selector); $element[response.method].apply($element, response.arguments); }, /** * Command to restripe a table. */ restripe: function (ajax, response, status) { // :even and :odd are reversed because jQuery counts from 0 and // we count from 1, so we're out of sync. // Match immediate children of the parent element to allow nesting. $('> tbody > tr:visible, > tr:visible', $(response.selector)) .removeClass('odd even') .filter(':even').addClass('odd').end() .filter(':odd').addClass('even'); } }; })(jQuery);
JavaScript
(function ($) { /** * Attaches the autocomplete behavior to all required fields. */ Drupal.behaviors.autocomplete = { attach: function (context, settings) { var acdb = []; $('input.autocomplete', context).once('autocomplete', function () { var uri = this.value; if (!acdb[uri]) { acdb[uri] = new Drupal.ACDB(uri); } var $input = $('#' + this.id.substr(0, this.id.length - 13)) .attr('autocomplete', 'OFF') .attr('aria-autocomplete', 'list'); $($input[0].form).submit(Drupal.autocompleteSubmit); $input.parent() .attr('role', 'application') .append($('<span class="element-invisible" aria-live="assertive"></span>') .attr('id', $input.attr('id') + '-autocomplete-aria-live') ); new Drupal.jsAC($input, acdb[uri]); }); } }; /** * Prevents the form from submitting if the suggestions popup is open * and closes the suggestions popup when doing so. */ Drupal.autocompleteSubmit = function () { return $('#autocomplete').each(function () { this.owner.hidePopup(); }).length == 0; }; /** * An AutoComplete object. */ Drupal.jsAC = function ($input, db) { var ac = this; this.input = $input[0]; this.ariaLive = $('#' + this.input.id + '-autocomplete-aria-live'); this.db = db; $input .keydown(function (event) { return ac.onkeydown(this, event); }) .keyup(function (event) { ac.onkeyup(this, event); }) .blur(function () { ac.hidePopup(); ac.db.cancel(); }); }; /** * Handler for the "keydown" event. */ Drupal.jsAC.prototype.onkeydown = function (input, e) { if (!e) { e = window.event; } switch (e.keyCode) { case 40: // down arrow. this.selectDown(); return false; case 38: // up arrow. this.selectUp(); return false; default: // All other keys. return true; } }; /** * Handler for the "keyup" event. */ Drupal.jsAC.prototype.onkeyup = function (input, e) { if (!e) { e = window.event; } switch (e.keyCode) { case 16: // Shift. case 17: // Ctrl. case 18: // Alt. case 20: // Caps lock. case 33: // Page up. case 34: // Page down. case 35: // End. case 36: // Home. case 37: // Left arrow. case 38: // Up arrow. case 39: // Right arrow. case 40: // Down arrow. return true; case 9: // Tab. case 13: // Enter. case 27: // Esc. this.hidePopup(e.keyCode); return true; default: // All other keys. if (input.value.length > 0 && !input.readOnly) { this.populatePopup(); } else { this.hidePopup(e.keyCode); } return true; } }; /** * Puts the currently highlighted suggestion into the autocomplete field. */ Drupal.jsAC.prototype.select = function (node) { this.input.value = $(node).data('autocompleteValue'); }; /** * Highlights the next suggestion. */ Drupal.jsAC.prototype.selectDown = function () { if (this.selected && this.selected.nextSibling) { this.highlight(this.selected.nextSibling); } else if (this.popup) { var lis = $('li', this.popup); if (lis.length > 0) { this.highlight(lis.get(0)); } } }; /** * Highlights the previous suggestion. */ Drupal.jsAC.prototype.selectUp = function () { if (this.selected && this.selected.previousSibling) { this.highlight(this.selected.previousSibling); } }; /** * Highlights a suggestion. */ Drupal.jsAC.prototype.highlight = function (node) { if (this.selected) { $(this.selected).removeClass('selected'); } $(node).addClass('selected'); this.selected = node; $(this.ariaLive).html($(this.selected).html()); }; /** * Unhighlights a suggestion. */ Drupal.jsAC.prototype.unhighlight = function (node) { $(node).removeClass('selected'); this.selected = false; $(this.ariaLive).empty(); }; /** * Hides the autocomplete suggestions. */ Drupal.jsAC.prototype.hidePopup = function (keycode) { // Select item if the right key or mousebutton was pressed. if (this.selected && ((keycode && keycode != 46 && keycode != 8 && keycode != 27) || !keycode)) { this.input.value = $(this.selected).data('autocompleteValue'); } // Hide popup. var popup = this.popup; if (popup) { this.popup = null; $(popup).fadeOut('fast', function () { $(popup).remove(); }); } this.selected = false; $(this.ariaLive).empty(); }; /** * Positions the suggestions popup and starts a search. */ Drupal.jsAC.prototype.populatePopup = function () { var $input = $(this.input); var position = $input.position(); // Show popup. if (this.popup) { $(this.popup).remove(); } this.selected = false; this.popup = $('<div id="autocomplete"></div>')[0]; this.popup.owner = this; $(this.popup).css({ top: parseInt(position.top + this.input.offsetHeight, 10) + 'px', left: parseInt(position.left, 10) + 'px', width: $input.innerWidth() + 'px', display: 'none' }); $input.before(this.popup); // Do search. this.db.owner = this; this.db.search(this.input.value); }; /** * Fills the suggestion popup with any matches received. */ Drupal.jsAC.prototype.found = function (matches) { // If no value in the textfield, do not show the popup. if (!this.input.value.length) { return false; } // Prepare matches. var ul = $('<ul></ul>'); var ac = this; for (key in matches) { $('<li></li>') .html($('<div></div>').html(matches[key])) .mousedown(function () { ac.select(this); }) .mouseover(function () { ac.highlight(this); }) .mouseout(function () { ac.unhighlight(this); }) .data('autocompleteValue', key) .appendTo(ul); } // Show popup with matches, if any. if (this.popup) { if (ul.children().length) { $(this.popup).empty().append(ul).show(); $(this.ariaLive).html(Drupal.t('Autocomplete popup')); } else { $(this.popup).css({ visibility: 'hidden' }); this.hidePopup(); } } }; Drupal.jsAC.prototype.setStatus = function (status) { switch (status) { case 'begin': $(this.input).addClass('throbbing'); $(this.ariaLive).html(Drupal.t('Searching for matches...')); break; case 'cancel': case 'error': case 'found': $(this.input).removeClass('throbbing'); break; } }; /** * An AutoComplete DataBase object. */ Drupal.ACDB = function (uri) { this.uri = uri; this.delay = 300; this.cache = {}; }; /** * Performs a cached and delayed search. */ Drupal.ACDB.prototype.search = function (searchString) { var db = this; this.searchString = searchString; // See if this string needs to be searched for anyway. searchString = searchString.replace(/^\s+|\s+$/, ''); if (searchString.length <= 0 || searchString.charAt(searchString.length - 1) == ',') { return; } // See if this key has been searched for before. if (this.cache[searchString]) { return this.owner.found(this.cache[searchString]); } // Initiate delayed search. if (this.timer) { clearTimeout(this.timer); } this.timer = setTimeout(function () { db.owner.setStatus('begin'); // Ajax GET request for autocompletion. We use Drupal.encodePath instead of // encodeURIComponent to allow autocomplete search terms to contain slashes. $.ajax({ type: 'GET', url: db.uri + '/' + Drupal.encodePath(searchString), dataType: 'json', success: function (matches) { if (typeof matches.status == 'undefined' || matches.status != 0) { db.cache[searchString] = matches; // Verify if these are still the matches the user wants to see. if (db.searchString == searchString) { db.owner.found(matches); } db.owner.setStatus('found'); } }, error: function (xmlhttp) { alert(Drupal.ajaxError(xmlhttp, db.uri)); } }); }, this.delay); }; /** * Cancels the current autocomplete request. */ Drupal.ACDB.prototype.cancel = function () { if (this.owner) this.owner.setStatus('cancel'); if (this.timer) clearTimeout(this.timer); this.searchString = ''; }; })(jQuery);
JavaScript
(function ($) { /** * This script transforms a set of fieldsets into a stack of vertical * tabs. Another tab pane can be selected by clicking on the respective * tab. * * Each tab may have a summary which can be updated by another * script. For that to work, each fieldset has an associated * 'verticalTabCallback' (with jQuery.data() attached to the fieldset), * which is called every time the user performs an update to a form * element inside the tab pane. */ Drupal.behaviors.verticalTabs = { attach: function (context) { $('.vertical-tabs-panes', context).once('vertical-tabs', function () { var focusID = $(':hidden.vertical-tabs-active-tab', this).val(); var tab_focus; // Check if there are some fieldsets that can be converted to vertical-tabs var $fieldsets = $('> fieldset', this); if ($fieldsets.length == 0) { return; } // Create the tab column. var tab_list = $('<ul class="vertical-tabs-list"></ul>'); $(this).wrap('<div class="vertical-tabs clearfix"></div>').before(tab_list); // Transform each fieldset into a tab. $fieldsets.each(function () { var vertical_tab = new Drupal.verticalTab({ title: $('> legend', this).text(), fieldset: $(this) }); tab_list.append(vertical_tab.item); $(this) .removeClass('collapsible collapsed') .addClass('vertical-tabs-pane') .data('verticalTab', vertical_tab); if (this.id == focusID) { tab_focus = $(this); } }); $('> li:first', tab_list).addClass('first'); $('> li:last', tab_list).addClass('last'); if (!tab_focus) { // If the current URL has a fragment and one of the tabs contains an // element that matches the URL fragment, activate that tab. if (window.location.hash && $(this).find(window.location.hash).length) { tab_focus = $(this).find(window.location.hash).closest('.vertical-tabs-pane'); } else { tab_focus = $('> .vertical-tabs-pane:first', this); } } if (tab_focus.length) { tab_focus.data('verticalTab').focus(); } }); } }; /** * The vertical tab object represents a single tab within a tab group. * * @param settings * An object with the following keys: * - title: The name of the tab. * - fieldset: The jQuery object of the fieldset that is the tab pane. */ Drupal.verticalTab = function (settings) { var self = this; $.extend(this, settings, Drupal.theme('verticalTab', settings)); this.link.click(function () { self.focus(); return false; }); // Keyboard events added: // Pressing the Enter key will open the tab pane. this.link.keydown(function(event) { if (event.keyCode == 13) { self.focus(); // Set focus on the first input field of the visible fieldset/tab pane. $("fieldset.vertical-tabs-pane :input:visible:enabled:first").focus(); return false; } }); this.fieldset .bind('summaryUpdated', function () { self.updateSummary(); }) .trigger('summaryUpdated'); }; Drupal.verticalTab.prototype = { /** * Displays the tab's content pane. */ focus: function () { this.fieldset .siblings('fieldset.vertical-tabs-pane') .each(function () { var tab = $(this).data('verticalTab'); tab.fieldset.hide(); tab.item.removeClass('selected'); }) .end() .show() .siblings(':hidden.vertical-tabs-active-tab') .val(this.fieldset.attr('id')); this.item.addClass('selected'); // Mark the active tab for screen readers. $('#active-vertical-tab').remove(); this.link.append('<span id="active-vertical-tab" class="element-invisible">' + Drupal.t('(active tab)') + '</span>'); }, /** * Updates the tab's summary. */ updateSummary: function () { this.summary.html(this.fieldset.drupalGetSummary()); }, /** * Shows a vertical tab pane. */ tabShow: function () { // Display the tab. this.item.show(); // Update .first marker for items. We need recurse from parent to retain the // actual DOM element order as jQuery implements sortOrder, but not as public // method. this.item.parent().children('.vertical-tab-button').removeClass('first') .filter(':visible:first').addClass('first'); // Display the fieldset. this.fieldset.removeClass('vertical-tab-hidden').show(); // Focus this tab. this.focus(); return this; }, /** * Hides a vertical tab pane. */ tabHide: function () { // Hide this tab. this.item.hide(); // Update .first marker for items. We need recurse from parent to retain the // actual DOM element order as jQuery implements sortOrder, but not as public // method. this.item.parent().children('.vertical-tab-button').removeClass('first') .filter(':visible:first').addClass('first'); // Hide the fieldset. this.fieldset.addClass('vertical-tab-hidden').hide(); // Focus the first visible tab (if there is one). var $firstTab = this.fieldset.siblings('.vertical-tabs-pane:not(.vertical-tab-hidden):first'); if ($firstTab.length) { $firstTab.data('verticalTab').focus(); } return this; } }; /** * Theme function for a vertical tab. * * @param settings * An object with the following keys: * - title: The name of the tab. * @return * This function has to return an object with at least these keys: * - item: The root tab jQuery element * - link: The anchor tag that acts as the clickable area of the tab * (jQuery version) * - summary: The jQuery element that contains the tab summary */ Drupal.theme.prototype.verticalTab = function (settings) { var tab = {}; tab.item = $('<li class="vertical-tab-button" tabindex="-1"></li>') .append(tab.link = $('<a href="#"></a>') .append(tab.title = $('<strong></strong>').text(settings.title)) .append(tab.summary = $('<span class="summary"></span>') ) ); return tab; }; })(jQuery);
JavaScript
/** * jQuery Once Plugin v1.2 * http://plugins.jquery.com/project/once * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ (function ($) { var cache = {}, uuid = 0; /** * Filters elements by whether they have not yet been processed. * * @param id * (Optional) If this is a string, then it will be used as the CSS class * name that is applied to the elements for determining whether it has * already been processed. The elements will get a class in the form of * "id-processed". * * If the id parameter is a function, it will be passed off to the fn * parameter and the id will become a unique identifier, represented as a * number. * * When the id is neither a string or a function, it becomes a unique * identifier, depicted as a number. The element's class will then be * represented in the form of "jquery-once-#-processed". * * Take note that the id must be valid for usage as an element's class name. * @param fn * (Optional) If given, this function will be called for each element that * has not yet been processed. The function's return value follows the same * logic as $.each(). Returning true will continue to the next matched * element in the set, while returning false will entirely break the * iteration. */ $.fn.once = function (id, fn) { if (typeof id != 'string') { // Generate a numeric ID if the id passed can't be used as a CSS class. if (!(id in cache)) { cache[id] = ++uuid; } // When the fn parameter is not passed, we interpret it from the id. if (!fn) { fn = id; } id = 'jquery-once-' + cache[id]; } // Remove elements from the set that have already been processed. var name = id + '-processed'; var elements = this.not('.' + name).addClass(name); return $.isFunction(fn) ? elements.each(fn) : elements; }; /** * Filters elements that have been processed once already. * * @param id * A required string representing the name of the class which should be used * when filtering the elements. This only filters elements that have already * been processed by the once function. The id should be the same id that * was originally passed to the once() function. * @param fn * (Optional) If given, this function will be called for each element that * has not yet been processed. The function's return value follows the same * logic as $.each(). Returning true will continue to the next matched * element in the set, while returning false will entirely break the * iteration. */ $.fn.removeOnce = function (id, fn) { var name = id + '-processed'; var elements = this.filter('.' + name).removeClass(name); return $.isFunction(fn) ? elements.each(fn) : elements; }; })(jQuery);
JavaScript
(function ($) { /** * Attach the machine-readable name form element behavior. */ Drupal.behaviors.machineName = { /** * Attaches the behavior. * * @param settings.machineName * A list of elements to process, keyed by the HTML ID of the form element * containing the human-readable value. Each element is an object defining * the following properties: * - target: The HTML ID of the machine name form element. * - suffix: The HTML ID of a container to show the machine name preview in * (usually a field suffix after the human-readable name form element). * - label: The label to show for the machine name preview. * - replace_pattern: A regular expression (without modifiers) matching * disallowed characters in the machine name; e.g., '[^a-z0-9]+'. * - replace: A character to replace disallowed characters with; e.g., '_' * or '-'. * - standalone: Whether the preview should stay in its own element rather * than the suffix of the source element. * - field_prefix: The #field_prefix of the form element. * - field_suffix: The #field_suffix of the form element. */ attach: function (context, settings) { var self = this; $.each(settings.machineName, function (source_id, options) { var $source = $(source_id, context).addClass('machine-name-source'); var $target = $(options.target, context).addClass('machine-name-target'); var $suffix = $(options.suffix, context); var $wrapper = $target.closest('.form-item'); // All elements have to exist. if (!$source.length || !$target.length || !$suffix.length || !$wrapper.length) { return; } // Skip processing upon a form validation error on the machine name. if ($target.hasClass('error')) { return; } // Figure out the maximum length for the machine name. options.maxlength = $target.attr('maxlength'); // Hide the form item container of the machine name form element. $wrapper.hide(); // Determine the initial machine name value. Unless the machine name form // element is disabled or not empty, the initial default value is based on // the human-readable form element value. if ($target.is(':disabled') || $target.val() != '') { var machine = $target.val(); } else { var machine = self.transliterate($source.val(), options); } // Append the machine name preview to the source field. var $preview = $('<span class="machine-name-value">' + options.field_prefix + Drupal.checkPlain(machine) + options.field_suffix + '</span>'); $suffix.empty(); if (options.label) { $suffix.append(' ').append('<span class="machine-name-label">' + options.label + ':</span>'); } $suffix.append(' ').append($preview); // If the machine name cannot be edited, stop further processing. if ($target.is(':disabled')) { return; } // If it is editable, append an edit link. var $link = $('<span class="admin-link"><a href="#">' + Drupal.t('Edit') + '</a></span>') .click(function () { $wrapper.show(); $target.focus(); $suffix.hide(); $source.unbind('.machineName'); return false; }); $suffix.append(' ').append($link); // Preview the machine name in realtime when the human-readable name // changes, but only if there is no machine name yet; i.e., only upon // initial creation, not when editing. if ($target.val() == '') { $source.bind('keyup.machineName change.machineName', function () { machine = self.transliterate($(this).val(), options); // Set the machine name to the transliterated value. if (machine != '') { if (machine != options.replace) { $target.val(machine); $preview.html(options.field_prefix + Drupal.checkPlain(machine) + options.field_suffix); } $suffix.show(); } else { $suffix.hide(); $target.val(machine); $preview.empty(); } }); // Initialize machine name preview. $source.keyup(); } }); }, /** * Transliterate a human-readable name to a machine name. * * @param source * A string to transliterate. * @param settings * The machine name settings for the corresponding field, containing: * - replace_pattern: A regular expression (without modifiers) matching * disallowed characters in the machine name; e.g., '[^a-z0-9]+'. * - replace: A character to replace disallowed characters with; e.g., '_' * or '-'. * - maxlength: The maximum length of the machine name. * * @return * The transliterated source string. */ transliterate: function (source, settings) { var rx = new RegExp(settings.replace_pattern, 'g'); return source.toLowerCase().replace(rx, settings.replace).substr(0, settings.maxlength); } }; })(jQuery);
JavaScript
(function ($) { /** * A progressbar object. Initialized with the given id. Must be inserted into * the DOM afterwards through progressBar.element. * * method is the function which will perform the HTTP request to get the * progress bar state. Either "GET" or "POST". * * e.g. pb = new progressBar('myProgressBar'); * some_element.appendChild(pb.element); */ Drupal.progressBar = function (id, updateCallback, method, errorCallback) { var pb = this; this.id = id; this.method = method || 'GET'; this.updateCallback = updateCallback; this.errorCallback = errorCallback; // The WAI-ARIA setting aria-live="polite" will announce changes after users // have completed their current activity and not interrupt the screen reader. this.element = $('<div class="progress" aria-live="polite"></div>').attr('id', id); this.element.html('<div class="bar"><div class="filled"></div></div>' + '<div class="percentage"></div>' + '<div class="message">&nbsp;</div>'); }; /** * Set the percentage and status message for the progressbar. */ Drupal.progressBar.prototype.setProgress = function (percentage, message) { if (percentage >= 0 && percentage <= 100) { $('div.filled', this.element).css('width', percentage + '%'); $('div.percentage', this.element).html(percentage + '%'); } $('div.message', this.element).html(message); if (this.updateCallback) { this.updateCallback(percentage, message, this); } }; /** * Start monitoring progress via Ajax. */ Drupal.progressBar.prototype.startMonitoring = function (uri, delay) { this.delay = delay; this.uri = uri; this.sendPing(); }; /** * Stop monitoring progress via Ajax. */ Drupal.progressBar.prototype.stopMonitoring = function () { clearTimeout(this.timer); // This allows monitoring to be stopped from within the callback. this.uri = null; }; /** * Request progress data from server. */ Drupal.progressBar.prototype.sendPing = function () { if (this.timer) { clearTimeout(this.timer); } if (this.uri) { var pb = this; // When doing a post request, you need non-null data. Otherwise a // HTTP 411 or HTTP 406 (with Apache mod_security) error may result. $.ajax({ type: this.method, url: this.uri, data: '', dataType: 'json', success: function (progress) { // Display errors. if (progress.status == 0) { pb.displayError(progress.data); return; } // Update display. pb.setProgress(progress.percentage, progress.message); // Schedule next timer. pb.timer = setTimeout(function () { pb.sendPing(); }, pb.delay); }, error: function (xmlhttp) { pb.displayError(Drupal.ajaxError(xmlhttp, pb.uri)); } }); } }; /** * Display errors on the page. */ Drupal.progressBar.prototype.displayError = function (string) { var error = $('<div class="messages error"></div>').html(string); $(this.element).before(error).hide(); if (this.errorCallback) { this.errorCallback(this); } }; })(jQuery);
JavaScript
/** * Cookie plugin 1.0 * * Copyright (c) 2006 Klaus Hartl (stilbuero.de) * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ jQuery.cookie=function(b,j,m){if(typeof j!="undefined"){m=m||{};if(j===null){j="";m.expires=-1}var e="";if(m.expires&&(typeof m.expires=="number"||m.expires.toUTCString)){var f;if(typeof m.expires=="number"){f=new Date();f.setTime(f.getTime()+(m.expires*24*60*60*1000))}else{f=m.expires}e="; expires="+f.toUTCString()}var l=m.path?"; path="+(m.path):"";var g=m.domain?"; domain="+(m.domain):"";var a=m.secure?"; secure":"";document.cookie=[b,"=",encodeURIComponent(j),e,l,g,a].join("")}else{var d=null;if(document.cookie&&document.cookie!=""){var k=document.cookie.split(";");for(var h=0;h<k.length;h++){var c=jQuery.trim(k[h]);if(c.substring(0,b.length+1)==(b+"=")){d=decodeURIComponent(c.substring(b.length+1));break}}}return d}};
JavaScript
(function ($) { Drupal.behaviors.tableSelect = { attach: function (context, settings) { // Select the inner-most table in case of nested tables. $('th.select-all', context).closest('table').once('table-select', Drupal.tableSelect); } }; Drupal.tableSelect = function () { // Do not add a "Select all" checkbox if there are no rows with checkboxes in the table if ($('td input:checkbox', this).length == 0) { return; } // Keep track of the table, which checkbox is checked and alias the settings. var table = this, checkboxes, lastChecked; var strings = { 'selectAll': Drupal.t('Select all rows in this table'), 'selectNone': Drupal.t('Deselect all rows in this table') }; var updateSelectAll = function (state) { // Update table's select-all checkbox (and sticky header's if available). $(table).prev('table.sticky-header').andSelf().find('th.select-all input:checkbox').each(function() { $(this).attr('title', state ? strings.selectNone : strings.selectAll); this.checked = state; }); }; // Find all <th> with class select-all, and insert the check all checkbox. $('th.select-all', table).prepend($('<input type="checkbox" class="form-checkbox" />').attr('title', strings.selectAll)).click(function (event) { if ($(event.target).is('input:checkbox')) { // Loop through all checkboxes and set their state to the select all checkbox' state. checkboxes.each(function () { this.checked = event.target.checked; // Either add or remove the selected class based on the state of the check all checkbox. $(this).closest('tr').toggleClass('selected', this.checked); }); // Update the title and the state of the check all box. updateSelectAll(event.target.checked); } }); // For each of the checkboxes within the table that are not disabled. checkboxes = $('td input:checkbox:enabled', table).click(function (e) { // Either add or remove the selected class based on the state of the check all checkbox. $(this).closest('tr').toggleClass('selected', this.checked); // If this is a shift click, we need to highlight everything in the range. // Also make sure that we are actually checking checkboxes over a range and // that a checkbox has been checked or unchecked before. if (e.shiftKey && lastChecked && lastChecked != e.target) { // We use the checkbox's parent TR to do our range searching. Drupal.tableSelectRange($(e.target).closest('tr')[0], $(lastChecked).closest('tr')[0], e.target.checked); } // If all checkboxes are checked, make sure the select-all one is checked too, otherwise keep unchecked. updateSelectAll((checkboxes.length == $(checkboxes).filter(':checked').length)); // Keep track of the last checked checkbox. lastChecked = e.target; }); }; Drupal.tableSelectRange = function (from, to, state) { // We determine the looping mode based on the the order of from and to. var mode = from.rowIndex > to.rowIndex ? 'previousSibling' : 'nextSibling'; // Traverse through the sibling nodes. for (var i = from[mode]; i; i = i[mode]) { // Make sure that we're only dealing with elements. if (i.nodeType != 1) { continue; } // Either add or remove the selected class based on the state of the target checkbox. $(i).toggleClass('selected', state); $('input:checkbox', i).each(function () { this.checked = state; }); if (to.nodeType) { // If we are at the end of the range, stop. if (i == to) { break; } } // A faster alternative to doing $(i).filter(to).length. else if ($.filter(to, [i]).r.length) { break; } } }; })(jQuery);
JavaScript
(function ($) { Drupal.color = { logoChanged: false, callback: function(context, settings, form, farb, height, width) { // Change the logo to be the real one. if (!this.logoChanged) { $('#preview #preview-logo img').attr('src', Drupal.settings.color.logo); this.logoChanged = true; } // Remove the logo if the setting is toggled off. if (Drupal.settings.color.logo == null) { $('div').remove('#preview-logo'); } // Solid background. $('#preview', form).css('backgroundColor', $('#palette input[name="palette[bg]"]', form).val()); // Text preview. $('#preview #preview-main h2, #preview .preview-content', form).css('color', $('#palette input[name="palette[text]"]', form).val()); $('#preview #preview-content a', form).css('color', $('#palette input[name="palette[link]"]', form).val()); // Sidebar block. $('#preview #preview-sidebar #preview-block', form).css('background-color', $('#palette input[name="palette[sidebar]"]', form).val()); $('#preview #preview-sidebar #preview-block', form).css('border-color', $('#palette input[name="palette[sidebarborders]"]', form).val()); // Footer wrapper background. $('#preview #preview-footer-wrapper', form).css('background-color', $('#palette input[name="palette[footer]"]', form).val()); // CSS3 Gradients. var gradient_start = $('#palette input[name="palette[top]"]', form).val(); var gradient_end = $('#palette input[name="palette[bottom]"]', form).val(); $('#preview #preview-header', form).attr('style', "background-color: " + gradient_start + "; background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, from(" + gradient_start + "), to(" + gradient_end + ")); background-image: -moz-linear-gradient(-90deg, " + gradient_start + ", " + gradient_end + ");"); $('#preview #preview-site-name', form).css('color', $('#palette input[name="palette[titleslogan]"]', form).val()); } }; })(jQuery);
JavaScript
/*jQuery获取列表复选框的值 * @param value 数据列表存放的div或table的id * @return 返回以","分割的字符串 */ function getCheckBoxValue(value){ return jQuery(""+value+"").jqGrid('getGridParam','selarrrow'); } /*删除选中的数据 * @param url 提交到Action路径 * @param par 以","分割的id字符串 * @param value 数据列表存放的div或table的id * @return 返回字符串 */ function deleteDataList(url,par,value){ var info ; var params = {"strValue[]":par}; if(par == ""){ alert("请至少选择一条数据进行删除!",true); }else{ showConfirmDivLayer("您确定要删除选中的信息吗?",{okFun:function(){ jQuery.post( url, params, function(data) { if ("1" == data) { alert("删除成功!",true); jQuery(""+value+"").jqGrid().trigger('reloadGrid'); }else if("-1" == data){ alert("删除失败!",true); } }, 'text' ); } }); } return info; }
JavaScript
/** * Styleswitch stylesheet switcher built on jQuery * Under an Attribution, Share Alike License * By Kelvin Luck ( http://www.kelvinluck.com/ ) **/ jQuery(document).ready(function() { jQuery('div').find('.styleswitch').click(function() { //刷新iframe //document.frames('framecon').location.reload(); document.getElementById('framecon').contentWindow.location.reload(); switchStylestyle(this.getAttribute("rel")); return false; }); var c = readCookie('ZfsoftStyle'); //如果cookies里样式为空则取样式的最后一个 if (c) { switchStylestyle(c); }else { var l=jQuery('link:[rel*=style][title]').length-1; var stylename=''; jQuery('link:[rel*=style][title]').each(function(i) { if(l==i) { stylename=this.getAttribute('title'); } }) switchStylestyle(stylename); } }); function switchStylestyle(styleName) { var str=""; jQuery('link:[rel*=style][title]').each(function(i) { this.disabled = true; if (this.getAttribute('title') == styleName ||this.getAttribute('title') == styleName + "1") { //str=str+this.getAttribute('href'); this.disabled = false; } }); //alert(str); createCookie('ZfsoftStyle', styleName, 365); } // cookie functions http://www.quirksmode.org/js/cookies.html function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function eraseCookie(name) { createCookie(name,"",-1); } // /cookie functions
JavaScript
var curr_row = null; //单选框脚本 function chooseRadio(objTr){ if(curr_row != null && curr_row.tagName.toLowerCase() == "tr"){ curr_row.style.backgroundColor="#FFFFFF"; document.getElementById("radio_"+curr_row.id).checked = "false"; } curr_row = objTr; curr_row.style.backgroundColor="#cceeee"; document.getElementById("radio_"+curr_row.id).checked = "true"; } //筛选框脚本 function chooseCheckbox(objTr,tabId){ if(objTr.style.backgroundColor == "#cceeee"){ objTr.style.backgroundColor = "#ffffff"; document.getElementById("checkbox_"+objTr.id).checked = false; ChangeAllChecked(objTr,tabId); }else{ objTr.style.backgroundColor = "#cceeee"; document.getElementById("checkbox_"+objTr.id).checked = true; ChangeAllChecked(objTr,tabId); } } //日历(日期选择、不含时间) function selectDate(contextPath,idName){ var yyyy=new Array(2); //yyyy[1]="yyyy-MM-dd h:m"; yyyy[1]="yyyy-MM-dd"; var today = new Date(); var theYear = today.getYear(); var theMonth = today.getMonth() + 1; var theDay = today.getDate(); var theHour = "00";//today.getHours(); var theMinute = "00";//today.getMinutes(); yyyy[0]=theYear+"-"+theMonth+"-"+theDay+"-"+theHour+"-"+theMinute; var dateString = showModalDialog(contextPath+"/component/calendar/calendar.htm",yyyy,"dialogWidth:309px;dialogHeight:380px;status:no;help:no;"); if(dateString=="0")return; //treck.value = dateString; document.getElementById(idName).value = dateString; } function selectDateS(contextPath,idName){ var yyyy=new Array(2); //yyyy[1]="yyyy-MM-dd h:m"; yyyy[1]="yyyy-MM"; var today = new Date(); var theYear = today.getYear(); var theMonth = today.getMonth() + 1; //var theDay = today.getDate(); //var theHour = "00";//today.getHours(); //var theMinute = "00";//today.getMinutes(); yyyy[0]=theYear+"-"+theMonth; var dateString = showModalDialog(contextPath+"/component/calendar/calendar.htm",yyyy,"dialogWidth:309px;dialogHeight:380px;status:no;help:no;"); if(dateString=="0")return; //treck.value = dateString; document.getElementById(idName).value = dateString; } //封装prototype nwe Ajax.Request提交 function ajaxRequest(url,pars,showReponse){ var myAjax = new Ajax.Request( url, { method: "post", parameters: pars, onComplete: showResponse }); } function ChangeAllChecked(objTr,tabId){ var thick = document.getElementById("checkbox_"+objTr.id); var tabObj = eval(tabId); var cellIndex = thick.parentElement.cellIndex; var tHead= tabObj.getElementsByTagName("thead")[0]; var tBody = tabObj.getElementsByTagName("tbody")[0]; if(thick.checked){ var checkAllFlag = true; for(var i=0;i<tBody.rows.length;i++) { if(!tBody.rows[i].cells[cellIndex].childNodes[0].checked){ checkAllFlag = false; break; } } if(checkAllFlag){ tHead.rows[0].cells[cellIndex].childNodes[0].checked = thick.checked; tBody.checkAllFlag = thick.checked; } }else{ tHead.rows[0].cells[cellIndex].childNodes[0].checked = thick.checked; } } function setObjStatus(objArray) { $("li" + objArray[0]).className="current"; $("div" + objArray[0]).style.display=""; for(i = 1;i < objArray.length;i++) { $("li" + objArray[i]).className = null; $("div" + objArray[i]).style.display="none"; } } //验证输入的只能为整数或者小数 function check_num_dot() { if (window.event.keyCode > 57 || window.event.keyCode < 46) { window.event.returnValue = false; } else { if(window.event.keyCode==47) { window.event.returnValue = false; } if(window.event.keyCode==46) { if (window.event.srcElement.value.indexOf(".")!=-1) { window.event.returnValue = false; } } } } //row上的checkBox的onclick事件;改变全选状态 function ChangeChecked(thick,tabId){ var tabObj = eval(tabId); var cellIndex = thick.parentElement.cellIndex; var tHead= tabObj.getElementsByTagName("thead")[0]; var tBody = tabObj.getElementsByTagName("tbody")[0]; if(thick.checked){ var checkAllFlag = true; for(var i=0;i<tBody.rows.length;i++) { if(!tBody.rows[i].cells[cellIndex].childNodes[0].checked){ checkAllFlag = false; break; } } if(checkAllFlag){ tHead.rows[0].cells[cellIndex].childNodes[0].checked = thick.checked; tBody.checkAllFlag = thick.checked; } }else{ tHead.rows[0].cells[cellIndex].childNodes[0].checked = thick.checked; } } function trselect(objTr,tabID){ if(objTr.style.backgroundColor=="#ffffff" || objTr.style.backgroundColor==""){ objTr.style.backgroundColor="#E5F0FD"; document.getElementById("checkbox_"+objTr.id).checked = true; }else{ objTr.style.backgroundColor="#ffffff"; document.getElementById("checkbox_"+objTr.id).checked = false; } } //编码转换 传换后的格式像%E7%A7%98%E5%AF%86这种在后台用java.net.URLDecoder.decode(str, "UTF-8")转回来; function encodeStr(str){ if(str != ""){ return encodeURI(encodeURI(str)); }else{ return ""; } } //输入的必须为整数 function iswholeNumber(){ if((event.keyCode<=47)||(event.keyCode>57)){ event.returnValue=false; } } //删除方法 function del(url,pars){ var myAjax = new Ajax.Request( url, { method: "post", parameters: pars, onComplete: showReponse }); } //消息提示 function pubMsg(url,pars){ var myAjax = new Ajax.Request( url, { method: "post", parameters: pars, onComplete: showReponse }); } //格式化日期(2009-12-16 00:00:00 格式化后 2009-12-16) function changeDate(Obj){ var str =Obj; str = str.substr(0,str.lastIndexOf ("-")+3); return str; } //初始化一个日期(2009-12-16) function getDate(){ var now= new Date(); var year=now.getYear(); var month=now.getMonth()+1; var day=now.getDate(); if(month<10){ month = "0"+month; } if(day<10){ day = "0"+day; } return year+"-"+month+"-"+day; } //两个日期进行比较 function checkdate(sdate,edate){ //得到日期值并转化成日期格式,replace(/\-/g, "\/")是根据验证表达式把日期转化成长日期格式,这样 //再进行判断就好判断了 var sDate = new Date(sdate.replace(/\-/g, "\/")); var eDate = new Date(edate.replace(/\-/g, "\/")); if(sDate > eDate){ return true; }else{ return false; } } function fomatMoneys(money,name){ if(/[^0-9\.]/.test(money)) return money; money=money.replace(/^(\d*)$/,"$1."); money=(money+"00").replace(/(\d*\.\d\d)\d*/,"$1"); money=money.replace(".",","); var re=/(\d)(\d{3},)/; while(re.test(money)){ money=money.replace(re,"$1,$2"); } money = money.replace(/,(\d\d)$/,".$1"); $(name).value = money; //return "¥" + money.replace(/^\./,"0.") } function fomatMoneyeval(money){ if(/[^0-9\.]/.test(money)) return money; money=money.replace(/^(\d*)$/,"$1."); money=(money+"00").replace(/(\d*\.\d\d)\d*/,"$1"); money=money.replace(".",","); var re=/(\d)(\d{3},)/; while(re.test(money)){ money=money.replace(re,"$1,$2"); } money=money.replace(/,(\d\d)$/,".$1"); return money; } //校验定位 function isSelectFocus(obj){ try{ $(obj).select(); $(obj).focus(); }catch(e){ $(obj).focus(); } } //清除带有选择按钮的文本框的值以及清除该文本的隐藏Id值 //@param objId 文本隐藏ID(属性)名称 //@param objName 文本的(属性)昵称 function clearText(objId,objName){ $(objId).value = ""; $(objName).value = ""; }
JavaScript
/** * �ж�Email��ʽ�Ƿ���ȷ * @param email * @return */ function isEmail(eMail) { var regex = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/; if(regex.exec(eMail)) return true; return false; } /** * �ж����������ʽ�Ƿ���ȷ * @param ZipCode * @return */ function isZipCode(zipCode) { var regex = /^[1-9]\d{5}$/; if(regex.exec(zipCode)) return true; return false; } /** * �ж��Ƿ������ַ�÷���ֻ���ж�һ���� * @param chCode * @return */ function isChCode(chCode) { var regex = /[\u4e00-\u9fa5]/; if(regex.exec(chCode)) return true; return false; } /** * �ж��Ƿ�Ϊ˫�ֽ��ַ�÷���ֻ���ж�һ�ַ� * @param doubleChar * @return */ function isDoubleChar(doubleChar) { var regex = /[^\x00-\xff]/; if(regex.exec(doubleChar)) return true; return false; } /** * �ж��Ƿ�Ϊ�հ��� * @param charStr * @return */ function isBlankSpace(blankStr) { var regex = /\n\s*\r/; if(regex.exec(blankStr)) return true; return false; } /** * �ж�URL��ʽ�Ƿ���ȷ * @param inUrl * @return */ function isURL(inUrl) { var regex = "^((https|http|ftp|rtsp|mms)://)" + "(([0-9a-z_!~*��().&=+$%-]+: )?[0-9a-z_!~*��().&=+$%-]+@)?" //ftp��user@ + "(([0-9]{1,3}\\.){3}[0-9]{1,3}" // IP��ʽ��URL- 199.194.52.184 + "|" // ����IP��DOMAIN������ + "([0-9a-z_!~*��()-]+\\.)*" // ����- www. + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\\.[a-z]{2,6})" // �������� + "(:[0-9]{1,4})?" // �˿�- :80 + "((/?)|(/[0-9a-zA-Z_!~*��().;?:@&=+$,%#-]+))$"; var re=new RegExp(regex); if (re.test(str_url)) return true; return false; } /** * ƥ���ʺ��Ƿ�Ϸ�(��ĸ��ͷ������5-16�ֽڣ�������ĸ�����»���) * @param account * @return */ function isAccount(account) { var regex = /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/; if(regex.exec(account)) return true; return false; } /** * ƥ����ڹ̶��绰���� * @param telPhone * @return */ function isTelPhone(telPhone) { var regex = /\d{3}-\d{8}|\d{4}-\d{7}|\d{4}-{8}/; if(regex.exec(telPhone)) return true; return false; } function isTelPhoneOrMobile(phone) { var regex = /^(13[0-9]|15[0|3|6|8|9])\d{8}$/; if(regex.exec(phone)) return true; regex = /\d{3}-\d{8}|\d{4}-\d{7}|\d{4}-{8}/; if(regex.exec(phone)) return true; return false; } /** * ƥ�����֤ * @param idCard * @return */ function isIDCard(idCard) { var regex = /^(\d{15})|(\d{17}(\d|x|X))$/; if(regex.exec(idCard)) return true; return false; } /** * ƥ��ip��ַ * @param ip * @return */ function isIPAddr(ip) { var regex = /\d+\.\d+\.\d+\.\d+/; if(regex.exec(ip)) return true; return false; } /** * �ж������ֻ�����ʽ�Ƿ���ȷ * @param mobile * @return */ function isMobile(mobile) { var regex = /^(13[0-9]|15[0|3|6|8|9])\d{8}$/; if(regex.exec(mobile)) return true; return false; } /** * �Ǹ����������� + 0�� * @param negative * @return */ function isNoNegInt(negative) { var regex = /^\d+$/; if(regex.exec(negative)) return true; return false; } /** * ������ * @param integer * @return */ function isPlusInt(integer) { var regex = /^[0-9]*[1-9][0-9]*$/; if(regex.exec(integer)) return true; return false; } /** * ������������ + 0�� * @param integer * @return */ function isNoPlusInt(integer) { var regex = /^((-\d+)|(0+))$/; if(regex.exec(integer)) return true; return false; } /** * ������ * @param integer * @return */ function isNegInt(integer) { var regex = /^-[0-9]*[1-9][0-9]*$/; if(regex.exec(integer)) return true; return false; } /** * ���� * @param integer * @return */ function isInteger(integer) { var regex = /^-?\d+$/; if(regex.exec(integer)) return true; return false; } /** * �Ǹ������������ + 0�� * @param floatStr * @return */ function isNoNegFloat(floatStr) { var regex = /^\d+(\.\d+)?$/; if(regex.exec(floatStr)) return true; return false; } /** * ����� * @param floatStr * @return */ function isPlusFloat(floatStr) { var regex = /^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$/; if(regex.exec(floatStr)) return true; return false; } /** * ������������ + 0�� * @param floatStr * @return */ function isNoPlusFloat(floatStr) { var regex = /^((-\d+(\.\d+)?)|(0+(\.0+)?))$/; if(regex.exec(floatStr)) return true; return false; } /** * �������� * @param floatStr * @return */ function isNegFloat(floatStr) { var regex = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; if(regex.exec(floatStr)) return true; return false; } /** * ������ * @param floatStr * @return */ function isFloat(floatStr) { var regex = /^(-?\d+)(\.\d+)?$/; if(regex.exec(floatStr)) return true; return false; } /** * ��26��Ӣ����ĸ��ɵ��ַ� * @param inStr * @return */ function isAZazStr(inStr) { var regex = /^[A-Za-z]+$/; if(regex.exec(inStr)) return true; return false; } /** * ��26��Ӣ����ĸ�Ĵ�д��ɵ��ַ� * @param inStr * @return */ function isAZStr(inStr) { var regex = /^[A-Z]+$/; if(regex.exec(inStr)) return true; return false; } /** * ��26��Ӣ����ĸ��Сд��ɵ��ַ� * @param inStr * @return */ function isazStr(inStr) { var regex = /^[a-z]+$/; if(regex.exec(inStr)) return true; return false; } /** * �����ֺ�26��Ӣ����ĸ��ɵ��ַ� * @param inStr * @return */ function isAZaz09Str(inStr) { var regex = /^[A-Za-z0-9]+$/; if(regex.exec(inStr)) return true; return false; } /** * �����֡�26��Ӣ����ĸ�����»�����ɵ��ַ� * @param inStr * @return */ function is09AZ_azStr(inStr) { var regex = /^\w+$/; if(regex.exec(inStr)) return true; return false; } /** * ����Ч�鲻Ϊ�� * @param inStr * @return */ function isInput(input){ if(input!=""&&input!=null){ return false; }else{ return true; } } /** * *��ȡ����ֵ���ֽڸ��� */ function getByte(str) { return str.replace(/[^\x00-\xff]/g,"**").length; }
JavaScript
var Aaw = 0; function Alf() { return (self.innerHeight || document.documentElement.clientHeight || document.body.clientHeight); } function Aml() { return (document.documentElement.offsetWidth || document.body.offsetWidth); } /***********对话框移动效果***************/ var isworking=0;//1拖动状态 var topmore=0;//top Number var leftmore=0;//top Number //mouse down or up function mouseDownOrUp(index){ if(index==1)//mouse down { isworking=1; //原始坐标 var divy=parseInt($("tipIFrame").style.top.substring(0,$("tipIFrame").style.top.indexOf("px"))); var divx=parseInt($("tipIFrame").style.left.substring(0,$("tipIFrame").style.left.indexOf("px"))); //鼠标坐标 var eventy=parseInt(event.y); var eventx=parseInt(event.x); //坐标差 topmore=(eventy-divy); leftmore=(eventx-divx); }else//mouse up { isworking=0; } } //drag function dialogmove(event){ if(isworking==1) { //鼠标坐标 var eventy=parseInt(event.y); var eventx=parseInt(event.x); //坐标差 eventx=eventx-leftmore; eventy=eventy-topmore; $("tipIFrame").style.top=eventy+"px"; $("tipIFrame").style.left=eventx+"px"; } } /////////////////////////////////////// function MyAlert(msg, tit, okCallbak, isConfirm, def, cancelCallbak) { setHideEleByTagName("select","none"); var br = document.createElement("DIV"); br.id = "dvMyAlert"; document.body.appendChild(br); tit = tit || "系统提示"; var u = ""; u += "<div class=\"main1\" id=\"tipIFrame\" style=\"width:300px;position:absolute;z-index:999\" id=\"sysMsgWin\">"; u += "<div class=\"title\" style=\"width:303px\"><div class=\"title_l\"></div><div class=\"title_m\">"; // u += "<div class=\"title\" style='width:303px;cursor: move;'><div class=\"title_l\"></div><div class=\"title_m\" onmousedown='mouseDownOrUp(1);' onmouseup='mouseDownOrUp(2);' onmousemove='dialogmove(event);' onselectstart='return false;' >"; u += tit + "</div><div id=\"btnSysInfoClose\" title=\"关闭\" class=\"title_c\"></div></div>"; u += "<div class=\"content_no\"><table bgcolor=\"ffffff\" width=\"100%\" border=\"0\"><tr><td height=\"80\" width=\"50\" valign=\"middle\">"; u += "<div class=\"img_info\" style=\"width:50px;height:50px\"></div></td><td style=\"word-break:break-all;\">"; u += msg + "</td></tr><tr><td colspan=\"2\" align=\"center\">"; u += "<input type=\"button\" value=\" 确 定 \" class=\"button2\" id=\"btnSysMsgOk\" />"; if(isConfirm){ u += "&nbsp;&nbsp;&nbsp;&nbsp;<input type=\"button\" value=\" 取 消 \" class=\"button2\" id=\"btnSysMsgNo\" />"; } u += "</td></tr></table></div></div>"; var Aok = "100%"; var Anc = "100%"; if (document.body.scrollHeight > Alf()) { Anc = document.body.scrollHeight; } var Abc = ""; Abc = "-moz-opacity:0.07;"; Abc += "filter:alpha(opacity=7);"; u += "<div style=\"position:absolute;z-index:998;top:0;left:0;width:" + Aok + ";height:" + Anc + ";" + Abc + "background-color:#000000\"></div>"; br.innerHTML = u; var ag = br.firstChild; var h = ag.offsetHeight; var w = ag.offsetWidth; var scrollTop = document.body.scrollTop; var x = (Aml() - w) / 2; var y = (Alf() - h) / 2 + scrollTop; ag.style.left = x + "px"; ag.style.top = y + "px"; if(!isConfirm){ $("btnSysMsgOk").focus(); $("btnSysInfoClose").onclick = function () { document.body.removeChild(br); if (okCallbak) { okCallbak(); } setHideEleByTagName("select",""); return false; }; $("btnSysMsgOk").onclick = function () { $("btnSysInfoClose").onclick(); }; }else{ if(def){ $("btnSysMsgOk").focus(); } $("btnSysMsgNo").focus(); $("btnSysMsgOk").onclick = function () { document.body.removeChild(br); if (okCallbak) { okCallbak(); } setHideEleByTagName("select",""); return false; }; $("btnSysInfoClose").onclick = function(){ document.body.removeChild(br); if (cancelCallbak) { cancelCallbak(); } setHideEleByTagName("select",""); return false; } $("btnSysMsgNo").onclick = function () { $("btnSysInfoClose").onclick(); }; } return false; }
JavaScript
/*****************处理(读)(写)权限********************/ //writeOrRead(); function writeOrRead(){ var framelength=window.parent.window.frames.length; if(framelength<=1)//主页 return; var objectframe=window.parent.window.frames[framelength-1];//获得最后一个 也就是当前打开的那个 //当前菜单功能模块ID var ignmkdm=(objectframe.parent.window.document.getElementsByTagName("iframe")[framelength-1].getAttribute("specialdm")); addListener(window, 'load', operatefunction); } //添加事件 function addListener (element, event, fn) { if (window.attachEvent) { element.attachEvent('on' + event, fn); } else { element.addEventListener(event, fn, false); } } function showDivWindow(url,width,height,title){ tipsWindown(title,"id:text",width,height,"true","","true","id",url,height,'no'); } function operatefunction(){ //处理DIV var alldiv=window.document.getElementsByTagName("div");//获得全部DIV for(g=0;g<alldiv.length;g++) { var perdiv=alldiv[g]; if(perdiv.getAttribute("classname")=="buttonbox")//循环判断每个DIV 找到功能区 { try{ var manarea=perdiv.getElementsByTagName("ul"); //perdiv.innerText="";//删除功能菜单 }catch(e){} break; } } } /*************************************/ var sort_col = null;//排序列(对象) var curr_row = null;//选中行(对象) var cur_bgc = "#F8E2C2";//选中行背景(字符串) var cookieValue = "skin1";//皮肤目录(字符串) var maxRowToSort = 200;//最大排序行(数字) var splitSignOne = "!!SplitSignOne!!"; var splitSignTwo = "!!SplitSignTwo!!"; var lastScrollY = 0; var flyLayerHeight = 36; var curr_row = null; var obj_bgc = "#EEEEEE"; var $; var P$; var ie = document.all ? 1 : 0; var ns = document.layers ? 1 : 0; /**JavaScript版本检测*/ if(ie){ var ver = Number(ScriptEngineMajorVersion() + "." + ScriptEngineMinorVersion()); if(ver < 5.5){ location.href = "errMsg.do?errMsg=?????÷°?±?????,????????·???"; } } /**定义公用方法:查找对象(ID)*/ if (!$ && document.getElementById) { $ = function() { var elements = new Array(); for (var i = 0; i < arguments.length; i++) { var element = arguments[i]; if (typeof element == 'string') { element = document.getElementById(element); } if (arguments.length == 1) { return element; } elements.push(element); } return elements; }; } else if (!$ && document.all) { $ = function() { var elements = new Array(); for (var i = 0; i < arguments.length; i++) { var element = arguments[i]; if (typeof element == 'string') { element = document.all[element]; } if (arguments.length == 1) { return element; } elements.push(element); } return elements; }; } if (!P$ && document.getElementById) { P$ = function() { var elements = new Array(); for (var i = 0; i < arguments.length; i++) { var element = arguments[i]; if (typeof element == 'string') { element = window.dialogArguments.document.getElementById(element); } if (arguments.length == 1) { return element; } elements.push(element); } return elements; }; } else if (!P$ && document.all) { P$ = function() { var elements = new Array(); for (var i = 0; i < arguments.length; i++) { var element = arguments[i]; if (typeof element == 'string') { element = window.dialogArguments.document.all[element]; } if (arguments.length == 1) { return element; } elements.push(element); } return elements; }; } /**定义页面初始化公用方法*/ function initCSS() { if (window.dialogArguments){ document.title = document.title + "------(ESC关闭窗口)"; } var search = "style="; if (document.cookie.length > 0) { offset = document.cookie.indexOf(search); if (offset != -1) { offset += search.length; end = document.cookie.indexOf(";", offset); if (end == -1) { end = document.cookie.length; } cookieValue = unescape(document.cookie.substring(offset, end)); } } //window.setInterval("window.status='数字化校园信息平台'",3000); //var tmp = $("csss").href; //tmp = tmp.substring(tmp.indexOf("style"),tmp.length); //$("csss").href = cookieValue + "/" + tmp; } initCSS(); /**设置网页打印的页眉页脚为空 */ function PageSetup(m_Left,m_Right,m_Top,m_Bottom,t_Header,t_Footer){ var chg = 0.03937; var l = (m_Left == null ? 0 : m_Left*chg); var r = (m_Right == null ? 0 : m_Right*chg); var t = (m_Top == null ? 0 : m_Top*chg); var b = (m_Bottom == null ? 0 : m_Bottom*chg); var msg = ""; try{ var HKEY_Root; var HKEY_Path; var HKEY_Key; HKEY_Root="HKEY_CURRENT_USER"; HKEY_Path="\\Software\\Microsoft\\Internet Explorer\\PageSetup\\"; var Wsh=new ActiveXObject("WScript.Shell"); HKEY_Key="margin_left"; Wsh.RegWrite(HKEY_Root+HKEY_Path+HKEY_Key,l); HKEY_Key="margin_right"; Wsh.RegWrite(HKEY_Root+HKEY_Path+HKEY_Key,r); HKEY_Key="margin_top"; Wsh.RegWrite(HKEY_Root+HKEY_Path+HKEY_Key,t); HKEY_Key="margin_bottom"; Wsh.RegWrite(HKEY_Root+HKEY_Path+HKEY_Key,b); HKEY_Key="header"; Wsh.RegWrite(HKEY_Root+HKEY_Path+HKEY_Key,t_Header); HKEY_Key="footer"; Wsh.RegWrite(HKEY_Root+HKEY_Path+HKEY_Key,t_Footer); }catch(e){ msg = "由于您的计算机安全级别设置得太高,系统无法修改本次打印所需的设置。<br>请手动设置。"; alert(msg); } } /**设置网页打印的页眉页脚为默认值 */ function PageSetup_Default() { try { var HKEY_Root; var HKEY_Path; var HKEY_Key; HKEY_Root="HKEY_CURRENT_USER"; HKEY_Path="\\Software\\Microsoft\\Internet Explorer\\PageSetup\\"; var Wsh=new ActiveXObject("WScript.Shell"); HKEY_Key="header"; Wsh.RegWrite(HKEY_Root+HKEY_Path+HKEY_Key,"&w&b页码,&p/&P"); HKEY_Key="footer"; Wsh.RegWrite(HKEY_Root+HKEY_Path+HKEY_Key,"&u&b&d"); } catch(e){ } } /**禁用选择、复制以及右键*/ /* document.onselectstart = function(){ return false; }; document.ondragstart = function(){ return false; }; document.onbeforecopy = function(){ return false; }; document.oncopy = function(){ document.selection.empty(); }; document.onselect = function(){ document.selection.empty(); }; document.oncontextmenu = function(){ return false; }; */ document.onkeypress = function () { if (event.keyCode == 27) { if (window.dialogArguments) { window.close(); return false; } if($("menuCont")){ $("menuCont").style.display = $("menuCont").style.display == "none"?"":"none"; return false; } if(window.parent.$("menuCont")){ window.parent.$("menuCont").style.display = window.parent.$("menuCont").style.display == "none"?"":"none"; return false; } } }; /**定义公用方法:关闭窗口*/ function Close() { var ua = navigator.userAgent; var ie = navigator.appName == "Microsoft Internet Explorer" ? true : false; if (ie) { var IEversion = parseFloat(ua.substring(ua.indexOf("MSIE ") + 5, ua.indexOf(";", ua.indexOf("MSIE ")))); if (IEversion < 5.5) { var str = "<object id=noTipClose classid=\"clsid:ADB880A6-D8FF-11CF-9377-00AA003B7A11\">"; str += "<param name=\"Command\" value=\"Close\"></object>"; document.body.insertAdjacentHTML("beforeEnd", str); document.all.noTipClose.Click(); } else { window.opener = null; window.close(); } } else { window.close(); } } /**定义公用方法:排序*/ function judge_CN(char1, char2, mode) { var charPYStr = "啊阿埃挨哎唉哀皑癌蔼矮艾碍爱隘鞍氨安俺按暗岸胺案肮昂盎凹敖熬翱袄傲奥懊澳芭捌扒叭吧笆八疤巴拔跋靶把耙坝霸罢爸白柏百摆佰败拜稗斑班搬扳般颁板版扮拌伴瓣半办绊邦帮梆榜膀绑棒磅蚌镑傍谤苞胞包褒剥薄雹保堡饱宝抱报暴豹鲍爆杯碑悲卑北辈背贝钡倍狈备惫焙被奔苯本笨崩绷甭泵蹦迸逼鼻比鄙笔彼碧蓖蔽毕毙毖币庇痹闭敝弊必辟壁臂避陛鞭边编贬扁便变卞辨辩辫遍标彪膘表鳖憋别瘪彬斌濒滨宾摈兵冰柄丙秉饼炳病并玻菠播拨钵波博勃搏铂箔伯帛舶脖膊渤泊驳捕卜哺补埠不布步簿部怖擦猜裁材才财睬踩采彩菜蔡餐参蚕残惭惨灿苍舱仓沧藏操糙槽曹草厕策侧册测层蹭插叉茬茶查碴搽察岔差诧拆柴豺搀掺蝉馋谗缠铲产阐颤昌猖场尝常长偿肠厂敞畅唱倡超抄钞朝嘲潮巢吵炒车扯撤掣彻澈郴臣辰尘晨忱沉陈趁衬撑称城橙成呈乘程惩澄诚承逞骋秤吃痴持匙池迟弛驰耻齿侈尺赤翅斥炽充冲虫崇宠抽酬畴踌稠愁筹仇绸瞅丑臭初出橱厨躇锄雏滁除楚础储矗搐触处揣川穿椽传船喘串疮窗幢床闯创吹炊捶锤垂春椿醇唇淳纯蠢戳绰疵茨磁雌辞慈瓷词此刺赐次聪葱囱匆从丛凑粗醋簇促蹿篡窜摧崔催脆瘁粹淬翠村存寸磋撮搓措挫错搭达答瘩打大呆歹傣戴带殆代贷袋待逮怠耽担丹单郸掸胆旦氮但惮淡诞弹蛋当挡党荡档刀捣蹈倒岛祷导到稻悼道盗德得的蹬灯登等瞪凳邓堤低滴迪敌笛狄涤翟嫡抵底地蒂第帝弟递缔颠掂滇碘点典靛垫电佃甸店惦奠淀殿碉叼雕凋刁掉吊钓调跌爹碟蝶迭谍叠丁盯叮钉顶鼎锭定订丢东冬董懂动栋侗恫冻洞兜抖斗陡豆逗痘都督毒犊独读堵睹赌杜镀肚度渡妒端短锻段断缎堆兑队对墩吨蹲敦顿囤钝盾遁掇哆多夺垛躲朵跺舵剁惰堕蛾峨鹅俄额讹娥恶厄扼遏鄂饿恩而儿耳尔饵洱二贰发罚筏伐乏阀法珐藩帆番翻樊矾钒繁凡烦反返范贩犯饭泛坊芳方肪房防妨仿访纺放菲非啡飞肥匪诽吠肺废沸费芬酚吩氛分纷坟焚汾粉奋份忿愤粪丰封枫蜂峰锋风疯烽逢冯缝讽奉凤佛否夫敷肤孵扶拂辐幅氟符伏俘服浮涪福袱弗甫抚辅俯釜斧脯腑府腐赴副覆赋复傅付阜父腹负富讣附妇缚咐噶嘎该改概钙盖溉干甘杆柑竿肝赶感秆敢赣冈刚钢缸肛纲岗港杠篙皋高膏羔糕搞镐稿告哥歌搁戈鸽胳疙割革葛格蛤阁隔铬个各给根跟耕更庚羹埂耿梗工攻功恭龚供躬公宫弓巩汞拱贡共钩勾沟苟狗垢构购够辜菇咕箍估沽孤姑鼓古蛊骨谷股故顾固雇刮瓜剐寡挂褂乖拐怪棺关官冠观管馆罐惯灌贯光广逛瑰规圭硅归龟闺轨鬼诡癸桂柜跪贵刽辊滚棍锅郭国果裹过哈骸孩海氦亥害骇酣憨邯韩含涵寒函喊罕翰撼捍旱憾悍焊汗汉夯杭航壕嚎豪毫郝好耗号浩呵喝荷菏核禾和何合盒貉阂河涸赫褐鹤贺嘿黑痕很狠恨哼亨横衡恒轰哄烘虹鸿洪宏弘红喉侯猴吼厚候后呼乎忽瑚壶葫胡蝴狐糊湖弧虎唬护互沪户花哗华猾滑画划化话槐徊怀淮坏欢环桓还缓换患唤痪豢焕涣宦幻荒慌黄磺蝗簧皇凰惶煌晃幌恍谎灰挥辉徽恢蛔回毁悔慧卉惠晦贿秽会烩汇讳诲绘荤昏婚魂浑混豁活伙火获或惑霍货祸击圾基机畸稽积箕肌饥迹激讥鸡姬绩缉吉极棘辑籍集及急疾汲即嫉级挤几脊己蓟技冀季伎祭剂悸济寄寂计记既忌际妓继纪嘉枷夹佳家加荚颊贾甲钾假稼价架驾嫁歼监坚尖笺间煎兼肩艰奸缄茧检柬碱硷拣捡简俭剪减荐槛鉴践贱见键箭件健舰剑饯渐溅涧建僵姜将浆江疆蒋桨奖讲匠酱降蕉椒礁焦胶交郊浇骄娇嚼搅铰矫侥脚狡角饺缴绞剿教酵轿较叫窖揭接皆秸街阶截劫节茎睛晶鲸京惊精粳经井警景颈静境敬镜径痉靖竟竞净炯窘揪究纠玖韭久灸九酒厩救旧臼舅咎就疚鞠拘狙疽居驹菊局咀矩举沮聚拒据巨具距踞锯俱句惧炬剧捐鹃娟倦眷卷绢撅攫抉掘倔爵桔杰捷睫竭洁结解姐戒藉芥界借介疥诫届巾筋斤金今津襟紧锦仅谨进靳晋禁近烬浸尽劲荆兢觉决诀绝均菌钧军君峻俊竣浚郡骏喀咖卡咯开揩楷凯慨刊堪勘坎砍看康慷糠扛抗亢炕考拷烤靠坷苛柯棵磕颗科壳咳可渴克刻客课肯啃垦恳坑吭空恐孔控抠口扣寇枯哭窟苦酷库裤夸垮挎跨胯块筷侩快宽款匡筐狂框矿眶旷况亏盔岿窥葵奎魁傀馈愧溃坤昆捆困括扩廓阔垃拉喇蜡腊辣啦莱来赖蓝婪栏拦篮阑兰澜谰揽览懒缆烂滥琅榔狼廊郎朗浪捞劳牢老佬姥酪烙涝勒乐雷镭蕾磊累儡垒擂肋类泪棱楞冷厘梨犁黎篱狸离漓理李里鲤礼莉荔吏栗丽厉励砾历利傈例俐痢立粒沥隶力璃哩俩联莲连镰廉怜涟帘敛脸链恋炼练粮凉梁粱良两辆量晾亮谅撩聊僚疗燎寥辽潦了撂镣廖料列裂烈劣猎琳林磷霖临邻鳞淋凛赁吝拎玲菱零龄铃伶羚凌灵陵岭领另令溜琉榴硫馏留刘瘤流柳六龙聋咙笼窿隆垄拢陇楼娄搂篓漏陋芦卢颅庐炉掳卤虏鲁麓碌露路赂鹿潞禄录陆戮驴吕铝侣旅履屡缕虑氯律率滤绿峦挛孪滦卵乱掠略抡轮伦仑沦纶论萝螺罗逻锣箩骡裸落洛骆络妈麻玛码蚂马骂嘛吗埋买麦卖迈脉瞒馒蛮满蔓曼慢漫谩芒茫盲氓忙莽猫茅锚毛矛铆卯茂冒帽貌贸么玫枚梅酶霉煤没眉媒镁每美昧寐妹媚门闷们萌蒙檬盟锰猛梦孟眯醚靡糜迷谜弥米秘觅泌蜜密幂棉眠绵冕免勉娩缅面苗描瞄藐秒渺庙妙蔑灭民抿皿敏悯闽明螟鸣铭名命谬摸摹蘑模膜磨摩魔抹末莫墨默沫漠寞陌谋牟某拇牡亩姆母墓暮幕募慕木目睦牧穆拿哪呐钠那娜纳氖乃奶耐奈南男难囊挠脑恼闹淖呢馁内嫩能妮霓倪泥尼拟你匿腻逆溺蔫拈年碾撵捻念娘酿鸟尿捏聂孽啮镊镍涅您柠狞凝宁拧泞牛扭钮纽脓浓农弄奴努怒女暖虐疟挪懦糯诺哦欧鸥殴藕呕偶沤啪趴爬帕怕琶拍排牌徘湃派攀潘盘磐盼畔判叛乓庞旁耪胖抛咆刨炮袍跑泡呸胚培裴赔陪配佩沛喷盆砰抨烹澎彭蓬棚硼篷膨朋鹏捧碰坯砒霹批披劈琵毗啤脾疲皮匹痞僻屁譬篇偏片骗飘漂瓢票撇瞥拼频贫品聘乒坪苹萍平凭瓶评屏坡泼颇婆破魄迫粕剖扑铺仆莆葡菩蒲埔朴圃普浦谱曝瀑期欺栖戚妻七凄漆柒沏其棋奇歧畦崎脐齐旗祈祁骑起岂乞企启契砌器气迄弃汽泣讫掐洽牵扦钎铅千迁签仟谦乾黔钱钳前潜遣浅谴堑嵌欠歉枪呛腔羌墙蔷强抢橇锹敲悄桥瞧乔侨巧鞘撬翘峭俏窍切茄且怯窃钦侵亲秦琴勤芹擒禽寝沁青轻氢倾卿清擎晴氰情顷请庆琼穷秋丘邱球求囚酋泅趋区蛆曲躯屈驱渠取娶龋趣去圈颧权醛泉全痊拳犬券劝缺炔瘸却鹊榷确雀裙群然燃冉染瓤壤攘嚷让饶扰绕惹热壬仁人忍韧任认刃妊纫扔仍日戎茸蓉荣融熔溶容绒冗揉柔肉茹蠕儒孺如辱乳汝入褥软阮蕊瑞锐闰润若弱撒洒萨腮鳃塞赛三叁伞散桑嗓丧搔骚扫嫂瑟色涩森僧莎砂杀刹沙纱傻啥煞筛晒珊苫杉山删煽衫闪陕擅赡膳善汕扇缮墒伤商赏晌上尚裳梢捎稍烧芍勺韶少哨邵绍奢赊蛇舌舍赦摄射慑涉社设砷申呻伸身深娠绅神沈审婶甚肾慎渗声生甥牲升绳省盛剩胜圣师失狮施湿诗尸虱十石拾时什食蚀实识史矢使屎驶始式示士世柿事拭誓逝势是嗜噬适仕侍释饰氏市恃室视试收手首守寿授售受瘦兽蔬枢梳殊抒输叔舒淑疏书赎孰熟薯暑曙署蜀黍鼠属术述树束戍竖墅庶数漱恕刷耍摔衰甩帅栓拴霜双爽谁水睡税吮瞬顺舜说硕朔烁斯撕嘶思私司丝死肆寺嗣四伺似饲巳松耸怂颂送宋讼诵搜艘擞嗽苏酥俗素速粟僳塑溯宿诉肃酸蒜算虽隋随绥髓碎岁穗遂隧祟孙损笋蓑梭唆缩琐索锁所塌他它她塔獭挞蹋踏胎苔抬台泰酞太态汰坍摊贪瘫滩坛檀痰潭谭谈坦毯袒碳探叹炭汤塘搪堂棠膛唐糖倘躺淌趟烫掏涛滔绦萄桃逃淘陶讨套特藤腾疼誊梯剔踢锑提题蹄啼体替嚏惕涕剃屉天添填田甜恬舔腆挑条迢眺跳贴铁帖厅听烃汀廷停亭庭挺艇通桐酮瞳同铜彤童桶捅筒统痛偷投头透凸秃突图徒途涂屠土吐兔湍团推颓腿蜕褪退吞屯臀拖托脱鸵陀驮驼椭妥拓唾挖哇蛙洼娃瓦袜歪外豌弯湾玩顽丸烷完碗挽晚皖惋宛婉万腕汪王亡枉网往旺望忘妄威巍微危韦违桅围唯惟为潍维苇萎委伟伪尾纬未蔚味畏胃喂魏位渭谓尉慰卫瘟温蚊文闻纹吻稳紊问嗡翁瓮挝蜗涡窝我斡卧握沃巫呜钨乌污诬屋无芜梧吾吴毋武五捂午舞伍侮坞戊雾晤物勿务悟误昔熙析西硒矽晰嘻吸锡牺稀息希悉膝夕惜熄烯溪汐犀檄袭席习媳喜铣洗系隙戏细瞎虾匣霞辖暇峡侠狭下厦夏吓掀锨先仙鲜纤咸贤衔舷闲涎弦嫌显险现献县腺馅羡宪陷限线相厢镶香箱襄湘乡翔祥详想响享项巷橡像向象萧硝霄削哮嚣销消宵淆晓小孝校肖啸笑效楔些歇蝎鞋协挟携邪斜胁谐写械卸蟹懈泄泻谢屑薪芯锌欣辛新忻心信衅星腥猩惺兴刑型形邢行醒幸杏性姓兄凶胸匈汹雄熊休修羞朽嗅锈秀袖绣墟戌需虚嘘须徐许蓄酗叙旭序畜恤絮婿绪续轩喧宣悬旋玄选癣眩绚靴薛学穴雪血勋熏循旬询寻驯巡殉汛训讯逊迅压押鸦鸭呀丫芽牙蚜崖衙涯雅哑亚讶焉咽阉烟淹盐严研蜒岩延言颜阎炎沿奄掩眼衍演艳堰燕厌砚雁唁彦焰宴谚验殃央鸯秧杨扬佯疡羊洋阳氧仰痒养样漾邀腰妖瑶摇尧遥窑谣姚咬舀药要耀椰噎耶爷野冶也页掖业叶曳腋夜液一壹医揖铱依伊衣颐夷遗移仪胰疑沂宜姨彝椅蚁倚已乙矣以艺抑易邑屹亿役臆逸肄疫亦裔意毅忆义益溢诣议谊译异翼翌绎茵荫因殷音阴姻吟银淫寅饮尹引隐印英樱婴鹰应缨莹萤营荧蝇迎赢盈影颖硬映哟拥佣臃痈庸雍踊蛹咏泳涌永恿勇用幽优悠忧尤由邮铀犹油游酉有友右佑釉诱又幼迂淤于盂榆虞愚舆余俞逾鱼愉渝渔隅予娱雨与屿禹宇语羽玉域芋郁吁遇喻峪御愈欲狱育誉浴寓裕预豫驭鸳渊冤元垣袁原援辕园员圆猿源缘远苑愿怨院曰约越跃钥岳粤月悦阅耘云郧匀陨允运蕴酝晕韵孕匝砸杂栽哉灾宰载再在咱攒暂赞赃脏葬遭糟凿藻枣早澡蚤躁噪造皂灶燥责择则泽贼怎增憎曾赠扎喳渣札轧铡闸眨栅榨咋乍炸诈摘斋宅窄债寨瞻毡詹粘沾盏斩辗崭展蘸栈占战站湛绽樟章彰漳张掌涨杖丈帐账仗胀瘴障招昭找沼赵照罩兆肇召遮折哲蛰辙者锗蔗这浙珍斟真甄砧臻贞针侦枕疹诊震振镇阵蒸挣睁征狰争怔整拯正政帧症郑证芝枝支吱蜘知肢脂汁之织职直植殖执值侄址指止趾只旨纸志挚掷至致置帜峙制智秩稚质炙痔滞治窒中盅忠钟衷终种肿重仲众舟周州洲诌粥轴肘帚咒皱宙昼骤珠株蛛朱猪诸诛逐竹烛煮拄瞩嘱主著柱助蛀贮铸筑住注祝驻抓爪拽专砖转撰赚篆桩庄装妆撞壮状椎锥追赘坠缀谆准捉拙卓桌琢茁酌啄着灼浊兹咨资姿滋淄孜紫仔籽滓子自渍字鬃棕踪宗综总纵邹走奏揍租足卒族祖诅阻组钻纂嘴醉最罪尊遵昨左佐柞做作坐座"; var charSet = charPYStr; for (var n = 0; n < (char1.length > char2.length ? char1.length : char2.length); n++) { if (char1.charAt(n) != char2.charAt(n)) { if (mode) { return (charSet.indexOf(char1.charAt(n)) > charSet.indexOf(char2.charAt(n)) ? 1 : -1); } else { return (charSet.indexOf(char1.charAt(n)) < charSet.indexOf(char2.charAt(n)) ? 1 : -1); } break; } } return (0); } function tableSort(the_td) { try{ arrowUp = document.createElement("SPAN"); arrowUp.innerHTML = "5"; arrowUp.style.cssText = " PADDING-RIGHT: 0px; MARGIN-TOP: -3px; PADDING-LEFT: 0px; FONT-SIZE: 10px; MARGIN-BOTTOM: 2px; PADDING-BOTTOM: 2px; OVERFLOW: hidden; WIDTH: 10px; COLOR: blue; PADDING-TOP: 0px; FONT-FAMILY: webdings; HEIGHT: 11px"; arrowDown = document.createElement("SPAN"); arrowDown.innerHTML = "6"; arrowDown.style.cssText = " PADDING-RIGHT: 0px; MARGIN-TOP: -3px; PADDING-LEFT: 0px; FONT-SIZE: 10px; MARGIN-BOTTOM: 2px; PADDING-BOTTOM: 2px; OVERFLOW: hidden; WIDTH: 10px; COLOR: blue; PADDING-TOP: 0px; FONT-FAMILY: webdings; HEIGHT: 11px"; the_td.mode = !the_td.mode; var cur_col = the_td.cellIndex; var the_table = getPapaElement(the_td, "table"); if (the_table.rows.length > maxRowToSort) { if (!confirm("当前表的行数超过" + maxRowToSort + "行,排序将耗费比较长的时间,确定要排序吗?")) { return false; } } if (sort_col != null) { with (the_table.rows[0].cells[sort_col]) { removeChild(lastChild); } } if(the_table.rows[1].cells[1]){ with (the_table.rows[0].cells[cur_col]) { appendChild(the_td.mode ? arrowUp : arrowDown); } sort_tab(the_table, cur_col, the_td.mode); sort_col = cur_col; } }catch(e){} } function sort_tab(the_tab, col, mode) { var tab_arr = new Array(); var i; var start = new Date; var indexSum = 0; var tempSum = 0; var tempText = ""; var checkL=0; if(the_tab.rows[0].cells[0].getElementsByTagName("input")[0].type =="checkbox") { checkL=1; } for(k = 0;k < the_tab.rows[0].cells.length;k++) { tempSum = 0; for(e = 1;e < the_tab.rows.length;e++) { tempText = the_tab.rows[e].cells[k].innerText; tempText = replaceChar(tempText," ",""); if(tempText=="") { continue; } else { tempSum ++; } } if(tempSum > indexSum) { indexSum = tempSum; } } //排序 var l = the_tab.rows.length; if (tempSum == 0) { for (var x = (indexSum + 1); x < l; x = x+1) { the_tab.deleteRow(indexSum + 1); } } else if (indexSum != (l-1)) { for (var x = (tempSum + 1); x < l; x = x+1) { the_tab.deleteRow(tempSum + 1); } } //排序 for (i = 1; i < the_tab.rows.length; i++) { //var tempText2 = the_tab.rows[i].cells[col].innerText; //tempText2 = replaceChar(tempText2," ",""); //if(tempText2 != "") { tab_arr.push(new Array(the_tab.rows[i].cells[col].innerText.toLowerCase(), the_tab.rows[i])); //} } tab_arr.sort(SortArr(mode)); /*if(tab_arr.length < indexSum) { for(d = indexSum - tab_arr.length; d >= 1;d--) { tab_arr.push(new Array(" ", the_tab.lastChild)); } }*/ /*if(mode) { for (i = tab_arr.length - 1; i >= 0; i--) { the_tab.lastChild.appendChild(tab_arr[i][1]); } } else {*/ for (i = 0; i < tab_arr.length; i++) { the_tab.lastChild.appendChild(tab_arr[i][1]); } //排序 if (tempSum == 0) { for(var y = (indexSum + 1); y < l; y = y+1) { var tr=document.createElement("tr"); for(var z = 0; z < the_tab.rows[0].cells.length; z = z+1) { var td=document.createElement("td"); td.align="center"; if(checkL > 0 && z == 0) { td.innerHTML="<input type=\"checkbox\" disabled=true>"; } else { td.innerHTML="&nbsp;&nbsp;"; } tr.appendChild(td); } the_tab.lastChild.appendChild(tr); } } else if (indexSum != (l-1)) { for(var y = (tempSum + 1); y < l; y = y+1) { var tr=document.createElement("tr"); for(var z = 0; z < the_tab.rows[0].cells.length; z = z+1) { var td=document.createElement("td"); td.align="center"; if(checkL > 0 && z==0) { td.innerHTML="<input type=\"checkbox\" disabled=true>"; } else { td.innerHTML="&nbsp;&nbsp;"; } tr.appendChild(td); } the_tab.lastChild.appendChild(tr); } } //排序 //} } function SortArr(mode) { return function (arr1, arr2) { var flag; var a, b; a = arr1[0]; b = arr2[0]; if (/^(\+|-)?\d+($|\.\d+$)/.test(a) && /^(\+|-)?\d+($|\.\d+$)/.test(b)) { a = eval(a); b = eval(b); flag = mode ? (a > b ? 1 : (a < b ? -1 : 0)) : (a < b ? 1 : (a > b ? -1 : 0)); } else { a = replaceChar(a.toString()," ",""); b = replaceChar(b.toString()," ",""); if (a.charCodeAt(0) >= 19968 && b.charCodeAt(0) >= 19968) { flag = judge_CN(a, b, mode); } else { flag = mode ? (a > b ? 1 : (a < b ? -1 : 0)) : (a < b ? 1 : (a > b ? -1 : 0)); } } return flag; }; } /**定义公用方法:获取父对象*/ function getPapaElement(the_ele, the_tag) { the_tag = the_tag.toLowerCase(); if (the_ele.tagName.toLowerCase() == the_tag) { return the_ele; } while (the_ele = the_ele.offsetParent) { if (the_ele.tagName.toLowerCase() == the_tag) { return the_ele; } } return (null); } /**定义公用方法:行点击*/ function rowOnClick(objTr) { if (curr_row != null && curr_row.tagName.toLowerCase() == "tr") { curr_row.style.backgroundColor = obj_bgc; } curr_row = objTr; obj_bgc = curr_row.style.backgroundColor; curr_row.style.backgroundColor = cur_bgc; try{ var obj = event.srcElement? event.srcElement : event.target; var chkBox = curr_row.getElementsByTagName("input"); if(!$("checkBoxStatus") || ($("checkBoxStatus") && $("checkBoxStatus").value!="no")) { for(var i = 0; i < chkBox.length; i++){ if(obj.tagName=="INPUT" && chkBox[i].type=="checkbox"){//事件源 chkBox[i].checked = !chkBox[i].checked; } } } }catch(e){ } } /**定义公用方法:替换字符串*/ function replaceChar(conversionString, inChar, outChar) { var convertedString = conversionString.split(inChar); convertedString = convertedString.join(outChar); return convertedString; } /**判断浏览器类型及版本*/ function browserinfo(){ var Browser_Name=navigator.appName; var Browser_Version=parseFloat(navigator.appVersion); var Browser_Agent=navigator.userAgent; var Actual_Version,Actual_Name; var is_IE=(Browser_Name=="Microsoft Internet Explorer"); var is_NN=(Browser_Name=="Netscape"); if(is_NN){ if(Browser_Version>=5.0){ var Split_Sign=Browser_Agent.lastIndexOf("/"); var Version=Browser_Agent.indexOf(" ",Split_Sign); var Bname=Browser_Agent.lastIndexOf(" ",Split_Sign); Actual_Version=Browser_Agent.substring(Split_Sign+1,Version); Actual_Name=Browser_Agent.substring(Bname+1,Split_Sign); } else{ Actual_Version=Browser_Version; Actual_Name=Browser_Name; } } else if(is_IE){ var Version_Start=Browser_Agent.indexOf("MSIE"); var Version_End=Browser_Agent.indexOf(";",Version_Start); Actual_Version=Browser_Agent.substring(Version_Start+5,Version_End) Actual_Name=Browser_Name; if(Browser_Agent.indexOf("Maxthon")!=-1){ Actual_Name+="(Maxthon)"; } else if(Browser_Agent.indexOf("Opera")!=-1){ Actual_Name="Opera"; var tempstart=Browser_Agent.indexOf("Opera"); var tempend=Browser_Agent.length; Actual_Version=Browser_Agent.substring(tempstart+6,tempend) } } else{ Actual_Name="Unknown Navigator" Actual_Version="Unknown Version" } navigator.Actual_Name=Actual_Name; navigator.Actual_Version=Actual_Version; this.Name=Actual_Name; this.Version=Actual_Version; } /**定义公用方法:弹出无模式对话框*/ function showTopWin(url, w, h, scro) { var info = ""; //browserinfo(); if(scro!=null){ if(navigator.Actual_Version == "6.0") { info = "status:0;dialogWidth:" + (w + 50) + "px;dialogHeight:" + (h + 50) + "px;help:no;scroll:yes;resizable=1;"; } else { info = "status:0;dialogWidth:" + w + "px;dialogHeight:" + h + "px;help:no;scroll:yes;resizable=1;"; } } else{ if(navigator.Actual_Version == "6.0") { info = "status:0;dialogWidth:" + (w + 50) + "px;dialogHeight:" + (h + 50) + "px;help:no;scroll:no;resizable=1;"; } else { info = "status:0;dialogWidth:" + w + "px;dialogHeight:" + h + "px;help:no;scroll:no;resizable=1;"; } } /*if(url.indexOf("?") != "-1") { url += "&"+Math.random(); } else { url += "?"+Math.random(); }*/ showModalDialog(url, window, info); } /**定义公用方法:弹出新windows窗口*/ function showWindowWin(url,width,height) { if(url.indexOf("?") != "-1") { url += "&"+Math.random(); } else { url += "?"+Math.random(); } vhei=screen.height - 60; vwid=screen.width -10; var prop= ""; if(!width&&height) { prop="toolbar=no,location=no,directories=no,resizable=yes,status=no,menubar=no,scrollbars=yes,left=0,top=0,height="+vhei+",width="+vwid; } else if(!height) { prop="toolbar=no,location=no,directories=no,resizable=yes,status=no,menubar=no,scrollbars=yes,left=0,top=0,height="+vhei+",width="+width; } else if(!width) { prop="toolbar=no,location=no,directories=no,resizable=yes,status=no,menubar=no,scrollbars=yes,left=0,top=0,height="+height+",width="+vwid; } else { prop="toolbar=no,location=no,directories=no,resizable=yes,status=no,menubar=no,scrollbars=yes,left=0,top=0,height="+height+",width="+width; } window.open(url,"",prop); } /**定义公用方法:表单提交*/ function refreshForm(url,tarG) { var tar = document.forms[0].target; document.forms[0].action = url; if(tarG != null){ document.forms[0].target = tarG; } document.forms[0].submit(); document.forms[0].target = tar; } /**定义公用方法:检测子窗口*/ function checkWinType() { if (window.dialogArguments == null || window.parent == null) { alert("非法访问,窗口即将关闭!"); Close(); return false; } } /**定义公用方法:数字格式及边界判断*/ function numFormatChk(obj,msg,minV,maxV,autoFill) { if(obj.value == "" && autoFill == null)obj.value = "0"; var reg1 = /^\d+[.]?\d+$/g; if(obj.value.length == 1){ reg1 = /^\d+$/g; } var str = obj.value; var r1 = str.match(reg1); if(r1 == null){ alert("您输入的" + msg + "不合法,请重新输入!",false,function(){ obj.select(); obj.focus(); }); return false; } var tmpV = parseFloat(str); if(minV != null && tmpV < minV){ alert("您输入的" + msg + "值过小(最小为:" + minV + "),请重新输入!",false,function(){ obj.select(); obj.focus(); }); return false; } if(maxV != null && tmpV > maxV){ alert("您输入的" + msg + "值过大(最大为:" + maxV + "),请重新输入!",false,function(){ obj.select(); obj.focus(); }); return false; } return true; } /**定义公用方法:检验姓名*/ function chkName(obj,msg) { if(obj.value == ""){ alert("请输入" + msg + "!",false,function(){ obj.select(); obj.focus(); }); return false; } var reg1 = /^([\u4e00-\u9fa5]+)(·|\s)?([\u4e00-\u9fa5]+)$/g; var str = obj.value; var r1 = str.match(reg1); if(r1 == null){ alert("您输入的" + msg + "不合法,请重新输入!",false,function(){ obj.select(); obj.focus(); }); return false; } return true; } function chkName2(obj) { var reg1 = /^([\u4e00-\u9fa5]+)(·|\s)?([\u4e00-\u9fa5]+)$/g; var str = obj.value; var r1 = str.match(reg1); if(r1 == null){ return false; } return true; } /**定义公用方法:检验身份证号码*/ function chkSfzh(obj) { var sfzh = obj.value; var OldID; if(sfzh.length == 15){ OldID = sfzh; return true; }else if(sfzh.length == 18){ OldID = sfzh.substring(0, 6) + sfzh.substring(8,sfzh.length-1); }else{ alert("请输入正确的身份证号码!",false,function(){ obj.select(); obj.focus(); }); return false; } var W = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1); var A = new Array("1", "0", "x", "9", "8", "7", "6", "5", "4", "3", "2"); var i, j, S; var NewID, ID, strNF; NewID = OldID.substring(0, 6) + "19" + OldID.substring(6,OldID.length); S = 0; for( i = 0; i <= 16; i++){ j = NewID.substring(i, i+1) * W[i]; S = S + j; } S = S % 11; if(sfzh != NewID + A[S]){ alert("请输入正确的身份证号码!",false,function(){ obj.select(); obj.focus(); }); return false; } return true; } function checkSfz(obj){ if (isNaN(obj.value)) { alert("身份证号输入的不是数字!"); return false; } var len = obj.value.length, re; if (len == 15) re = new RegExp(/^(\d{6})()?(\d{2})(\d{2})(\d{2})(\d{3})$/); else if (len == 18) re = new RegExp(/^(\d{6})()?(\d{4})(\d{2})(\d{2})(\d{3})(\d)$/); else { alert("输入的身份证号数字位数不对!"); return false; } var a = obj.value.match(re); if (a != null) { if (len==15) { var D = new Date("19"+a[3]+"/"+a[4]+"/"+a[5]); var B = D.getYear()==a[3]&&(D.getMonth()+1)==a[4]&&D.getDate()==a[5]; } else { var D = new Date(a[3]+"/"+a[4]+"/"+a[5]); var B = D.getFullYear()==a[3]&&(D.getMonth()+1)==a[4]&&D.getDate()==a[5]; } if (!B) { alert("输入的身份证号 "+ a[0] +" 里出生日期不对!"); return false; } } return true } /**定义公用方法:检验E-Mail*/ function chkEmail(obj,msg) { if(obj.value == ""){ alert("请输入邮箱!",false,function(){ obj.select(); obj.focus(); }); return false; } var reg1 = /^(.+)@(.+)\.(.+)$/g; var str = obj.value; var r1 = str.match(reg1); if(r1 == null){ alert("您输入的" + msg + "邮箱不合法,请重新输入!",false,function(){ obj.select(); obj.focus(); }); return false; } return true; } /**定义公用方法:显示提示信息*/ function setHideEleByTagName(tagName,sty1){ var tmp = document.getElementsByTagName(tagName); for(var i = 0; i < tmp.length; i++){ tmp[i].style.display = sty1; } } function cancelShowTips(){ document.getElementById("tipsConv").style.display="none"; } function showTips(msg) { setHideEleByTagName("select","none"); msg = (msg == null)?"数据处理中,请稍候...":msg; var dd_html = ""; tipsConv = document.createElement("DIV"); tipsConv.id = "tipsConv"; tipsConv.oncontextmenu = function(){return false;}; tipsConv.onSelectstart = function(){return false;}; tipsConv.style.cssText = "background-color:#CCCCCC;position:absolute;z-index:100;filter:alpha(opacity=20);"; tipsConv.style.width = document.body.clientWidth; tipsConv.style.height = document.body.scrollHeight; tipsConv.style.pixelTop = 0; tipsConv.style.left = 0; tipsConv.style.display = "block"; document.body.appendChild(tipsConv); dd_html += "<table border=0 cellpadding=0 cellspacing=1 bgcolor=\"#000000\""; dd_html += "width=\"100%\" height=\"100%\"><tr>"; dd_html += "<td bgcolor=#5C8DBE>"; dd_html += "<marquee align=\"middle\" behavior=\"alternate\" scrollamount=\"2\" style=\"font-size:9pt\">"; dd_html += "<font color=yellow>" dd_html += msg + "</font>"; dd_html += "</marquee></td></tr></table>"; tips = document.createElement("DIV"); tips.id = "tipDiv"; tips.innerHTML = dd_html; tips.style.cssText = "width:200px;height:30px;position:absolute;z-index:100;filter:alpha(opacity=70);"; tips.style.pixelTop = lastScrollY + 120; tips.style.left = (document.body.clientWidth - 200) / 2; tips.style.display = "block"; document.body.appendChild(tips); } function showMsgWin(msg,tit) { setHideEleByTagName("select","none"); tit = (tit == null)?"信息提示...":tit; var dd_html = ""; tipsConv = document.createElement("DIV"); tipsConv.id = "tipsConv"; tipsConv.oncontextmenu = function(){return false;}; tipsConv.onSelectstart = function(){return false;}; tipsConv.style.cssText = "background-color:#CCCCCC;position:absolute;z-index:100;filter:alpha(opacity=20);"; tipsConv.style.width = document.body.clientWidth; tipsConv.style.height = document.body.scrollHeight; tipsConv.style.pixelTop = 0; tipsConv.style.left = 0; tipsConv.style.display = "block"; document.body.appendChild(tipsConv); dd_html += '<center>'; dd_html += '<div class="main1">'; dd_html += ' <div class="title">'; dd_html += ' <div class="title_l"></div>'; dd_html += ' <div class="title_m">' + tit + '</div>'; dd_html += ' <div class="title_r"></div>'; dd_html += ' </div>'; dd_html += ' <div class="content_no" style="height:100%">'; dd_html += ' <p>&nbsp;</p>'; dd_html += ' <font color="red">'; dd_html += ' <p>' + msg + '</p>'; dd_html += ' </font>'; dd_html += ' <p>&nbsp;</p>'; dd_html += ' <p align="center"><a href="javascript:closeTips()">【关 闭】</a> </p>'; dd_html += ' </div>'; dd_html += '</div> '; dd_html += '</center>'; tips = document.createElement("DIV"); tips.id = "tipDiv"; tips.innerHTML = dd_html; tips.style.cssText = "width:390px;position:absolute;z-index:100;filter:alpha(opacity=80);"; tips.style.pixelTop = lastScrollY + 120; tips.style.left = (document.body.offsetWidth - 400) / 2; tips.style.display = "block"; document.body.appendChild(tips); } function closeTips(){ setHideEleByTagName("select",""); if($("tipsConv")){ document.body.removeChild($("tipsConv")); } if($("tipDiv")){ document.body.removeChild($("tipDiv")); } if($("tipIFrame")){ document.body.removeChild($("tipIFrame")); } } /**定义公用方法:判断当前是否选中行*/ function chkCurrRow(){ if(curr_row == null){ alert("此操作需要有选中的行,请选择(单击)要操作的行!"); return false; }else{ var j=0; var tab =document.getElementsByTagName("input"); for(var i = 0;i<tab.length;i++){ if((tab[i].type=="checkbox")&&(tab[i].checked==true)){ tab[i].checked = false; } } var checkedcho = curr_row.getElementsByTagName("input"); for(var m = 0;m<checkedcho.length;m++ ){ if(checkedcho[m].type=="checkbox"){ checkedcho[m].checked = true; } } } return true; } /**定义公用方法:连接字符串*/ function joinTxt(){ var outTxt = ""; if(arguments.length > 1){ for(var i = 1;i < arguments.length;i++){ if(arguments[0] != "" && arguments[i] == ""){ outTxt += (arguments[0] +"!!splitSign!!"); }else{ outTxt += (arguments[i] +"!!splitSign!!"); } } outTxt = outTxt.substring(0,outTxt.length-13); } return outTxt; } /**定义公用方法:初始化年度下拉框*/ function initNdList(id,def){ var idx = 0; var date = new Date(); var year = date.getFullYear(); for(var i = year - 5; i <= year + 5; i++){ $(id).options[$(id).options.length] = new Option(i,i); if(i < def)idx++; } $(id).options[idx].selected = true; } /**定义公用方法:数据导出*/ function dataExport() { document.forms[0].action = "dataExport.do"; document.forms[0].target = "_blank"; document.forms[0].submit(); document.forms[0].target = "_self"; } function dataExpLDSJ() { document.forms[0].action = "dataExpLDSJ.do" document.forms[0].target = "_blank"; document.forms[0].submit(); document.forms[0].target = "_self"; } function initList(hideID, fillID, def) { var tmp1 = $(hideID).value.split(splitSignOne); var tmp2 = new Array; for (i = 1; i < tmp1.length; i++) { tmp2[tmp2.length] = tmp1[i].split(splitSignTwo); } $(fillID).options.length = 0; for (i = 0; i < tmp2.length; i++) { $(fillID).options[$(fillID).options.length] = new Option(tmp2[i][2], tmp2[i][1]); } for (i = 0; i < $(fillID).options.length; i++) { if ($(fillID).options[i].text == def || $(fillID).options[i].value == def) { $(fillID).options[i].selected = true; return; } } } function expTab(the_table, tabTit, titSpan) { /*var HKEY_Root="HKEY_CURRENT_USER"; var HKEY_Path="\\Software\\Microsoft\\Internet Explorer\\PageSetup\\"; var Wsh=new ActiveXObject("WScript.Shell"); var HKEY_Key="header"; Wsh.RegWrite(HKEY_Root+HKEY_Path+HKEY_Key,""); HKEY_Key="footer"; Wsh.RegWrite(HKEY_Root+HKEY_Path+HKEY_Key,""); */ var table_title = (titSpan == null || titSpan == "") ? tabTit : document.getElementById(titSpan).outerHTML; var the_content = "<style media='print'>\n"; the_content += ".noPrin{\n"; the_content += "display:none;}\n"; the_content += "</style>\n"; the_content += "<link rel='stylesheet' rev='stylesheet' href='"+document.getElementById("css").getAttribute("styleserve")+"style/standard/zfoa.css' type='text/css' media='all' />\n"; the_content += "<link rel='icon' href='/favicon.ico' type='image/x-icon' />\n"; the_content += "<link rel='shortcut icon' href='/favicon.ico' type='image/x-icon' />\n"; the_content += "<link rel='stylesheet' href='"+document.getElementById("css").getAttribute("styleserve")+"style/base.css' type='text/css' media='all' />\n"; the_content += "<link rel='stylesheet' href='"+document.getElementById("css").getAttribute("styleserve")+"style/print.css' type='text/css' media='print' />\n"; the_content += "<link rel='stylesheet' href='"+document.getElementById("css").getAttribute("styleserve")+"style/standard/default.css' type='text/css' media='all' />\n"; the_content += "<script type='text/javascript' src='"+document.getElementById("css").getAttribute("styleserve")+"style/pngbug.js'></script>\n"; the_content += "<object id=\"WebBrowser\" width=0 height=0 classid=\"CLSID:8856F961-340A-11D0-A96B-00C04FD705A2\"></object>\n"; the_content += "<center><h3><b>"; the_content += table_title; the_content += "</b></h3>"; the_content += document.all(the_table).outerHTML; the_content = the_content.replace(/ style=\"[^\"]*\"/g, ""); the_content = the_content.replace(/ onclick=\"[^\"]*\"/g, ""); the_content = the_content.replace(/ mode=\"(false|true)"/g, ""); the_content = the_content.replace(/ oBgc=\"[\w#\d]*\"/g, ""); the_content = the_content.replace(/ oFc=\"[\w#\d]*\"/g, ""); the_content = the_content.replace(/<span>(5|6)<\/span>/gi, ""); the_content = the_content.replace(/<DIV contentEditable=false>(.*)<\/DIV>/ig, "$1"); the_content += "\n<br><div class='noPrin'><input type='button' class='button2' value='页面设置' onclick=\"WebBrowser.ExecWB(8,1)\">"; the_content += "<input type='button' class='button2' value='打印预览' onclick=\"WebBrowser.ExecWB(7,1)\">"; the_content += "<input type='button' class='button2' value='直接打印' onclick=\"WebBrowser.ExecWB(6,6)\">"; the_content += "<\/div>"; //confirm(the_content); var newwin = window.open("about:blank", "_blank", ""); newwin.document.open(); newwin.document.write(the_content); newwin.document.close(); newwin = null; } function expAppTab(the_table, tabTit, titSpan) { var table_title = (titSpan == null || titSpan == "") ? tabTit : document.getElementById(titSpan).outerHTML; var the_content = "<style media='print'>\n"; the_content += ".noPrin{\n"; the_content += "display:none;}\n"; the_content += "</style>\n"; the_content += "<link rel='stylesheet' rev='stylesheet' href='skin1/style/main.css' type='text/css' media='all' />\n"; the_content += "<object id=\"WebBrowser\" width=0 height=0 classid=\"CLSID:8856F961-340A-11D0-A96B-00C04FD705A2\"></object>\n"; the_content += "<script language='javascript' src='style/function.js'>"; the_content += "<script language='javascript'>"; the_content +="var HKEY_Root,HKEY_Path,HKEY_Key;" ; the_content +="HKEY_Root='HKEY_CURRENT_USER';"; the_content +="HKEY_Path='\\Software\\Microsoft\\Internet Explorer\\PageSetup\\';"; the_content +="var Wsh=new ActiveXObject('WScript.Shell');"; the_content +="HKEY_Key='header';"; the_content +="Wsh.RegWrite(HKEY_Root+HKEY_Path+HKEY_Key,'');"; the_content +="HKEY_Key='footer';"; the_content +="Wsh.RegWrite(HKEY_Root+HKEY_Path+HKEY_Key,'');"; the_content +="</script>"; the_content += "</sc"; the_content += "ript>\n"; the_content += "<center><b>"; the_content += table_title; the_content += "</b>"; the_content += document.all(the_table).outerHTML; the_content = the_content.replace(/ style=\"[^\"]*\"/g, ""); the_content = the_content.replace(/ onclick=\"[^\"]*\"/g, ""); the_content = the_content.replace(/ mode=\"(false|true)"/g, ""); the_content = the_content.replace(/ oBgc=\"[\w#\d]*\"/g, ""); the_content = the_content.replace(/ oFc=\"[\w#\d]*\"/g, ""); the_content = the_content.replace(/<span>(5|6)<\/span>/gi, ""); the_content = the_content.replace(/<DIV contentEditable=false>(.*)<\/DIV>/ig, "$1"); the_content = the_content.replace(/\*/g, " "); the_content += "\n<br><div class='noPrin'><input type='button' class='button2' value='页面设置' onclick=\"WebBrowser.ExecWB(8,1)\">"; the_content += "<input type='button' class='button2' value='打印预览' onclick=\"WebBrowser.ExecWB(7,1)\">"; the_content += "<input type='button' class='button2' value='直接打印' onclick=\"WebBrowser.ExecWB(6,6)\"></div>"; var newwin = window.open("about:blank", "_blank", ""); newwin.document.open(); newwin.document.write(the_content); newwin.document.getElementById(the_table).getElementsByTagName("tr")[0].style.display = "none"; var inps = newwin.document.getElementById(the_table).getElementsByTagName("INPUT"); var sels = newwin.document.getElementsByTagName("select"); var txts = newwin.document.getElementsByTagName("textarea"); var buts = newwin.document.getElementsByTagName("button"); for (i = inps.length - 1; i >= 0; i--) { inps[i].outerHTML = inps[i].value; } for (i = sels.length - 1; i >= 0; i--) { sels[i].outerHTML = sels[i].options[sels[i].selectedIndex].text; } for (i = txts.length - 1; i >= 0; i--) { txts[i].outerHTML = txts[i].value; } for (i = buts.length - 1; i >= 0; i--) { buts[i].style.display = "none"; } newwin.document.close(); newwin = null; } /**定义公用方法:简易报表生成*/ function expTab(the_table, tabTit, titSpan, mar) { if($(the_table).tagName.toLowerCase() == "table" && $(the_table).rows.length <= 1){ alert("当前页面没有可打印的数据!"); return false; } if(mar){ try{ var mars = mar.split("-"); PageSetup(mars[0],mars[1],mars[2],mars[3],mars[4],mars[5]); }catch(e){ } } var table_title = (titSpan == null || titSpan == "") ? tabTit : $(titSpan).innerText; var the_content = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"; the_content += "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"; the_content += "<head>\n"; the_content += "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=GBK\" />\n"; the_content += "<meta http-equiv=\"Content-Language\" content=\"GBK\" />\n"; the_content += "<%@include file=\"/common/head.ini\"%>\n"; //<link rel="stylesheet" href="http://10.71.19.19:82/zfstyle_v4/css/public.css" type="text/css" media="all" /> //<link rel="stylesheet" href="http://10.71.19.19:82/zfstyle_v4/css/module.css" type="text/css" media="all" /> //<link rel="stylesheet" href="http://10.71.19.19:82/zfstyle_v4/css/skin_blue.css" type="text/css" media="all" /> the_content += "<link rel=\"stylesheet\" href=\"/zfstyle_v4/css/public.css\" type=\"text/css\" media=\"all\" />\n"; the_content += "<link rel=\"stylesheet\" href=\"/zfstyle_v4/css/module.css\" type=\"text/css\" media=\"all\" />\n"; the_content += "<link rel=\"stylesheet\" href=\"/zfstyle_v4/css/skin_blue.css\" type=\"text/css\" media=\"all\" />\n"; the_content += "<style>@media print {.hideWhenPrint {display: none;}}</style>"; the_content += "<object id=\"WebBrowser\" width=0 height=0 classid=\"CLSID:8856F961-340A-11D0-A96B-00C04FD705A2\"></object>\n"; the_content += "</head>\n<body>\n"; the_content += "<div class=\"printview\">\n<h3>"; the_content += table_title; the_content += "</h3>\n"; the_content += $(the_table).outerHTML; the_content = the_content.replace(/( *)(style=\")(.*)(\")/gi, ""); the_content = the_content.replace(/(<td.*<input.*)(checkbox|text)(.*\/td>)/gi, ""); the_content = the_content.replace(/( *)(on)([dbl]*)(click=\")(.*)(\")/gi, ""); the_content = the_content.replace(/on[a-z]*=\w*\(\)/g, ""); the_content = the_content.replace(/on[a-z]*=\"\w*\(\'\w*\'\)\"/g, ""); //the_content = the_content.replace(/>\s*删\s*除\s*</g, ""); the_content = the_content.replace(/(<span)(.*)(<\/span>)/gi, ""); the_content += "\n<div class=\"hideWhenPrint\"><button onclick=\"WebBrowser.ExecWB(8,1)\">页面设置</button>"; the_content += "<button onclick=\"WebBrowser.ExecWB(7,1)\">打印预览</button>"; the_content += "<button onclick=\"WebBrowser.ExecWB(6,6)\">直接打印</button></div>\n"; the_content += "</body>\n</html>"; var newwin = window.open("about:blank", "_blank", ""); newwin.document.open(); newwin.document.write(the_content); newwin.document.close(); newwin = null; } /**定义公用方法:通过name属性改变复选框状态*/ function chgChkAll(obj,oName){ var boxes = document.getElementsByName(oName); for(var i = 0; i < boxes.length; i++){ boxes[i].checked = obj.checked; } } //qukong function chgChkNull(){ var boxes = document.getElementsByTagName("input"); for(var i = 0; i < boxes.length; i++){ if(boxes[i].type=="text"||boxes[i].type=="password"){ boxes[i].value=boxes[i].value.toString().replace(/^\s+|\s+$/g,""); } } } function printTable(){ /** var ht = window.frames["mainFrame"].document; var num = ht.getElementsByTagName("input"); alert(num.length); * */ } function cxxy(a,b,c,d){ $("kjName").value = a; showTopWin(b,c,d); //window.open(b,'',''); } function xdxy(){ var dm = $("dm").value; var dmxx = dm.split(","); if(window.dialogArguments.$("xyldxxb.yhm")){ window.dialogArguments.$("xyldxxb.yhm").value = dmxx[0]; } if(window.dialogArguments.$("xyldxxb.ldxm")){ window.dialogArguments.$("xyldxxb.ldxm").value = dmxx[1]; } if(window.dialogArguments.$("yhm")){ window.dialogArguments.$("yhm").value = dmxx[0]; window.dialogArguments.$("xm").value = dmxx[1]; } window.close(); } function xdxybm(){ var dm = $("dm").value; var dmxx = dm.split(","); if(window.dialogArguments.$("xyldxxb.fgbm") && window.dialogArguments.$("xyldxxb.fgbmmc")){ if (window.dialogArguments.$("xyldxxb.fgbm").value.length ==0) { window.dialogArguments.$("xyldxxb.fgbm").value = dmxx[0]; window.dialogArguments.$("xyldxxb.fgbmmc").value = dmxx[1]; } else { //alert(window.dialogArguments.$("fgbm")) var fgbm =window.dialogArguments.$("xyldxxb.fgbm").value.split(","); for (i = 0; i < fgbm.length; i++) { if (fgbm[i] ==dmxx[0] ) { alert("此学院已经存在!"); return false; } } window.dialogArguments.$("xyldxxb.fgbm").value =window.dialogArguments.$("xyldxxb.fgbm").value+','+ dmxx[0]; window.dialogArguments.$("xyldxxb.fgbmmc").value = window.dialogArguments.$("xyldxxb.fgbmmc").value+','+dmxx[1]; } } if(window.dialogArguments.$("fgbm")) { if (window.dialogArguments.$("fgbm").value.length ==0) { window.dialogArguments.$("fgbm").value = dmxx[0]; window.dialogArguments.$("fgbmmc").value = dmxx[1]; }else { //alert(window.dialogArguments.$("fgbm")) var fgbm =window.dialogArguments.$("fgbm").value.split(","); for (i = 0; i < fgbm.length; i++) { if (fgbm[i] ==dmxx[0] ) { alert("此学院已经存在!"); return false; } } window.dialogArguments.$("fgbm").value =window.dialogArguments.$("fgbm").value+','+ dmxx[0]; window.dialogArguments.$("fgbmmc").value = window.dialogArguments.$("fgbmmc").value+','+dmxx[1]; } } window.close(); } function rowonclick(objTr){ if(curr_row != null && curr_row.tagName.toLowerCase() == "tr"){ curr_row.style.backgroundColor="#FFFFFF"; } curr_row = objTr; curr_row.style.backgroundColor=obj_bgc; document.forms[0].dm.value=curr_row.id; } function clearValue(a){ var dmxx = a.split(","); for (i = 0; i < dmxx.length; i++) { $(dmxx[i]).value=""; } } function getChoose(obj,processid){ if (processid!=null) { refreshForm('cxczr.do?processid='+processid+'&chk='+obj.value); } else{ refreshForm('cxczr.do?chk='+obj.value); } } function cxzxr_change(obj,b,c,d){ var i = obj.selectedIndex; if(i=0){ return false; } else if(i<0){ return false; } else{ var txt = obj.options[obj.selectedIndex].value; refreshForm('cxczr.do?processid='+d+'&chk='+c+'&'+b+'='+txt); } } //判断是不是电话号码 //校验普通电话、传真号码:可以“+”开头,除数字外,可含有“-” function isTel(s) { if(s != null && s != "") { //var patrn=/^[+]{0,1}(\d){1,3}[ ]?([-]?(\d){1,12})+$/; var patrn=/^[+]{0,1}(\d){1,3}[ ]?([-]?((\d)|[ ]){1,12})+$/; if (!patrn.exec(s)) { alert("请输入正确的电话号码"); return false } else return true } } function isEmail(src) { isEmail1 = /^\w+([\.\-]\w+)*\@\w+([\.\-]\w+)*\.\w+$/; isEmail2 = /^.*@[^_]*$/; return (isEmail1.test(src) && isEmail2.test(src)); } //显示下拉列表框 function dispDdlList(data){ var objId =data[0]; if((data[1] == null && typeof data[1] == 'object')||(data[1] == "" && typeof data[1] == 'object')){ BatAjax.removeAllOptions(objId); return false; } if($(data[0]) && $(data[0]).tagName.toLowerCase() == "select"){ BatAjax.removeAllOptions(objId); BatAjax.addOptions(objId,data[1],data[2],data[3]); if($(data[0]).options[0].value=="null"){ $(data[0]).options[0].value = ""; } } if(data[4]){ if($(data[4])){ if($(data[4]).value){ var defaultVal = replaceChar($(data[4]).value," ",""); DWRUtil.setValue(objId,defaultVal); } } } if($("bdzdStr")) { var unShowbdzd = $("bdzdStr").value; var bdzdArray = unShowbdzd.split(","); var flag = false; for(i = 0;i < bdzdArray.length;i++) { if(bdzdArray[i] === objId) { flag=true; break; } } if(flag) { var text = $(objId).options[$(objId).selectedIndex].text; var value = $(objId).value; $(objId).options.length=1; $(objId).options[0] = new Option(text , value); } } try{ operationSeleced();//lost next }catch(e){} } //显示下拉列表框 function dispDdlList2(data){ var objId =data[0]; if((data[1] == null && typeof data[1] == 'object')||(data[1] == "" && typeof data[1] == 'object')){ BatAjax.removeAllOptions(objId); return false; } if($(data[0]) && $(data[0]).tagName.toLowerCase() == "select"){ //BatAjax.removeAllOptions(objId); BatAjax.addOptions(objId,data[1],data[2],data[3]); if($(data[0]).options[0].value=="null"){ $(data[0]).options[0].value = ""; } } if(data[4]){ if($(data[4])){ if($(data[4]).value){ var defaultVal = replaceChar($(data[4]).value," ",""); DWRUtil.setValue(objId,defaultVal); } } } if($("bdzdStr")) { var unShowbdzd = $("bdzdStr").value; var bdzdArray = unShowbdzd.split(","); var flag = false; for(i = 0;i < bdzdArray.length;i++) { if(bdzdArray[i] === objId) { flag=true; break; } } if(flag) { var text = $(objId).options[$(objId).selectedIndex].text; var value = $(objId).value; $(objId).options.length=1; $(objId).options[0] = new Option(text , value); } } try{ operationSeleced();//lost next }catch(e){} } //显示下拉列表框 function dispDdlListZdy(data){ var objId =data[0]; if((data[1] == null && typeof data[1] == 'object')||(data[1] == "" && typeof data[1] == 'object')){ BatAjax.removeAllOptions(objId); return false; } if($(data[0]) && $(data[0]).tagName.toLowerCase() == "select"){ BatAjax.removeAllOptions(objId); BatAjax.addOptions(objId,data[1],data[2],data[3]); if($(data[0]).options[0].value=="null"){ $(data[0]).options[0].value = ""; } } if(data[4]){ if($(data[4])){ if($(data[4]).value){ var defaultVal = replaceChar($(data[4]).value," ",""); DWRUtil.setValue(objId,defaultVal); } } } try{ operationSeleced();//lost next }catch(e){} } //通过数组来显示下拉列表 //此方法适用于取单个值的情况,不支持去两列数据的情况。data中包含下拉列表框的ID,满足所有条件的数组,显示数据的数组,默认值id function dispArrayList(data) { var objId = data[0]; var strArray = data[1]; var obj = data[2]; var ele = $(objId); ele.options.length=0; ele.options[0]=new Option("请选择","请选择"); for(i = 0;i < obj.length;i++) { for(j = 0;j < strArray.length;j++) { if(strArray[j] === obj[i]) { ele.options[ele.options.length] = new Option(obj[i] , obj[i]); } } } if(data[3]) { DWRUtil.setValue(objId,$(data[2]).value); } } function dispDdlBean(data) { var objId = data.dispControl; if ((data.datalist == null && typeof data.datalist == 'object') || (data.datalist == "" && typeof data.datalist == 'object')) { BatAjax.removeAllOptions(objId); return false; } if ($(objId) && $(objId).tagName.toLowerCase() == "select") { BatAjax.removeAllOptions(objId); BatAjax.addOptions(objId, data.datalist, data.valueLine,data.textLine); if ($(objId).options[0].value == "null") { $(objId).options[0].value = ""; } } if (data.initControl) { if ($(data.initControl)) { if ($(data.initControl).value) { DWRUtil.setValue(objId, $(data.initControl).value); } } }else if(data.initValue){ DWRUtil.setValue(objId, data.initValue); } } function dispDdlListTree(data){ var objId =data[0]; if((data[1] == null && typeof data[1] == 'object')||(data[1] == "" && typeof data[1] == 'object')){ BatAjax.removeAllOptions(objId); return false; } if($(data[0]) && $(data[0]).tagName.toLowerCase() == "select"){ BatAjax.removeAllOptions(objId); BatAjax.addOptions(objId,data[1],data[2],data[3]); if($(data[0]).options[0].value=="null"){ $(data[0]).options[0].value = ""; } } if(data[4]){ if($(data[4])){ if($(data[4]).value){ DWRUtil.setValue(objId,$(data[4]).value);}} } } function showDiv(d_html,w,h){ i = document.getElementsByTagName("select").length; for(j = 0;j<i;j++){ document.getElementsByTagName("select")[j].style.visibility = "hidden"; } var d_width = document.body.clientWidth; var d_height = document.body.clientHeight; var d_left = 0; var d_top = 0; var d_color = "#EEF4F9"; var d_width_top = w; var d_height_top = h; var d_left_top = (d_width - d_width_top)/2; var d_top_top = (d_height - d_height_top)/2-50; var d_color_top = "#EEF4F9"; dd_html = "<div oncontextmenu='return false' onselectstart='return false' style='filter:alpha(opacity=50);position:absolute;align:middle;text-align:center;padding-top:10px;border: 1px solid #5E88B8; width:"+d_width+"px; height:"+d_height+"px; top:"+d_top+"px; left:"+d_left+"px; background-color:"+d_color+"'>"; dd_html += "</div>"; dd_html += "<div style='position:absolute;align:middle;text-align:center;padding-top:10px;border: 1px solid #5E88B8; width:"+d_width_top+"px; height:"+d_height_top+"px; top:"+d_top_top+"px; left:"+d_left_top+"px; background-color:"+d_color_top+"'>"; dd_html += "<br>"; dd_html += d_html; dd_html += "<br>"; dd_html += "</div>"; tmpdiv.innerHTML=dd_html; } function closeAdd(){ i = document.getElementsByTagName("select").length; for(j = 0;j<i;j++){ document.getElementsByTagName("select")[j].style.visibility = ""; } dd_html=""; tmpdiv.innerHTML=dd_html; } /*function AJAX显示表格 *data 表格数据源 *objid 绑定的控件名称 *fun_list 功能数组*/ function dispTable(data,objid,fun_list,onclick,ondblclick){ if(data == null){ return false; } var optAdd = {}; optAdd.rowCreator = function(){ var tr = document.createElement("tr"); tr.style.cssText = "cursor:hand"; if(onclick){ tr.onclick = onclick; } if(ondblclick){ tr.ondblclick = ondblclick; } return tr; }; BatAjax.removeAllRows(objid); BatAjax.addRows(objid,data,fun_list,optAdd); BatAlert.closeTips(); } /**定义公用方法:检验身份证号码*/ function chkSfzh(obj){ var sfzh=obj.value; var OldID; if(sfzh.length == 15){ OldID = sfzh; return true; }else if(sfzh.length == 18){ OldID = sfzh.substring(0, 6) + sfzh.substring(8,sfzh.length-1); }else{ alert("请输入正确的身份证号码!"); return false; } var W = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1); var A = new Array("1", "0", "x", "9", "8", "7", "6", "5", "4", "3", "2"); var i, j, S; var NewID, ID, strNF; NewID = OldID.substring(0, 6) + "19" + OldID.substring(6,OldID.length); S = 0; for( i = 0; i <= 16; i++){ j = NewID.substring(i, i+1) * W[i]; S = S + j; } S = S % 11; if(sfzh != NewID + A[S]){ alert("请输入正确的身份证号码!"); return false; } return true; } /*功能描述:完成CHECKBOX全选和全消操作 * 参数1 事件源控件名称 * 参数2 操作源控件名称 * * */ function checkBox_select(control_event,control_oper,id){ if($(control_event)){ if($(control_oper)){ for(i=0;i<$(control_oper).getElementsByTagName("input").length;i++){ if($(control_oper).getElementsByTagName("input")[i].type == "checkbox" && $(control_oper).getElementsByTagName("input")[i].disabled==false){ $(control_oper).getElementsByTagName("input")[i].checked = $(control_event).checked; } } } } } /*功能描述:判断一个控件的值是否为空 * 参数1 事件源控件ID * 参数2 弹出语句 * * 参数3 是否选中控件 * */ function isObjNull(id,text,sel){ if($(id).value == ""){ if($("WebOffice")){ alert(text,false,function(){ if(parseInt(sel)==1){ try{ $(id).select(); $(id).focus(); }catch(e){} } }); return false; }else{ alert(text,false,function(){ if(parseInt(sel)==1){ try{ $(id).select(); $(id).focus(); }catch(e){} } }); return false; } } return true; } /*功能描述:是否为数字 * 参数1 事件源控件ID * 参数2 弹出语句 * * 参数3 是否选中控件 * */ function checkNaN(id,text,sel){ if(isNaN($(id).value)){ if($("WebOffice")){ alert(text,false,function(){ if(parseInt(sel)==1){ $(id).select(); $(id).focus(); } }); return false; }else{ alert(text,false,function(){ if(parseInt(sel)==1){ $(id).select(); $(id).focus(); } }); return false; } } return true; } function isObjCheck(id,text,sel){ for(i=0;i<document.getElementsByName(id).length;i++){ if(document.getElementsByName(id)[i].checked==true){ return true; } } alert(text,false,function(){ if(parseInt(sel)==1){ $(id).select(); $(id).focus(); } }); return false; } function isAllObjNull(str){ for(i=0;i<str.length;i++){ if(!isObjNull(str[i][0],str[i][1],str[i][2])) { break; } } if(i < str.length) return false; else if(i == str.length) return true; } function chkUsername(obj,text) { var reg1 = /^[0-9a-zA-Z]+$/g; var str = $(obj).value; var r1 = str.match(reg1); if(r1 == null){ alert(text,false,function(){ //$(obj).select(); //$(obj).focus(); }); return false; } else { return true; } } /*功能描述:判断一个控件的值是否合法 * 参数1 事件源控件ID * 参数2 控件内容格式* * * 参数3 是否选中控件 * */ function isRightObj(id,format,sel) { //alert($(id).value); //alert(format); if($(id).value=="") return true; if(format=="username"&&$(id).value != "") { var reg1 = /^[0-9a-zA-Z]+$/g; var str = $(id).value; var r1 = str.match(reg1); if(r1 == null){ alert("用户名只能由字母和数字组成,不得含有其他字符!",false,function(){ if(parseInt(sel)==1){ $(id).select(); $(id).focus(); } }); return false; } } else if(format=="tel"){ if(!isTel($(id))&&$(id).value != "") { alert("电话号码不符合要求!",false,function(){ if(parseInt(sel)==1){ $(id).select(); $(id).focus(); } }); return false; } } else if(format=="email"&&$(id).value!=""){ if(!isEmail($(id).value)) { alert("电子邮箱不符合要求!",false,function(){ if(parseInt(sel)==1){ $(id).select(); $(id).focus(); } }); return false; } } else if(format == "identity"&&$(id).value != "") { if(!chkSfzh($(id))) { alert("身份证号码不符合要求!",false,function(){ if(parseInt(sel)==1){ $(id).select(); $(id).focus(); } }); return false; } } /*else if(format == "name" &&$(id).value != "") { if(!chkName2($(id))) { alert("姓名不符合要求!",false,function(){ if(parseInt(sel)==1){ $(id).select(); $(id).focus(); } }); return false; } }*/ return true; } function isAllRightObj(str) { for(i=0;i<str.length;i++){ if(!isRightObj(str[i][0],str[i][1],str[i][2])) { break; } } if(i < str.length) return false; if(i == str.length) return true; } /*功能描述:判断一个控件的值是否超出范围 * 参数1 事件源控件ID * 参数2 控件的最小长度* * * 参数3 控件的最大长度* * * * 参数4 控件名称* * * * 参数5 是否选中控件 * */ function isLength(id,minl,maxl,text,sel) { if($(id).value == "") return false; else if($(id).value != "") { if($(id).value.length >parseInt(maxl)){ //alert("1"); alert( text+"太长,请重新输入!",false,function(){ if(parseInt(sel) == 1) { $(id).select(); $(id).focus(); } }); return false; } if($(id).value.length < parseInt(minl)){ //alert("2"); alert(text+"太短,请重新输入!",false,function(){ if(parseInt(sel) == 1) { $(id).select(); $(id).focus(); } }); return false; } return true; } } function isAlllenRight(str) { for(i = 0;i < str.length;i++) { if(!isLength(str[i][0],str[i][1],str[i][2],str[i][3],str[i][4])) { break; } } if(i < str.length) return false; else if(i == str.length) return true; } //打开组织结构代码表 function openTree(mxdxid,mode,valcont,listcont,selectPNum){ //showTopWin("search_person_tree.do?mxdxid="+mxdxid+"&mode="+mode+"&valcont="+valcont+"&listcont="+listcont+"&id="+$(valcont).value+"&name="+$(listcont).value,600,600); //window.open("search_person_tree.do?mxdxid="+mxdxid+"&modi="+mode+"&valcont="+valcont+"&listcont="+listcont,600,600); //showTopWin("searchperson.do?mxdxid="+mxdxid+"&mode="+mode+"&valcont="+valcont+"&listcont="+listcont+"&id="+$(valcont).value+"&name="+$(listcont).value,620,640,"Y"); //alert(encodeURIComponent($(listcont).value)) var name =$(listcont).value; // encodeURIComponent($(listcont).value.Trim()) //if(name.indexOf("_")<0){ // name = name.replaceAll('%','___'); // } showTopWin("allPersonTree.action?mxdxid="+mxdxid+"&mode="+mode+"&valcont="+valcont+"&listcont="+listcont+"&id="+$(valcont).value+"&name="+name+"&selectPNum="+selectPNum,620,580,"Y"); } function openTreeOfDepname(mxdxid,mode,valcont,listcont,selectPNum,depname){ //showTopWin("search_person_tree.do?mxdxid="+mxdxid+"&mode="+mode+"&valcont="+valcont+"&listcont="+listcont+"&id="+$(valcont).value+"&name="+$(listcont).value,600,600); //window.open("search_person_tree.do?mxdxid="+mxdxid+"&modi="+mode+"&valcont="+valcont+"&listcont="+listcont,600,600); //showTopWin("searchperson.do?mxdxid="+mxdxid+"&mode="+mode+"&valcont="+valcont+"&listcont="+listcont+"&id="+$(valcont).value+"&name="+$(listcont).value,620,640,"Y"); //alert(encodeURIComponent($(listcont).value)) var name =$(listcont).value; // encodeURIComponent($(listcont).value.Trim()) //if(name.indexOf("_")<0){ // name = name.replaceAll('%','___'); // } showTopWin("allPersonTree.action?depname="+depname+"&mxdxid="+mxdxid+"&mode="+mode+"&valcont="+valcont+"&listcont="+listcont+"&id="+$(valcont).value+"&name="+name+"&selectPNum="+selectPNum,620,580,"Y"); } function openTreebyone(mxdxid,mode,valcont,listcont){ //showTopWin("search_person_tree.do?mxdxid="+mxdxid+"&mode="+mode+"&valcont="+valcont+"&listcont="+listcont,600,600); //window.open("search_person_tree.do?mxdxid="+mxdxid+"&modi="+mode+"&valcont="+valcont+"&listcont="+listcont,600,600); showTopWin("searchperson.do?mxdxid="+mxdxid+"&mode="+mode+"&valcont="+valcont+"&listcont="+listcont+"&id="+$(valcont).value+"&name="+$(listcont).value,620,640,"Y"); } function openCxzxr(mxdxid,valcont,listcont){ showTopWin("cxczr.do?mxdxid="+mxdxid+"&valcont="+valcont+"&listcont="+listcont,580,510); /*if(mxdxid=="") { openTree(mxdxid,"2",valcont,listcont); } else { showTopWin("chooseFlowPerson.action?mxdxid="+mxdxid+"&valcont="+valcont+"&listcont="+listcont,550,450); }*/ } //选择下拉列表框 function selectDdl(idV,id){ if($(idV) && $(idV).value != "" && $(idV).value != null){ for(var i = 0;i < $(id).options.length; i++){ if($(id).options[i].value == $(idV).value){ $(id).options[i].selected = true; return true; } } } } function sleectRadio(idV,id){ if($(idV) && $(idV).value != "" && $(idV).value != null){ for(i=0;i<document.getElementsByName(id).length;i++){ document.getElementsByName(id)[i].checked=false; if(document.getElementsByName(id)[i].value==$(idV).value){ document.getElementsByName(id)[i].checked=true; } } } } function openpdf(sUrl,jc){ if (jc==""){ return false; } document.forms[0].action = sUrl; document.forms[0].target = "_blank"; document.forms[0].submit(); document.forms[0].target = "_self"; } function checkMobile(){ var sMobile = document.mobileform.mobile.value if(!(/^1[3|5][0-9]\d{4,8}$/.test(sMobile))){ alert("不是完整的11位手机号或者正确的手机号前七位"); document.mobileform.mobile.focus(); return false; } window.open('', 'mobilewindow', 'height=197,width=350,status=yes,toolbar=no,menubar=no,location=no') } function resetHeight(obj,height1){ if( $(obj)){ var height=document.documentElement.offsetHeight-height1; $(obj).style.cssText="overflow-y:auto;height:"+height; } } function resetHeightDM(obj,height1){ if( $(obj)){ var height=document.documentElement.offsetHeight-height1; $(obj).style.cssText+=";height:"+height; } } function getKeyVal(keyVal){ return function(array) {return eval(keyVal);}; } function getHiddenKayVal(keyVal,hiddenKey){ return function(array) { var span= document.createElement("span"); span.innerHTML=eval(keyVal); var hiddenid = document.createElement("input"); hiddenid.type = "hidden"; hiddenid.value =eval(hiddenKey); span.appendChild(hiddenid); return span;}; } function getChkboxKeyVal(checkKeyVal) { return function(array) { var span=document.createElement("span"); var chk = document.createElement("input"); chk.type = "checkbox"; chk.value = eval(checkKeyVal); span.appendChild(chk); return span;} } function dblClick(){//如果要特别指定双击事件 在页面从写次函数 if($("edit")){ $("edit").onclick; } } function dispTableList(data){ if(data[1].length == 0 && typeof data[1] == "object"){ curr_row=null; BatAlert.closeTips(); BatAjax.removeAllRows(data[0]); var tr=document.createElement("tr"); var td=document.createElement("td"); td.colSpan=data[2].length; td.align="center"; td.innerText="暂无数据!"; tr.appendChild(td); $(data[0]).appendChild(tr); return false; } if($("num")){ if(data[3]){ $("num").innerText = data[3].maxRecord; }else{ $("num").innerText = data[1].length; } } var array =data[1]; var arr_hidden=new Array(); if(data[4]){ arr_hidden=data[4]; } //var mailList=dispTableGetList(array,data[2],arr_hidden); OLD var mailList=dispTableGetList(array,data[2],arr_hidden,new Array()); //new add 'new Array()' if(data[5]){ mailList[mailList.length]=dispTableTaxis(array,data[5]); } var optAdd = {}; optAdd.rowCreator = function(){ var tr = document.createElement("tr"); tr.onclick = function(){ rowOnClick(this); }; if($("edit")){ tr.ondblclick = $("edit").onclick; } else if($("exa_capability")) { tr.ondblclick = $("exa_capability").onclick; } else { } return tr; }; BatAjax.removeAllRows(data[0]); curr_row=null; BatAjax.addRows(data[0],array,mailList,optAdd); BatAlert.closeTips(); if(data[3]){ initPage(data[3]); } } function resetHeightPages(obj,height1,height2){ if(height1=="") height1=98; if(height2=="") height2=32; var pagesize=10; if($(obj)){ var height=document.documentElement.offsetHeight-height1; $(obj).style.cssText="vertical-align:top;overflow-y:auto;height:"+height; pagesize=height/height2; pagesize=Math.floor(pagesize); if($("pagesize")){ $("pagesize").value=pagesize; } } } //对象,是否多选,列数,行数 function emptyTableBean(objs,ischkField,rowsize,pagessize){ var pagesize = pagessize; if(true){//如果结果集为空 if ($("RsCount")) { $("RsCount").innerText="0"; } curr_row=null; BatAlert.closeTips(); BatAjax.removeAllRows(objs); for(i = 0;i < pagesize;i++) { var tr=document.createElement("tr"); var length = 0; if(ischkField){ length = rowsize+1; }else{ length = rowsize; } for(j = 0;j < length;j++) { var td=document.createElement("td"); td.align="center"; if(ischkField && j==0){ td.innerHTML="<input type=\"checkbox\" id=\"tempCheck\" disabled=\"true\"/>"; } else { td.innerHTML="&nbsp;&nbsp;"; } tr.appendChild(td); if($("add")){ //tr.ondblclick = $("add").onclick; } } $(objs).appendChild(tr); } return false; } } function singleclick(){}//单击 function dispTableBean(data){ if(data.datalist != null && data.datalist.length > 0) { initPage(data.pages); } else { $("maxrecord").innerText="0"; } if ($("RsCount")&& data.pages) { $("RsCount").innerText = data.pages.maxRecord; } var pagesize = data.pages.pageSize; if((data.datalist == null || data.datalist.length == 0) && typeof data.datalist == "object"){//如果结果集为空 if ($("RsCount")) { $("RsCount").innerText="0"; } curr_row=null; BatAlert.closeTips(); BatAjax.removeAllRows(data.dispControl); for(i = 0;i < pagesize;i++) { var tr=document.createElement("tr"); var length = 0; if(data.chkField){ length = data.showTxt.length+1; }else{ length = data.showTxt.length; } for(j = 0;j < length;j++) { var td=document.createElement("td"); td.align="center"; if(data.chkField && j==0){ td.innerHTML="<input type=\"checkbox\" id=\"tempCheck\" disabled=\"true\"/>"; } else { td.innerHTML="&nbsp;&nbsp;"; } tr.appendChild(td); if($("add")){ //tr.ondblclick = $("add").onclick; } } $(data.dispControl).appendChild(tr); } return false; } if($("num")){ if(data.pages){ $("num").innerText =data.pages.maxRecord; }else{ $("num").innerText = data.datalist.length; } } var array =data.datalist; var arr_hidden=data.hiddentxt; var mailList=new Array(); if(data.chkField){ mailList[mailList.length]= eval("getChkKayVal()"); } mailList=dispTableGetList(array,data.showTxt,arr_hidden,mailList); if(data.taxis.taxisField!=""){ mailList[mailList.length]=dispTableTaxis(array,data.taxis); } var optAdd = {}; optAdd.rowCreator = function(){ var tr = document.createElement("tr"); tr.onclick = function(){ rowOnClick(this); if($("rowclick")) { $("rowclick").value="yes"; } singleclick();//Page maybe change single click,event,rewrite this function if($("editSection")) { $("editSection").value="yes"; } }; if(data.ondblclick!=""){ tr.ondblclick =function (){ eval(data.ondblclick); } } else if($("edit") && !$("editLxjd") && !$("editLxtj")){ tr.ondblclick = $("edit").onclick; } return tr; }; BatAjax.removeAllRows(data.dispControl); curr_row=null; if(data.showHtml.length==0){//没有HTML列 默认 BatAjax.addRows(data.dispControl,array,mailList,optAdd); } else { //增加参数 显示的列,全部列,是否有多选框 var newalllist=new Array(); for(f=0;f<data.hiddentxt.length;f++) { newalllist[newalllist.length]=data.hiddentxt[f]; } for(f=0;f<data.showTxt.length;f++) { newalllist[newalllist.length]=data.showTxt[f]; } BatAjax.addRowsHtml(data.dispControl,array,mailList,optAdd,data.showHtml,newalllist); } var offset = pagesize - data.datalist.length; if(offset > 0) { for(i = 0;i < offset;i++) { var tr=document.createElement("tr"); var length = 0; if(data.chkField){ length = data.showTxt.length + 1; }else{ length = data.showTxt.length; } for(j = 0;j < length;j++) { var td=document.createElement("td"); td.align="center"; if(data.chkField && j==0){ td.innerHTML="<input type=\"checkbox\" id=\"tempCheck\" disabled=\"true\"/>"; } else { td.innerHTML="&nbsp;&nbsp;"; } tr.appendChild(td); if($("add")){ //tr.ondblclick = $("add").onclick; } } $(data.dispControl).appendChild(tr); } } BatAlert.closeTips(); if(data.pages){ initPage(data.pages); } if($("hzyobjValue")) { dispCheck($("hzyobjValue").value); } if($("setCheckStr")) { setDefaultCheck(); } } function dispTableBeanTwo(data){ if(data.datalist != null && data.datalist.length > 0) { initPage(data.pages); } if ($("RsCount")&& data.pages) { $("RsCount").innerText = data.pages.maxRecord; } var pagesize = data.pages.pageSize; if((data.datalist == null || data.datalist.length == 0) && typeof data.datalist == "object"){//如果结果集为空 if ($("RsCount")) { $("RsCount").innerText="0"; } curr_row=null; BatAlert.closeTips(); BatAjax.removeAllRows(data.dispControl); for(i = 0;i < pagesize;i++) { var tr=document.createElement("tr"); var length = 0; if(data.chkField){ length = data.showTxt.length+1; }else{ length = data.showTxt.length; } for(j = 0;j < length;j++) { var td=document.createElement("td"); td.align="center"; if(data.chkField && j==0){ td.innerHTML="<input type=\"checkbox\" id=\"tempCheck\" disabled=\"true\"/>"; } else { td.innerHTML="&nbsp;&nbsp;"; } tr.appendChild(td); if($("add")){ //tr.ondblclick = $("add").onclick; } } $(data.dispControl).appendChild(tr); } return false; } if($("num")){ if(data.pages){ $("num").innerText =data.pages.maxRecord; }else{ $("num").innerText = data.datalist.length; } } var array =data.datalist; var arr_hidden=data.hiddentxt; var mailList=new Array(); if(data.chkField){ mailList[mailList.length]= eval("getChkKayVal()"); } mailList=dispTableGetList(array,data.showTxt,arr_hidden,mailList); if(data.taxis.taxisField!=""){ mailList[mailList.length]=dispTableTaxis(array,data.taxis); } var optAdd = {}; optAdd.rowCreator = function(){ var tr = document.createElement("tr"); tr.onclick = function(){ rowOnClick(this); if($("rowclick")) { $("rowclick").value="yes"; } singleclick();//Page maybe change single click,event,rewrite this function if($("editSection")) { $("editSection").value="yes"; } }; if(data.ondblclick!=""){ tr.ondblclick =function (){ eval(data.ondblclick); } } else if($("edit") && !$("editLxjd") && !$("editLxtj")){ tr.ondblclick = $("edit").onclick; } return tr; }; BatAjax.removeAllRows(data.dispControl); curr_row=null; if(data.showHtml.length==0){//没有HTML列 默认 BatAjax.addRowsTwo(data.dispControl,array,mailList,optAdd); } else { //增加参数 显示的列,全部列,是否有多选框 var newalllist=new Array(); for(f=0;f<data.hiddentxt.length;f++) { newalllist[newalllist.length]=data.hiddentxt[f]; } for(f=0;f<data.showTxt.length;f++) { newalllist[newalllist.length]=data.showTxt[f]; } BatAjax.addRowsHtml(data.dispControl,array,mailList,optAdd,data.showHtml,newalllist); } var offset = pagesize - data.datalist.length; if(offset > 0) { for(i = 0;i < offset;i++) { var tr=document.createElement("tr"); var length = 0; if(data.chkField){ length = data.showTxt.length + 1; }else{ length = data.showTxt.length; } for(j = 0;j < length;j++) { var td=document.createElement("td"); td.align="center"; if(data.chkField && j==0){ td.innerHTML="<input type=\"checkbox\" id=\"tempCheck\" disabled=\"true\"/>"; } else { td.innerHTML="&nbsp;&nbsp;"; } tr.appendChild(td); if($("add")){ //tr.ondblclick = $("add").onclick; } } $(data.dispControl).appendChild(tr); } } BatAlert.closeTips(); if(data.pages){ initPage(data.pages); } if($("hzyobjValue")) { dispCheck($("hzyobjValue").value); } if($("setCheckStr")) { setDefaultCheck(); } } function singleclick2(event){}//单击 function dispTableBean2(data){ if ($("RsCount")&& data.pages) { $("RsCount").innerText = data.pages.maxRecord; } if(data.datalist.length == 0 && typeof data.datalist == "object"){//如果结果集为空 if ($("RsCount")) { $("RsCount").innerText="0"; } curr_row=null; BatAlert.closeTips(); BatAjax.removeAllRows(data.dispControl); var tr=document.createElement("tr"); var td=document.createElement("td"); if(data.chkField){ td.colSpan=data.showTxt.length+1; }else{ td.colSpan=data.showTxt.length; } td.align="center"; td.innerText="暂无数据!"; tr.appendChild(td); $(data.dispControl).appendChild(tr); return false; } if($("num")){ if(data.pages){ $("num").innerText =data.pages.maxRecord; }else{ $("num").innerText = data.datalist.length; } } var array =data.datalist; var arr_hidden=data.hiddentxt; var mailList=new Array(); if(data.chkField){ mailList[mailList.length]= eval("getChkKayVal()"); } mailList=dispTableGetList(array,data.showTxt,arr_hidden,mailList); if(data.taxis.taxisField!=""){ mailList[mailList.length]=dispTableTaxis(array,data.taxis); } var optAdd = {}; optAdd.rowCreator = function(){ var tr = document.createElement("tr"); tr.onclick = function(){ rowOnClick(this,event); singleclick2(event);//Page maybe change single click,event,rewrite this function }; if(data.ondblclick!=""){ tr.ondblclick =function (){ eval(data.ondblclick); } }else if($("edit")){ tr.ondblclick = $("edit").onclick; } return tr; }; BatAjax.removeAllRows(data.dispControl); curr_row=null; BatAjax.addRows(data.dispControl,array,mailList,optAdd); BatAlert.closeTips(); if(data.pages){ initPage(data.pages); } } function dispTableBeanCheckBox(data){ var pagesize = data.pages.pageSize; if(data.datalist.length == 0 && typeof data.datalist == "object"){ curr_row=null; BatAlert.closeTips(); BatAjax.removeAllRows(data.dispControl); for(i = 0;i < pagesize;i++) { var tr=document.createElement("tr"); var length = 0; if(data.chkField){ length = data.showTxt.length+2; }else{ length = data.showTxt.length+1; } for(j = 0;j < length;j++) { var td=document.createElement("td"); td.align="center"; td.innerText=" "; tr.appendChild(td); if($("add")){ //tr.ondblclick = $("add").onclick; } } $(data.dispControl).appendChild(tr); } return false; } if($("num")){ if(data.pages){ $("num").innerText =data.pages.maxRecord; }else{ $("num").innerText = data.datalist.length; } } var array =data.datalist; var txt_check=data.checktxt; var mailList=new Array(); mailList=dispTableGetListChk(array,data.showTxt,txt_check,mailList); if(data.taxis.taxisField!=""){ mailList[mailList.length]=dispTableTaxis(array,data.taxis); } var optAdd = {}; optAdd.rowCreator = function(){ var tr = document.createElement("tr"); tr.onclick = function(){ rowOnClick(this); }; if(data.ondblclick!=""){ tr.ondblclick =function (){ eval(data.ondblclick); } } else if($("edit")){ tr.ondblclick = $("edit").onclick; } return tr; }; BatAjax.removeAllRows(data.dispControl); curr_row=null; BatAjax.addRows(data.dispControl,array,mailList,optAdd); var offset = pagesize - data.datalist.length; if(offset > 0) { for(i = 0;i < offset;i++) { var tr=document.createElement("tr"); var length = 0; if(data.chkField){ length = data.showTxt.length+2; }else{ length = data.showTxt.length+1; } for(j = 0;j < length;j++) { var td=document.createElement("td"); td.align="center"; td.innerText=" "; tr.appendChild(td); if($("add")){ //tr.ondblclick = $("add").onclick; } } $(data.dispControl).appendChild(tr); } } BatAlert.closeTips(); if(data.pages){ initPage(data.pages); } } /********按住shift键多选***********/ var isShift=false; var checkIndex=0; var previousIndex=null; window.document.onkeydown=function(){ if(event.keyCode==16) isShift=true; } window.document.onkeyup=function(){ isShift=false; } function selectMore(nowsIndex) { if(!isShift) return; if(previousIndex==null) return; var startindex=0; var endindex=0; if(nowsIndex==previousIndex) return; if(nowsIndex>previousIndex) { endindex=nowsIndex; startindex=previousIndex; } if(nowsIndex<previousIndex) { endindex=previousIndex; startindex=nowsIndex; } for(findex=startindex;findex<endindex;findex++) { $("ID"+findex).checked=true; } previousIndex=null; } /* * *多选 */ function getChkKayVal(){ return function(array) { var span=document.createElement("span"); var hiddenid = document.createElement("input"); hiddenid.type = "checkbox"; hiddenid.name = "checkname"; hiddenid.value = array.ID; if($("checkBoxStatus")) { if($("checkBoxStatus").value=="no") { hiddenid.disabled="true"; } } //////////////////////////////////////设置顺序-shift hiddenid.sIndex=checkIndex; hiddenid.id="ID"+checkIndex; checkIndex++; ////////////////////////////////////// hiddenid.onclick=function(){ if(hiddenid.checked==true) { hiddenid.checked=false; }else { hiddenid.checked=true; } //////////////////////////////////////设置顺序-shift selectMore(hiddenid.sIndex);//判断是 previousIndex=hiddenid.sIndex;//保存当前点击的 ////////////////////////////////////// } span.appendChild(hiddenid); return span;}; } function dispTableGetList(array,txt,arr_hidden,mailList){ var i=0; for(j=0; j<txt.length; j++){ if(arr_hidden.length>i&&arr_hidden[i]!=""){ mailList[mailList.length]= eval("getHiddenKayVal('array." + txt[j] + "','array." + arr_hidden[i] + "')"); i++; }else{ mailList[mailList.length] = eval("getKeyVal('array." + txt[j] + "')"); } } return mailList; } function dispTableGetListChk(array,txt,txt_check,mailList) { var i=0; for(j=0; j<txt.length; j++){ if(txt_check.length>i&&txt_check[i]!=""){ mailList[mailList.length]= eval("getChkboxKeyVal('array." + txt_check[i] + "')"); i++; } mailList[mailList.length] = eval("getKeyVal('array." + txt[j] + "')"); } return mailList; } function dispTableTaxis(array,taxis){ return function(array) { var currentNumber=eval("array."+taxis.taxisField); var span=document.createElement("span"); span.style.cssText = "cursor:hand"; if(1==parseInt(currentNumber)){ span.innerHTML="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; var img=document.createElement("A"); img.href="#"; img.innerHTML="<img src='style/base/down.gif' border='0' align=absmiddle />"; img.onclick=function(){ down(this.parentNode.parentNode.parentNode); }; span.appendChild(img); }else if(taxis.totalNumber==parseInt(currentNumber)){ span.innerHTML="&nbsp;"; var img=document.createElement("A"); img.href="#"; img.innerHTML="<img src='style/base/up.gif' border='0' align=absmiddle />"; img.onclick=function(){ up(this.parentNode.parentNode.parentNode); }; span.appendChild(img); }else{ span.innerHTML="&nbsp;"; var img=document.createElement("A"); img.href="#"; img.innerHTML="<img src='style/base/up.gif' border='0' align=absmiddle />"; img.onclick=function(){ up(this.parentNode.parentNode.parentNode); }; span.appendChild(img); var img=document.createElement("A"); img.innerHTML="&nbsp;&nbsp;"; span.appendChild(img); img=document.createElement("A"); img.href="#"; img.innerHTML="<img src='style/base/down.gif' border='0' align=absmiddle />"; img.onclick=function(){ down(this.parentNode.parentNode.parentNode); }; span.appendChild(img); } return span; }; } function initPage(page){ if($("pagediv")&&page.maxPage>1){ $("pagesize").innerText=page.pageSize; $("currentpage").innerText=page.currentPage; $("maxpage").innerText=page.maxPage; $("maxrecord").innerText=page.maxRecord; $("pagelist").innerHTML=""; for (var I in page.pagelist) { var A=document.createElement("A"); A.innerText=page.pagelist[I]; A.href="javascript:submitPage('"+page.pagelist[I]+"')" if(page.pagelist[I]==page.currentPage){ A.className="current"; } $("pagelist").appendChild(A); } } else { $("pagesize").innerText=page.pageSize; $("currentpage").innerText=page.currentPage; $("maxpage").innerText=page.maxPage; $("maxrecord").innerText=page.maxRecord; $("pagelist").innerHTML=""; } } function dispTableListWithoutdb(data){ if(data[1] == null && typeof data[1] == 'object'){ BatAjax.removeAllOptions(data[0]); return false; } if($("num")){ $("num").innerText = data[1].length; } var optAdd = {}; var array = new Array(); array = data[1]; txt=data[2]; var mailList = new Array(); for(j=0; j<txt.length; j++){ mailList[j] = eval("getKeyVal('array." + txt[j] + "')"); } optAdd.rowCreator = function(){ var tr = document.createElement("tr"); tr.onclick = function(){ rowOnClick(this); }; return tr; }; BatAjax.removeAllRows(data[0]); curr_row=null; BatAjax.addRows(data[0],array,mailList,optAdd); BatAlert.closeTips(); } var temptimebyautclose=null;; function doClose(time){ $("close").innerText=time; if(time!=0){ temptimebyautclose=window.setTimeout("doClose("+(time-1)+")", 1000); }else{ temptimebyautclose=null; if($("preAction") && $("preAction").value!=null &&$("preAction").value!=""){ document.forms[0].action=$("preAction").value; document.forms[0].submit(); } Close(); } } function doreturn(time,newhref){ $("close").innerText=time; if(time!=0){ window.setTimeout("doreturn("+(time-1)+",'"+newhref+"')", 1000); }else{ window.location.href=newhref; } } //close windows function doreturnbyclose(time,newhref){ $("close").innerText=time; if(time!=0){ window.setTimeout("doreturnbyclose("+(time-1)+",'"+newhref+"')", 1000); }else{ window.close(); // window.location.href=newhref; } } function doreturnnourl(time) { $("close").innerText=time; if(time!=0){ window.setTimeout("doreturnnourl("+(time-1)+")",1000); } else { autoback(); } } function dispDelInfoComman(str) { if(str === "true") { } else if(str === "false") { alert("删除失败!"); } refurbish(); } /**定义公用类(方法):强制改变窗口*/ function ForceWindow(sTarget) { if (sTarget == null) { sTarget = "mainFrame"; } this.r = document.documentElement; this.f = document.createElement("FORM"); this.f.target = sTarget; this.f.method = "post"; this.r.insertBefore(this.f, this.r.childNodes[0]); } function inArray(str, array) {// for (tmp = 0; tmp <array.length; tmp++) { if (str == array[tmp]) { return true; } } return false; } function setCookie(name, value) { var today = new Date() var expires = new Date() expires.setTime(today.getTime() + 1000*60*60*24*365) document.cookie = name + "=" + escape(value) + "; expires=" + expires.toGMTString() } function getCookie(Name) { var search = Name + "=" if(document.cookie.length > 0) { offset = document.cookie.indexOf(search) if(offset != -1) { offset += search.length end = document.cookie.indexOf(";", offset) if(end == -1) end = document.cookie.length return unescape(document.cookie.substring(offset, end)) } else return "" } } function checkNumber(value) { //var str = ["0","1","2","3","4","5","6","7","8","9","0"]; var str="0123456789"; for(i=0;i < value.length;i++) { if(str.indexOf(value.substring(i,i+1)) == "-1") break; } if(i < value.length) return false; else return true; } function correctPNG() { for(var i=0; i<document.images.length; i++) { var img = document.images[i] var imgName = img.src.toUpperCase() if (imgName.substring(imgName.length-3, imgName.length) == "PNG") { var imgID = (img.id) ? "id='" + img.id + "' " : "" var imgClass = (img.className) ? "class='" + img.className + "' " : "" var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' " var imgStyle = "display:inline-block;" + img.style.cssText if (img.align == "left") imgStyle = "float:left;" + imgStyle if (img.align == "right") imgStyle = "float:right;" + imgStyle if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle var strNewHTML = "<span " + imgID + imgClass + imgTitle + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";" + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader" + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" img.outerHTML = strNewHTML i = i-1 } } } //get selected checkbok value,return string like 12123,45487,12142 function getCheckValue(){ var str=""; for(i =0;i < document.getElementsByTagName("input").length;i++){ if(document.getElementsByTagName("input")[i].type == "checkbox"){ if(document.getElementsByTagName("input")[i].checked==true&&document.getElementsByTagName("input")[i].name=='checkname'){ if(str==""){ str=document.getElementsByTagName("input")[i].value; }else{ str=str+","+document.getElementsByTagName("input")[i].value; } } } } return str; } function getCheckValueStr(){ var str=""; for(i =0;i < document.getElementsByTagName("input").length;i++){ if(document.getElementsByTagName("input")[i].type == "checkbox"){ if(document.getElementsByTagName("input")[i].checked==true&&document.getElementsByTagName("input")[i].name=='checkname'){ if(str==""){ str="'"+ document.getElementsByTagName("input")[i].value+"'"; }else{ str=str+",'"+document.getElementsByTagName("input")[i].value+"'"; } } } } return str; } //选中全部 或取消全部 function selectAllOrCancel(thiss){ if(thiss.checked)//如果选中 { for(i =0;i < document.getElementsByTagName("input").length;i++){ if(document.getElementsByTagName("input")[i].type == "checkbox"){ if(document.getElementsByTagName("input")[i].name=='checkname') { document.getElementsByTagName("input")[i].checked=true; } } } }else { for(i =0;i < document.getElementsByTagName("input").length;i++){ if(document.getElementsByTagName("input")[i].type == "checkbox"){ if(document.getElementsByTagName("input")[i].name=='checkname') { document.getElementsByTagName("input")[i].checked=false; } } } } } function Alert(msg,tit){ if(tit==""||tit==null){ tit="提示"; } parent.Ext.MessageBox.alert(tit,msg); } function showDiv(event,id) { if($(id).getAttribute("left")!=null&$(id).getAttribute("top")!=null) { $(id).style.top=(event.y-parseInt($(id).clientHeight)); $(id).style.left=(event.x-parseInt($(id).clientWidth)); return; } else if($(id).getAttribute("top")!=null) { $(id).style.top=(event.y-parseInt($(id).clientHeight)); $(id).style.left=event.x; return; } else if($(id).getAttribute("left")!=null) { $(id).style.top=event.y; $(id).style.left=(event.x-parseInt($(id).clientWidth)); return; } else { $(id).style.top=event.y; $(id).style.left=event.x; return; } } function rightMClick(event,id) { if(event.button=='2') { $(id).style.top=event.y; $(id).style.left=event.x; $(id).style.display=""; } } function setValue(objId,value) { if($(objId)) { $(objId).value = value; } } function setObjShowOrHidden(objId,way) { if($(objId)) { $(objId).style.display = way; } } String.prototype.contains = function(str){ return this.indexOf(str) > -1; } String.prototype.replaceAll=function(oldChar, newChar){ var str = this; while(str.indexOf(oldChar) != -1){ str = str.replace(oldChar, newChar); } return str; } function setNullData(pagesize,listsize,length,objId) { var offset = pagesize - listsize; if(offset > 0) { for(i = 0;i < offset;i++) { var tr=document.createElement("tr"); for(j = 0;j < length;j++) { var td=document.createElement("td"); td.align="center"; td.innerHTML="&nbsp;&nbsp;"; tr.appendChild(td); if($("add")){ tr.ondblclick = $("add").onclick; } } $(objId).appendChild(tr); } } } function setNullData2(pagesize,listsize,length,objId) { var offset = pagesize - listsize; if(offset > 0) { for(i = 0;i < offset;i++) { var tr=document.createElement("tr"); for(j = 0;j < length;j++) { var td=document.createElement("td"); td.align="center"; td.innerHTML="&nbsp;&nbsp;"; tr.appendChild(td); } $(objId).appendChild(tr); } } } function setNullDataCheckBox(pagesize,listsize,length,objId) { var offset = pagesize - listsize; if(offset > 0) { for(i = 0;i < offset;i++) { var tr=document.createElement("tr"); for(j = 0;j < length;j++) { var td=document.createElement("td"); if(j == 0) { td.align="center"; td.innerHTML="<input type=\"checkbox\" disabled=\"true\"/>"; } else { td.align="center"; td.innerHTML="&nbsp;&nbsp;"; } tr.appendChild(td); } $(objId).appendChild(tr); } } } function checkLength(objId,maxLength) { if($(objId).value=="") { return false; } else { var mc = $(objId).value; if(mc.length > maxLength) { return false; } } } function openSelectJcsj(sslx,kjid,kjmcid) { var url="jcsjdyzb.do?theAction=chooseSelectJcsj&kjid="+kjid+"&kjmcid="+kjmcid+"&sslx="+sslx; var height="300"; var scrolling="no"; tipsWindown("业务对象","id:text","620","300","true","","true","id",url,height,scrolling); //showTopWin("jcsjdyzb.do?theAction=chooseSelectJcsj&kjid="+kjid+"&kjmcid="+kjmcid+"&sslx="+sslx,400,600,"Y"); } String.prototype.Trim = function() { var m = this.match(/^\s*(\S+(\s+\S+)*)\s*$/); return (m == null) ? "" : m[1]; } /** * 检测手机号码 * @return */ String.prototype.isMobile = function() { return (/^(?:13\d|15[89])-?\d{5}(\d{3}|\*{3})$/.test(this.Trim())); } /* * 检测电话号码 */ String.prototype.isTel = function() { //"兼容格式: 国家代码(2到3位)-区号(2到3位)-电话号码(7到8位)-分机号(3位)" return (/^(([0\+]\d{2,3}-)?(0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/.test(this.Trim())); } function checkTel(obj){ var s_reg = "[^ ]"; if($(obj).value.match(s_reg)==null){ alert("提醒:请输入正确的手机号码或电话号码\n\n例如:13916752109或023-86526333"); $(obj).focus(); return false; } if ($(obj).value.isMobile()||$(obj).value.isTel()) { $(obj).value = $(obj).value.Trim(); return true; } else { alert("提醒:请输入正确的手机号码或电话号码\n\n例如:13916752109或023-86526333"); $(obj).focus(); return false; } } function checkMobile(obj) { var s_reg = "[^ ]"; if($(obj).value.match(s_reg)==null){ alert("提醒:请输入正确的手机号码\n\n例如:13916752109"); $(obj).focus(); return false; } if ($(obj).value.isMobile()) { $(obj).value = $(obj).value.Trim(); return true; } else { alert("提醒:请输入正确的手机号码\n\n例如:13916752109"); $(obj).focus(); return false; } } //判断输入密码的类型 function CharMode(iN){ if (iN>=48 && iN <=57) //数字 return 1; if (iN>=65 && iN <=90) //大写 return 2; if (iN>=97 && iN <=122) //小写 return 4; else return 8; } //bitTotal函数 //计算密码模式 function bitTotal(num){ modes=0; for (i=0;i<4;i++){ if (num & 1) modes++; num>>>=1; } return modes; } //返回强度级别 function checkStrong(sPW){ if (sPW.length<=4) return 0; //密码太短 Modes=0; for (i=0;i<sPW.length;i++){ //密码模式 Modes|=CharMode(sPW.charCodeAt(i)); } return bitTotal(Modes); } /** * 自动匹配下拉选择框 参数一 value对应控件id name对应的空间id 默认显示的提示信息 * ConferenceAjax.getPersonList("conference.registerid","conference.registername","请选择...",displayCombo); */ function setSearchKeyParam(split){ var str = document.getElementById("searchKey").value; if(split == null){ split = "-"; } if(str == ""){ return ""; } var strArr = str.split(split); var res = ""; for(var i=0;i<strArr.length;i++){ res += "&"+strArr[i]+"="+document.getElementById(strArr[i]).value; } res += "&searchKey="+document.getElementById("searchKey").value ; if(document.getElementById("currentpage") && document.getElementById("currentpage").tagName.toLowerCase() == 'span'){ res += "&currentpage="+document.getElementById("currentpage").innerHTML; }else if(document.getElementById("currentpage") && document.getElementById("currentpage").tagName.toLowerCase() == 'input'){ res += "&currentpage="+document.getElementById("currentpage").value; } return res; } //window.attachEvent("onload", correctPNG); //firefox and ie //zhoujiawei function dispTableBeanFI(data){ //window.alert("a1"); if(data.datalist != null && data.datalist.length > 0) { initPageFI(data.pages); } else { //$("maxrecord").innerText="0"; document.getElementById("maxrecord").innerHTML="0"; document.getElementById("maxpage").innerHTML="1"; } //window.alert("a2"); if (document.getElementById("RsCount")&& data.pages) { document.getElementById("RsCount").innerHTML = data.pages.maxRecord; } //window.alert("a3"); var pagesize = data.pages.pageSize; if((data.datalist == null || data.datalist.length == 0) && typeof data.datalist != "object"){//如果结果集为空 if (document.getElementById("RsCount")) { document.getElementById("RsCount").innerHTML="0"; } curr_row=null; BatAlert.closeTips(); BatAjax.removeAllRowsFI(data.dispControl); for(i = 0;i < pagesize;i++) { var tr=document.createElement("tr"); var length = 0; if(data.chkField){ length = data.showTxt.length+1; }else{ length = data.showTxt.length; } for(j = 0;j < length;j++) { var td=document.createElement("td"); td.align="center"; if(data.chkField && j==0){ td.innerHTML="<input type=\"checkbox\" id=\"tempCheck\" disabled=\"true\"/>"; } else { td.innerHTML="&nbsp;&nbsp;"; } tr.appendChild(td); if($("add")){ //tr.ondblclick = $("add").onclick; } } document.getElementById(data.dispControl).appendChild(tr); } return false; } //window.alert("a5"); if(document.getElementById("num")){ if(data.pages){ document.getElementById("num").innerHTML =data.pages.maxRecord; }else{ document.getElementById("num").innerHTML = data.datalist.length; } } var array =data.datalist; var arr_hidden=data.hiddentxt; var mailList=new Array(); if(data.chkField){ mailList[mailList.length]= eval("getChkKayVal()"); } //window.alert("a6"); mailList=dispTableGetList(array,data.showTxt,arr_hidden,mailList); if(data.taxis.taxisField!=""){ mailList[mailList.length]=dispTableTaxis(array,data.taxis); } var optAdd = {}; optAdd.rowCreator = function(){ var tr = document.createElement("tr"); tr.onclick = function(){ rowOnClick(this); if(document.getElementById("rowclick")) { document.getElementById("rowclick").value="yes"; } singleclick();//Page maybe change single click,event,rewrite this function if(document.getElementById("editSection")) { document.getElementById("editSection").value="yes"; } }; if(data.ondblclick!=""){ tr.ondblclick =function (){ eval(data.ondblclick); } } else if($("edit") && !$("editLxjd") && !$("editLxtj")){ tr.ondblclick = $("edit").onclick; } return tr; }; BatAjax.removeAllRowsFI(data.dispControl); curr_row=null; if(data.showHtml.length==0){//没有HTML列 默认 BatAjax.addRowsFI(data.dispControl,array,mailList,optAdd); } else { //增加参数 显示的列,全部列,是否有多选框 var newalllist=new Array(); for(f=0;f<data.hiddentxt.length;f++) { newalllist[newalllist.length]=data.hiddentxt[f]; } for(f=0;f<data.showTxt.length;f++) { newalllist[newalllist.length]=data.showTxt[f]; } BatAjax.addRowsHtmlFI(data.dispControl,array,mailList,optAdd,data.showHtml,newalllist); } var offset = pagesize - data.datalist.length; //window.alert("a7"); if(offset > 0) { for(i = 0;i < offset;i++) { var tr=document.createElement("tr"); var length = 0; if(data.chkField){ length = data.showTxt.length + 1; }else{ length = data.showTxt.length; } for(j = 0;j < length;j++) { var td=document.createElement("td"); td.align="center"; if(data.chkField && j==0){ td.innerHTML="<input type=\"checkbox\" id=\"tempCheck\" disabled=\"true\"/>"; } else { td.innerHTML="&nbsp;&nbsp;"; } tr.appendChild(td); if($("add")){ //tr.ondblclick = $("add").onclick; } } document.getElementById(data.dispControl).appendChild(tr); } } BatAlert.closeTips(); if(data.pages){ initPageFI(data.pages); } if(document.getElementById("hzyobjValue")) { dispCheck(document.getElementById("hzyobjValue").value); } if(document.getElementById("setCheckStr")) { setDefaultCheck(); } } function initPageFI(page){ if(document.getElementById("pagediv")&&page.maxPage>1){ document.getElementById("pagesize").innerHTML=page.pageSize; document.getElementById("currentpage").innerHTML=page.currentPage; document.getElementById("maxpage").innerHTML=page.maxPage; document.getElementById("maxrecord").innerHTML=page.maxRecord; document.getElementById("pagelist").innerHTML=""; for (var I in page.pagelist) { var A=document.createElement("A"); A.innerText=page.pagelist[I]; A.href="javascript:submitPage('"+page.pagelist[I]+"')" if(page.pagelist[I]==page.currentPage){ A.className="current"; } document.getElementById("pagelist").appendChild(A); } } else { document.getElementById("pagesize").innerHTML=page.pageSize; document.getElementById("currentpage").innerHTML=page.currentPage; document.getElementById("maxpage").innerHTML=page.maxPage; document.getElementById("maxrecord").innerHTML=page.maxRecord; document.getElementById("pagelist").innerHTML=""; } } function setValueFI(objId,value) { if(document.getElementById(objId)) { document.getElementById(objId).value = value; } }
JavaScript
jQuery.noConflict(); jQuery.ajaxSetup({cache:false})//设置全局都不用缓存 //初始加载页面时 jQuery(document).ready(function(){ //为获取单个值的按钮注册鼠标单击事件 jQuery("#getMessage").click(function(){ jQuery.ajaxSettings.async = false; //(同步执行) jQuery.getJSON("jsontest!returnMessage.action",function(data){ //通过.操作符可以从data.message中获得Action中message的值 jQuery("#message").html("<font color='red'>"+data.message+"</font>"); }); jQuery.ajaxSettings.async = true; //(异步执行) }); //为获取UserInfo对象按钮添加鼠标单击事件 jQuery("#getUserInfo").click(function(){ jQuery.getJSON("jsontest!returnUserInfo.action",function(data){ //清空显示层中的数据 jQuery("#message").html(""); //为显示层添加获取到的数据 //获取对象的数据用data.userInfo.属性 jQuery("#message").append("<div><font color='red'>用户ID:"+data.userInfo.userId+"</font></div>") .append("<div><font color='red'>用户名:"+data.userInfo.userName+"</font></div>") .append("<div><font color='red'>密码:"+data.userInfo.password+"</font></div>") }); }); //为获取List对象按钮添加鼠标单击事件 jQuery("#getList").click(function(){ jQuery.getJSON("jsontest!returnList.action",function(data){ //清空显示层中的数据 jQuery("#message").html(""); //使用jQuery中的each(data,function(){});函数 //从data.userInfosList获取UserInfo对象放入value之中 jQuery.each(data.userInfosList,function(i,value){ jQuery("#message").append("<div>第"+(i+1)+"个用户:</div>") .append("<div><font color='red'>用户ID:"+value.userId+"</font></div>") .append("<div><font color='red'>用户名:"+value.userName+"</font></div>") .append("<div><font color='red'>密码:"+value.password+"</font></div>"); }); }); }); //为获取Map对象按钮添加鼠标单击事件 jQuery("#getMap").click(function(){ jQuery.getJSON("jsontest!returnMap.action",function(data){ //清空显示层中的数据 jQuery("#message").html(""); //使用jQuery中的each(data,function(){});函数 //从data.userInfosList获取UserInfo对象放入value之中 //key值为Map的键值 jQuery.each(data.userInfosMap,function(key,value){ jQuery("#message").append("<div><font color='red'>用户ID:"+value.userId+"</font></div>") .append("<div><font color='red'>用户名:"+value.userName+"</font></div>") .append("<div><font color='red'>密码:"+value.password+"</font></div>"); }); }); }); //向服务器发送表达数据 jQuery("#regRe").click(function(){ //把表单的数据进行序列化 var params = jQuery("form").serialize(); //使用jQuery中的$.ajax({});Ajax方法 jQuery.ajax({ url:"jsontest!gainUserInfo.action", type:"POST", data:params, dataType:"json", success:function(data){ //清空显示层中的数据 jQuery("#message").html(""); //为显示层添加获取到的数据 //获取对象的数据用data.userInfo.属性 jQuery("#message").append("<div><font color='red'>用户ID:"+data.userInfo.userId+"</font></div>") .append("<div><font color='red'>用户名:"+data.userInfo.userName+"</font></div>") .append("<div><font color='red'>密码:"+data.userInfo.password+"</font></div>") } }); }); });
JavaScript
;(function ($) { /* * jqGrid 3.8.2 - jQuery Grid * Copyright (c) 2008, Tony Tomov, tony@trirand.com * Dual licensed under the MIT and GPL licenses * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl-2.0.html * Date: 2010-12-14 */ $.jgrid = $.jgrid || {}; $.extend($.jgrid,{ htmlDecode : function(value){ if(value=='&nbsp;' || value=='&#160;' || (value.length==1 && value.charCodeAt(0)==160)) { return "";} return !value ? value : String(value).replace(/&amp;/g, "&").replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&quot;/g, '"'); }, htmlEncode : function (value){ return !value ? value : String(value).replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/\"/g, "&quot;"); }, format : function(format){ //jqgformat var args = $.makeArray(arguments).slice(1); if(format===undefined) { format = ""; } return format.replace(/\{(\d+)\}/g, function(m, i){ return args[i]; }); }, getCellIndex : function (cell) { var c = $(cell); if (c.is('tr')) { return -1; } c = (!c.is('td') && !c.is('th') ? c.closest("td,th") : c)[0]; if ($.browser.msie) { return $.inArray(c, c.parentNode.cells); } return c.cellIndex; }, stripHtml : function(v) { v = v+""; var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi; if (v) { v = v.replace(regexp,""); return (v && v !== '&nbsp;' && v !== '&#160;') ? v.replace(/\"/g,"'") : ""; } else { return v; } }, stringToDoc : function (xmlString) { var xmlDoc; if(typeof xmlString !== 'string') { return xmlString; } try { var parser = new DOMParser(); xmlDoc = parser.parseFromString(xmlString,"text/xml"); } catch(e) { xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async=false; xmlDoc.loadXML(xmlString); } return (xmlDoc && xmlDoc.documentElement && xmlDoc.documentElement.tagName != 'parsererror') ? xmlDoc : null; }, parse : function(jsonString) { var js = jsonString; if (js.substr(0,9) == "while(1);") { js = js.substr(9); } if (js.substr(0,2) == "/*") { js = js.substr(2,js.length-4); } if(!js) { js = "{}"; } return ($.jgrid.useJSON===true && typeof (JSON) === 'object' && typeof (JSON.parse) === 'function') ? JSON.parse(js) : eval('(' + js + ')'); }, parseDate : function(format, date) { var tsp = {m : 1, d : 1, y : 1970, h : 0, i : 0, s : 0},k,hl,dM; if(date && date !== null && date !== undefined){ date = $.trim(date); date = date.split(/[\\\/:_;.\t\T\s-]/); format = format.split(/[\\\/:_;.\t\T\s-]/); var dfmt = $.jgrid.formatter.date.monthNames; var afmt = $.jgrid.formatter.date.AmPm; var h12to24 = function(ampm, h){ if (ampm === 0){ if (h == 12) { h = 0;} } else { if (h != 12) { h += 12; } } return h; }; for(k=0,hl=format.length;k<hl;k++){ if(format[k] == 'M') { dM = $.inArray(date[k],dfmt); if(dM !== -1 && dM < 12){date[k] = dM+1;} } if(format[k] == 'F') { dM = $.inArray(date[k],dfmt); if(dM !== -1 && dM > 11){date[k] = dM+1-12;} } if(format[k] == 'a') { dM = $.inArray(date[k],afmt); if(dM !== -1 && dM < 2 && date[k] == afmt[dM]){ date[k] = dM; tsp.h = h12to24(date[k], tsp.h); } } if(format[k] == 'A') { dM = $.inArray(date[k],afmt); if(dM !== -1 && dM > 1 && date[k] == afmt[dM]){ date[k] = dM-2; tsp.h = h12to24(date[k], tsp.h); } } if(date[k] !== undefined) { tsp[format[k].toLowerCase()] = parseInt(date[k],10); } } tsp.m = parseInt(tsp.m,10)-1; var ty = tsp.y; if (ty >= 70 && ty <= 99) {tsp.y = 1900+tsp.y;} else if (ty >=0 && ty <=69) {tsp.y= 2000+tsp.y;} } return new Date(tsp.y, tsp.m, tsp.d, tsp.h, tsp.i, tsp.s,0); }, jqID : function(sid){ sid = sid + ""; return sid.replace(/([\.\:\[\]])/g,"\\$1"); }, getAccessor : function(obj, expr) { var ret,p,prm, i; if( typeof expr === 'function') { return expr(obj); } ret = obj[expr]; if(ret===undefined) { try { if ( typeof expr === 'string' ) { prm = expr.split('.'); } i = prm.length; if( i ) { ret = obj; while (ret && i--) { p = prm.shift(); ret = ret[p]; } } } catch (e) {} } return ret; }, ajaxOptions: {}, from : function(source,initalQuery){ // Original Author Hugo Bonacci // License MIT http://jlinq.codeplex.com/license var queryObject=function(d,q){ if(typeof(d)=="string"){ d=$.data(d); } var self=this, _data=d, _usecase=true, _trim=false, _query=q, _stripNum = /[\$,%]/g, _lastCommand=null, _lastField=null, _negate=false, _queuedOperator="", _sorting=[], _useProperties=true; if(typeof(d)=="object"&&d.push) { if(d.length>0){ if(typeof(d[0])!="object"){ _useProperties=false; }else{ _useProperties=true; } } }else{ throw "data provides is not an array"; } this._hasData=function(){ return _data===null?false:_data.length===0?false:true; }; this._getStr=function(s){ var phrase=[]; if(_trim){ phrase.push("jQuery.trim("); } phrase.push("String("+s+")"); if(_trim){ phrase.push(")"); } if(!_usecase){ phrase.push(".toLowerCase()"); } return phrase.join(""); }; this._strComp=function(val){ if(typeof(val)=="string"){ return".toString()"; }else{ return""; } }; this._group=function(f,u){ return({field:f.toString(),unique:u,items:[]}); }; this._toStr=function(phrase){ if(_trim){ phrase=$.trim(phrase); } if(!_usecase){ phrase=phrase.toLowerCase(); } phrase=phrase.toString().replace(new RegExp('\\"',"g"),'\\"'); return phrase; }; this._funcLoop=function(func){ var results=[]; $.each(_data,function(i,v){ results.push(func(v)); }); return results; }; this._append=function(s){ if(_query===null){ _query=""; } else { _query+=_queuedOperator === "" ? " && " :_queuedOperator; } if(_negate){ _query+="!"; } _query+="("+s+")"; _negate=false; _queuedOperator=""; }; this._setCommand=function(f,c){ _lastCommand=f; _lastField=c; }; this._resetNegate=function(){ _negate=false; }; this._repeatCommand=function(f,v){ if(_lastCommand===null){ return self; } if(f!=null&&v!=null){ return _lastCommand(f,v); } if(_lastField===null){ return _lastCommand(f); } if(!_useProperties){ return _lastCommand(f); } return _lastCommand(_lastField,f); }; this._equals=function(a,b){ return(self._compare(a,b,1)===0); }; this._compare=function(a,b,d){ if( d === undefined) { d = 1; } if(a===undefined) { a = null; } if(b===undefined) { b = null; } if(a===null && b===null){ return 0; } if(a===null&&b!==null){ return 1; } if(a!==null&&b===null){ return -1; } if(!_usecase && typeof(a) !== "number" && typeof(b) !== "number" ) { a=String(a).toLowerCase(); b=String(b).toLowerCase(); } if(a<b){return -d;} if(a>b){return d;} return 0; }; this._performSort=function(){ if(_sorting.length===0){return;} _data=self._doSort(_data,0); }; this._doSort=function(d,q){ var by=_sorting[q].by, dir=_sorting[q].dir, type = _sorting[q].type, dfmt = _sorting[q].datefmt; if(q==_sorting.length-1){ return self._getOrder(d, by, dir, type, dfmt); } q++; var values=self._getGroup(d,by,dir,type,dfmt); var results=[]; for(var i=0;i<values.length;i++){ var sorted=self._doSort(values[i].items,q); for(var j=0;j<sorted.length;j++){ results.push(sorted[j]); } } return results; }; this._getOrder=function(data,by,dir,type, dfmt){ var sortData=[],_sortData=[], newDir = dir=="a" ? 1 : -1, i,ab,j, findSortKey; if(type === undefined ) { type = "text"; } if (type == 'float' || type== 'number' || type== 'currency' || type== 'numeric') { findSortKey = function($cell, a) { var key = parseFloat( String($cell).replace(_stripNum, '')); return isNaN(key) ? 0.00 : key; }; } else if (type=='int' || type=='integer') { findSortKey = function($cell, a) { return $cell ? parseFloat(String($cell).replace(_stripNum, '')) : 0; }; } else if(type == 'date' || type == 'datetime') { findSortKey = function($cell, a) { return $.jgrid.parseDate(dfmt,$cell).getTime(); }; } else if($.isFunction(type)) { findSortKey = type; } else { findSortKey = function($cell, a) { if(!$cell) {$cell ="";} return $.trim(String($cell).toUpperCase()); }; } $.each(data,function(i,v){ ab = by!=="" ? $.jgrid.getAccessor(v,by) : v; if(ab === undefined) { ab = ""; } ab = findSortKey(ab, v); _sortData.push({ 'vSort': ab,'index':i}); }); _sortData.sort(function(a,b){ a = a.vSort; b = b.vSort; return self._compare(a,b,newDir); }); j=0; var nrec= data.length; // overhead, but we do not change the original data. while(j<nrec) { i = _sortData[j].index; sortData.push(data[i]); j++; } return sortData; }; this._getGroup=function(data,by,dir,type, dfmt){ var results=[], group=null, last=null, val; $.each(self._getOrder(data,by,dir,type, dfmt),function(i,v){ val = $.jgrid.getAccessor(v, by); if(val === undefined) { val = ""; } if(!self._equals(last,val)){ last=val; if(group!=null){ results.push(group); } group=self._group(by,val); } group.items.push(v); }); if(group!=null){ results.push(group); } return results; }; this.ignoreCase=function(){ _usecase=false; return self; }; this.useCase=function(){ _usecase=true; return self; }; this.trim=function(){ _trim=true; return self; }; this.noTrim=function(){ _trim=false; return self; }; this.combine=function(f){ var q=$.from(_data); if(!_usecase){ q.ignoreCase(); } if(_trim){ q.trim(); } var result=f(q).showQuery(); self._append(result); return self; }; this.execute=function(){ var match=_query, results=[]; if(match === null){ return self; } $.each(_data,function(){ if(eval(match)){results.push(this);} }); _data=results; return self; }; this.data=function(){ return _data; }; this.select=function(f){ self._performSort(); if(!self._hasData()){ return[]; } self.execute(); if($.isFunction(f)){ var results=[]; $.each(_data,function(i,v){ results.push(f(v)); }); return results; } return _data; }; this.hasMatch=function(f){ if(!self._hasData()) { return false; } self.execute(); return _data.length>0; }; this.showQuery=function(cmd){ var queryString=_query; if(queryString === null) { queryString="no query found"; } if($.isFunction(cmd)){ cmd(queryString);return self; } return queryString; }; this.andNot=function(f,v,x){ _negate=!_negate; return self.and(f,v,x); }; this.orNot=function(f,v,x){ _negate=!_negate; return self.or(f,v,x); }; this.not=function(f,v,x){ return self.andNot(f,v,x); }; this.and=function(f,v,x){ _queuedOperator=" && "; if(f===undefined){ return self; } return self._repeatCommand(f,v,x); }; this.or=function(f,v,x){ _queuedOperator=" || "; if(f===undefined) { return self; } return self._repeatCommand(f,v,x); }; this.isNot=function(f){ _negate=!_negate; return self.is(f); }; this.is=function(f){ self._append('this.'+f); self._resetNegate(); return self; }; this._compareValues=function(func,f,v,how,t){ var fld; if(_useProperties){ fld='this.'+f; }else{ fld='this'; } if(v===undefined) { v = null; } var val=v===null?f:v, swst = t.stype === undefined ? "text" : t.stype; switch(swst) { case 'int': case 'integer': val = isNaN(Number(val)) ? '0' : val; // To be fixed with more inteligent code fld = 'parseInt('+fld+',10)'; val = 'parseInt('+val+',10)'; break; case 'float': case 'number': case 'numeric': val = String(val).replace(_stripNum, ''); val = isNaN(Number(val)) ? '0' : val; // To be fixed with more inteligent code fld = 'parseFloat('+fld+')'; val = 'parseFloat('+val+')'; break; case 'date': case 'datetime': val = String($.jgrid.parseDate(t.newfmt || 'Y-m-d',val).getTime()); fld = 'jQuery.jgrid.parseDate("'+t.srcfmt+'",'+fld+').getTime()'; break; default : fld=self._getStr(fld); val=self._getStr('"'+self._toStr(val)+'"'); } self._append(fld+' '+how+' '+val); self._setCommand(func,f); self._resetNegate(); return self; }; this.equals=function(f,v,t){ return self._compareValues(self.equals,f,v,"==",t); }; this.greater=function(f,v,t){ return self._compareValues(self.greater,f,v,">",t); }; this.less=function(f,v,t){ return self._compareValues(self.less,f,v,"<",t); }; this.greaterOrEquals=function(f,v,t){ return self._compareValues(self.greaterOrEquals,f,v,">=",t); }; this.lessOrEquals=function(f,v,t){ return self._compareValues(self.lessOrEquals,f,v,"<=",t); }; this.startsWith=function(f,v){ var val = (v===undefined || v===null) ? f: v, length=_trim ? $.trim(val.toString()).length : val.toString().length; if(_useProperties){ self._append(self._getStr('this.'+f)+'.substr(0,'+length+') == '+self._getStr('"'+self._toStr(v)+'"')); }else{ length=_trim?$.trim(v.toString()).length:v.toString().length; self._append(self._getStr('this')+'.substr(0,'+length+') == '+self._getStr('"'+self._toStr(f)+'"')); } self._setCommand(self.startsWith,f); self._resetNegate(); return self; }; this.endsWith=function(f,v){ var val = (v===undefined || v===null) ? f: v, length=_trim ? $.trim(val.toString()).length:val.toString().length; if(_useProperties){ self._append(self._getStr('this.'+f)+'.substr('+self._getStr('this.'+f)+'.length-'+length+','+length+') == "'+self._toStr(v)+'"'); } else { self._append(self._getStr('this')+'.substr('+self._getStr('this')+'.length-"'+self._toStr(f)+'".length,"'+self._toStr(f)+'".length) == "'+self._toStr(f)+'"'); } self._setCommand(self.endsWith,f);self._resetNegate(); return self; }; this.contains=function(f,v){ if(_useProperties){ self._append(self._getStr('this.'+f)+'.indexOf("'+self._toStr(v)+'",0) > -1'); }else{ self._append(self._getStr('this')+'.indexOf("'+self._toStr(f)+'",0) > -1'); } self._setCommand(self.contains,f); self._resetNegate(); return self; }; this.groupBy=function(by,dir,type, datefmt){ if(!self._hasData()){ return null; } return self._getGroup(_data,by,dir,type, datefmt); }; this.orderBy=function(by,dir,stype, dfmt){ dir = dir === undefined || dir === null ? "a" :$.trim(dir.toString().toLowerCase()); if(stype === null || stype === undefined) { stype = "text"; } if(dfmt === null || dfmt === undefined) { dfmt = "Y-m-d"; } if(dir=="desc"||dir=="descending"){dir="d";} if(dir=="asc"||dir=="ascending"){dir="a";} _sorting.push({by:by,dir:dir,type:stype, datefmt: dfmt}); return self; }; return self; }; return new queryObject(source,null); }, extend : function(methods) { $.extend($.fn.jqGrid,methods); if (!this.no_legacy_api) { $.fn.extend(methods); } } }); $.fn.jqGrid = function( pin ) { if (typeof pin == 'string') { //var fn = $.fn.jqGrid[pin]; var fn = $.jgrid.getAccessor($.fn.jqGrid,pin); if (!fn) { throw ("jqGrid - No such method: " + pin); } var args = $.makeArray(arguments).slice(1); return fn.apply(this,args); } return this.each( function() { if(this.grid) {return;} var p = $.extend(true,{ url: "", height: 150, page: 1, rowNum: 20, rowTotal : null, records: 0, pager: "", pgbuttons: true, pginput: true, colModel: [], rowList: [], colNames: [], sortorder: "asc", sortname: "", datatype: "xml", mtype: "GET", altRows: false, selarrrow: [], savedRow: [], shrinkToFit: true, xmlReader: {}, jsonReader: {}, subGrid: false, subGridModel :[], reccount: 0, lastpage: 0, lastsort: 0, selrow: null, beforeSelectRow: null, onSelectRow: null, onSortCol: null, ondblClickRow: null, onRightClickRow: null, onPaging: null, onSelectAll: null, loadComplete: null, gridComplete: null, loadError: null, loadBeforeSend: null, afterInsertRow: null, beforeRequest: null, onHeaderClick: null, viewrecords: false, loadonce: false, multiselect: false, multikey: false, editurl: null, search: false, caption: "", hidegrid: true, hiddengrid: false, postData: {}, userData: {}, treeGrid : false, treeGridModel : 'nested', treeReader : {}, treeANode : -1, ExpandColumn: null, tree_root_level : 0, prmNames: {page:"page",rows:"rows", sort: "sidx",order: "sord", search:"_search", nd:"nd", id:"id",oper:"oper",editoper:"edit",addoper:"add",deloper:"del", subgridid:"id", npage: null, totalrows:"totalrows"}, forceFit : false, gridstate : "visible", cellEdit: false, cellsubmit: "remote", nv:0, loadui: "enable", toolbar: [false,""], scroll: false, multiboxonly : false, deselectAfterSort : true, scrollrows : false, autowidth: false, scrollOffset :18, cellLayout: 5, subGridWidth: 20, multiselectWidth: 20, gridview: false, rownumWidth: 25, rownumbers : false, pagerpos: 'center', recordpos: 'right', footerrow : false, userDataOnFooter : false, hoverrows : true, altclass : 'ui-priority-secondary', viewsortcols : [false,'vertical',true], resizeclass : '', autoencode : false, remapColumns : [], ajaxGridOptions :{}, direction : "ltr", toppager: false, headertitles: false, scrollTimeout: 40, data : [], _index : {}, grouping : false, groupingView : {groupField:[],groupOrder:[], groupText:[],groupColumnShow:[],groupSummary:[], showSummaryOnHide: false, sortitems:[], sortnames:[], groupDataSorted : false, summary:[],summaryval:[], plusicon: 'ui-icon-circlesmall-plus', minusicon: 'ui-icon-circlesmall-minus'}, ignoreCase : false, cmTemplate : {} }, $.jgrid.defaults, pin || {}); var grid={ headers:[], cols:[], footers: [], dragStart: function(i,x,y) { this.resizing = { idx: i, startX: x.clientX, sOL : y[0]}; this.hDiv.style.cursor = "col-resize"; this.curGbox = $("#rs_m"+p.id,"#gbox_"+p.id); this.curGbox.css({display:"block",left:y[0],top:y[1],height:y[2]}); if($.isFunction(p.resizeStart)) { p.resizeStart.call(this,x,i); } document.onselectstart=function(){return false;}; }, dragMove: function(x) { if(this.resizing) { var diff = x.clientX-this.resizing.startX, h = this.headers[this.resizing.idx], newWidth = p.direction === "ltr" ? h.width + diff : h.width - diff, hn, nWn; if(newWidth > 33) { this.curGbox.css({left:this.resizing.sOL+diff}); if(p.forceFit===true ){ hn = this.headers[this.resizing.idx+p.nv]; nWn = p.direction === "ltr" ? hn.width - diff : hn.width + diff; if(nWn >33) { h.newWidth = newWidth; hn.newWidth = nWn; } } else { this.newWidth = p.direction === "ltr" ? p.tblwidth+diff : p.tblwidth-diff; h.newWidth = newWidth; } } } }, dragEnd: function() { this.hDiv.style.cursor = "default"; if(this.resizing) { var idx = this.resizing.idx, nw = this.headers[idx].newWidth || this.headers[idx].width; nw = parseInt(nw,10); this.resizing = false; $("#rs_m"+p.id).css("display","none"); p.colModel[idx].width = nw; this.headers[idx].width = nw; this.headers[idx].el.style.width = nw + "px"; this.cols[idx].style.width = nw+"px"; if(this.footers.length>0) {this.footers[idx].style.width = nw+"px";} if(p.forceFit===true){ nw = this.headers[idx+p.nv].newWidth || this.headers[idx+p.nv].width; this.headers[idx+p.nv].width = nw; this.headers[idx+p.nv].el.style.width = nw + "px"; this.cols[idx+p.nv].style.width = nw+"px"; if(this.footers.length>0) {this.footers[idx+p.nv].style.width = nw+"px";} p.colModel[idx+p.nv].width = nw; } else { p.tblwidth = this.newWidth || p.tblwidth; $('table:first',this.bDiv).css("width",p.tblwidth+"px"); $('table:first',this.hDiv).css("width",p.tblwidth+"px"); this.hDiv.scrollLeft = this.bDiv.scrollLeft; if(p.footerrow) { $('table:first',this.sDiv).css("width",p.tblwidth+"px"); this.sDiv.scrollLeft = this.bDiv.scrollLeft; } } if($.isFunction(p.resizeStop)) { p.resizeStop.call(this,nw,idx); } } this.curGbox = null; document.onselectstart=function(){return true;}; }, populateVisible: function() { if (grid.timer) { clearTimeout(grid.timer); } grid.timer = null; var dh = $(grid.bDiv).height(); if (!dh) { return; } var table = $("table:first", grid.bDiv); var rows = $("> tbody > tr:gt(0):visible:first", table); var rh = rows.outerHeight() || grid.prevRowHeight; if (!rh) { return; } grid.prevRowHeight = rh; var rn = p.rowNum; var scrollTop = grid.scrollTop = grid.bDiv.scrollTop; var ttop = Math.round(table.position().top) - scrollTop; var tbot = ttop + table.height(); var div = rh * rn; var page, npage, empty; if ( tbot < dh && ttop <= 0 && (p.lastpage===undefined||parseInt((tbot + scrollTop + div - 1) / div,10) <= p.lastpage)) { npage = parseInt((dh - tbot + div - 1) / div,10); if (tbot >= 0 || npage < 2 || p.scroll === true) { page = Math.round((tbot + scrollTop) / div) + 1; ttop = -1; } else { ttop = 1; } } if (ttop > 0) { page = parseInt(scrollTop / div,10) + 1; npage = parseInt((scrollTop + dh) / div,10) + 2 - page; empty = true; } if (npage) { if (p.lastpage && page > p.lastpage || p.lastpage==1) { return; } if (grid.hDiv.loading) { grid.timer = setTimeout(grid.populateVisible, p.scrollTimeout); } else { p.page = page; if (empty) { grid.selectionPreserver(table[0]); grid.emptyRows(grid.bDiv,false); } grid.populate(npage); } } }, scrollGrid: function() { if(p.scroll) { var scrollTop = grid.bDiv.scrollTop; if(grid.scrollTop === undefined) { grid.scrollTop = 0; } if (scrollTop != grid.scrollTop) { grid.scrollTop = scrollTop; if (grid.timer) { clearTimeout(grid.timer); } grid.timer = setTimeout(grid.populateVisible, p.scrollTimeout); } } grid.hDiv.scrollLeft = grid.bDiv.scrollLeft; if(p.footerrow) { grid.sDiv.scrollLeft = grid.bDiv.scrollLeft; } }, selectionPreserver : function(ts) { var p = ts.p; var sr = p.selrow, sra = p.selarrrow ? $.makeArray(p.selarrrow) : null; var left = ts.grid.bDiv.scrollLeft; var complete = p.gridComplete; p.gridComplete = function() { p.selrow = null; p.selarrrow = []; if(p.multiselect && sra && sra.length>0) { for(var i=0;i<sra.length;i++){ if (sra[i] != sr) { $(ts).jqGrid("setSelection",sra[i],false); } } } if (sr) { $(ts).jqGrid("setSelection",sr,false); } ts.grid.bDiv.scrollLeft = left; p.gridComplete = complete; if (p.gridComplete) { complete(); } }; } }; if(this.tagName != 'TABLE') { alert("Element is not a table"); return; } $(this).empty(); this.p = p ; var i, dir,ts, clm; if(this.p.colNames.length === 0) { for (i=0;i<this.p.colModel.length;i++){ this.p.colNames[i] = this.p.colModel[i].label || this.p.colModel[i].name; } } if( this.p.colNames.length !== this.p.colModel.length ) { alert($.jgrid.errors.model); return; } var gv = $("<div class='ui-jqgrid-view'></div>"), ii, isMSIE = $.browser.msie ? true:false, isSafari = $.browser.safari ? true : false; ts = this; ts.p.direction = $.trim(ts.p.direction.toLowerCase()); if($.inArray(ts.p.direction,["ltr","rtl"]) == -1) { ts.p.direction = "ltr"; } dir = ts.p.direction; $(gv).insertBefore(this); $(this).appendTo(gv).removeClass("scroll"); var eg = $("<div class='ui-jqgrid ui-widget ui-widget-content ui-corner-all'></div>"); $(eg).insertBefore(gv).attr({"id" : "gbox_"+this.id,"dir":dir}); $(gv).appendTo(eg).attr("id","gview_"+this.id); if (isMSIE && $.browser.version <= 6) { ii = '<iframe style="display:block;position:absolute;z-index:-1;filter:Alpha(Opacity=\'0\');" src="javascript:false;"></iframe>'; } else { ii="";} $("<div class='ui-widget-overlay jqgrid-overlay' id='lui_"+this.id+"'></div>").append(ii).insertBefore(gv); $("<div class='loading ui-state-default ui-state-active' id='load_"+this.id+"'>"+this.p.loadtext+"</div>").insertBefore(gv); $(this).attr({cellspacing:"0",cellpadding:"0",border:"0","role":"grid","aria-multiselectable":!!this.p.multiselect,"aria-labelledby":"gbox_"+this.id}); var sortkeys = ["shiftKey","altKey","ctrlKey"], intNum = function(val,defval) { val = parseInt(val,10); if (isNaN(val)) { return defval ? defval : 0;} else {return val;} }, formatCol = function (pos, rowInd, tv){ var cm = ts.p.colModel[pos], ral = cm.align, result="style=\"", clas = cm.classes, nm = cm.name; if(ral) { result += "text-align:"+ral+";"; } if(cm.hidden===true) { result += "display:none;"; } if(rowInd===0) { result += "width: "+grid.headers[pos].width+"px;"; } result += "\"" + (clas !== undefined ? (" class=\""+clas+"\"") :"") + ((cm.title && tv) ? (" title=\""+$.jgrid.stripHtml(tv)+"\"") :""); result += " aria-describedby=\""+ts.p.id+"_"+nm+"\""; return result; }, cellVal = function (val) { return val === undefined || val === null || val === "" ? "&#160;" : (ts.p.autoencode ? $.jgrid.htmlEncode(val) : val+""); }, formatter = function (rowId, cellval , colpos, rwdat, _act){ var cm = ts.p.colModel[colpos],v; if(typeof cm.formatter !== 'undefined') { var opts= {rowId: rowId, colModel:cm, gid:ts.p.id, pos:colpos }; if($.isFunction( cm.formatter ) ) { v = cm.formatter.call(ts,cellval,opts,rwdat,_act); } else if($.fmatter){ v = $.fn.fmatter(cm.formatter, cellval,opts, rwdat, _act); } else { v = cellVal(cellval); } } else { v = cellVal(cellval); } return v; }, addCell = function(rowId,cell,pos,irow, srvr) { var v,prp; v = formatter(rowId,cell,pos,srvr,'add'); prp = formatCol( pos,irow, v); return "<td role=\"gridcell\" "+prp+">"+v+"</td>"; }, addMulti = function(rowid,pos,irow){ var v = "<input role=\"checkbox\" type=\"checkbox\""+" id=\"jqg_"+ts.p.id+"_"+rowid+"\" class=\"cbox\" name=\"jqg_"+ts.p.id+"_"+rowid+"\"/>", prp = formatCol(pos,irow,''); return "<td role=\"gridcell\" "+prp+">"+v+"</td>"; }, addRowNum = function (pos,irow,pG,rN) { var v = (parseInt(pG,10)-1)*parseInt(rN,10)+1+irow, prp = formatCol(pos,irow,''); return "<td role=\"gridcell\" class=\"ui-state-default jqgrid-rownum\" "+prp+">"+v+"</td>"; }, reader = function (datatype) { var field, f=[], j=0, i; for(i =0; i<ts.p.colModel.length; i++){ field = ts.p.colModel[i]; if (field.name !== 'cb' && field.name !=='subgrid' && field.name !=='rn') { if(datatype == "local") { f[j] = field.name; } else { f[j] = (datatype=="xml") ? field.xmlmap || field.name : field.jsonmap || field.name; } j++; } } return f; }, orderedCols = function (offset) { var order = ts.p.remapColumns; if (!order || !order.length) { order = $.map(ts.p.colModel, function(v,i) { return i; }); } if (offset) { order = $.map(order, function(v) { return v<offset?null:v-offset; }); } return order; }, emptyRows = function (parent, scroll) { if(ts.p.deepempty) {$("#"+ts.p.id+" tbody:first tr:gt(0)").remove();} else { var trf = $("#"+ts.p.id+" tbody:first tr:first")[0]; $("#"+ts.p.id+" tbody:first").empty().append(trf); } if (scroll && ts.p.scroll) { $(">div:first", parent).css({height:"auto"}).children("div:first").css({height:0,display:"none"}); parent.scrollTop = 0; } }, refreshIndex = function() { var datalen = ts.p.data.length, idname, i, val, ni = ts.p.rownumbers===true ? 1 :0, gi = ts.p.multiselect ===true ? 1 :0, si = ts.p.subGrid===true ? 1 :0; if(ts.p.keyIndex === false || ts.p.loadonce === true) { idname = ts.p.localReader.id; } else { idname = ts.p.colModel[ts.p.keyIndex+gi+si+ni].name; } for(i =0;i < datalen; i++) { val = $.jgrid.getAccessor(ts.p.data[i],idname); ts.p._index[val] = i; } }, addXmlData = function (xml,t, rcnt, more, adjust) { var startReq = new Date(), locdata = (ts.p.datatype != "local" && ts.p.loadonce) || ts.p.datatype == "xmlstring", xmlid, frd = ts.p.datatype == "local" ? "local" : "xml"; if(locdata) { ts.p.data = []; ts.p._index = {}; ts.p.localReader.id = xmlid = "_id_"; } ts.p.reccount = 0; if($.isXMLDoc(xml)) { if(ts.p.treeANode===-1 && !ts.p.scroll) { emptyRows(t,false); rcnt=1; } else { rcnt = rcnt > 1 ? rcnt :1; } } else { return; } var i,fpos,ir=0,v,row,gi=0,si=0,ni=0,idn, getId,f=[],F,rd ={}, xmlr,rid, rowData=[], cn=(ts.p.altRows === true) ? " "+ts.p.altclass:"",cn1; if(!ts.p.xmlReader.repeatitems) {f = reader(frd);} if( ts.p.keyIndex===false) { idn = ts.p.xmlReader.id; } else { idn = ts.p.keyIndex; } if(f.length>0 && !isNaN(idn)) { if (ts.p.remapColumns && ts.p.remapColumns.length) { idn = $.inArray(idn, ts.p.remapColumns); } idn=f[idn]; } if( (idn+"").indexOf("[") === -1 ) { if (f.length) { getId = function( trow, k) {return $(idn,trow).text() || k;}; } else { getId = function( trow, k) {return $(ts.p.xmlReader.cell,trow).eq(idn).text() || k;}; } } else { getId = function( trow, k) {return trow.getAttribute(idn.replace(/[\[\]]/g,"")) || k;}; } ts.p.userData = {}; $(ts.p.xmlReader.page,xml).each(function() {ts.p.page = this.textContent || this.text || 0; }); $(ts.p.xmlReader.total,xml).each(function() {ts.p.lastpage = this.textContent || this.text; if(ts.p.lastpage===undefined) { ts.p.lastpage=1; } } ); $(ts.p.xmlReader.records,xml).each(function() {ts.p.records = this.textContent || this.text || 0; } ); $(ts.p.xmlReader.userdata,xml).each(function() {ts.p.userData[this.getAttribute("name")]=this.textContent || this.text;}); var gxml = $(ts.p.xmlReader.root+" "+ts.p.xmlReader.row,xml); if (!gxml) { gxml = []; } var gl = gxml.length, j=0; if(gxml && gl){ var rn = parseInt(ts.p.rowNum,10),br=ts.p.scroll?(parseInt(ts.p.page,10)-1)*rn+1:1,altr; if (adjust) { rn *= adjust+1; } var afterInsRow = $.isFunction(ts.p.afterInsertRow), grpdata={}, hiderow=""; if(ts.p.grouping && ts.p.groupingView.groupCollapse === true) { hiderow = " style=\"display:none;\""; } while (j<gl) { xmlr = gxml[j]; rid = getId(xmlr,br+j); altr = rcnt === 0 ? 0 : rcnt+1; cn1 = (altr+j)%2 == 1 ? cn : ''; rowData.push( "<tr"+hiderow+" id=\""+rid+"\" role=\"row\" class =\"ui-widget-content jqgrow ui-row-"+ts.p.direction+""+cn1+"\">" ); if(ts.p.rownumbers===true) { rowData.push( addRowNum(0,j,ts.p.page,ts.p.rowNum) ); ni=1; } if(ts.p.multiselect===true) { rowData.push( addMulti(rid,ni,j) ); gi=1; } if (ts.p.subGrid===true) { rowData.push( $(ts).jqGrid("addSubGridCell",gi+ni,j+rcnt) ); si= 1; } if(ts.p.xmlReader.repeatitems){ if (!F) { F=orderedCols(gi+si+ni); } var cells = $(ts.p.xmlReader.cell,xmlr); $.each(F, function (k) { var cell = cells[this]; if (!cell) { return false; } v = cell.textContent || cell.text; rd[ts.p.colModel[k+gi+si+ni].name] = v; rowData.push( addCell(rid,v,k+gi+si+ni,j+rcnt,xmlr) ); }); } else { for(i = 0; i < f.length;i++) { v = $(f[i],xmlr).text(); rd[ts.p.colModel[i+gi+si+ni].name] = v; rowData.push( addCell(rid, v, i+gi+si+ni, j+rcnt, xmlr) ); } } rowData.push("</tr>"); if(ts.p.grouping) { var grlen = ts.p.groupingView.groupField.length, grpitem = []; for(var z=0;z<grlen;z++) { grpitem.push(rd[ts.p.groupingView.groupField[z]]); } grpdata = $(ts).jqGrid('groupingPrepare',rowData, grpitem, grpdata, rd); rowData = []; } if(locdata) { rd[xmlid] = rid; ts.p.data.push(rd); } if(ts.p.gridview === false ) { if( ts.p.treeGrid === true) { fpos = ts.p.treeANode > -1 ? ts.p.treeANode: 0; row = $(rowData.join(''))[0]; // speed overhead $(ts.rows[j+fpos]).after(row); try {$(ts).jqGrid("setTreeNode",rd,row);} catch (e) {} } else { $("tbody:first",t).append(rowData.join('')); } if (ts.p.subGrid===true) { try {$(ts).jqGrid("addSubGrid",ts.rows[ts.rows.length-1],gi+ni);} catch (_){} } if(afterInsRow) {ts.p.afterInsertRow.call(ts,rid,rd,xmlr);} rowData=[]; } rd={}; ir++; j++; if(ir==rn) {break;} } } if(ts.p.gridview === true) { if(ts.p.grouping) { $(ts).jqGrid('groupingRender',grpdata,ts.p.colModel.length); grpdata = null; } else { $("tbody:first",t).append(rowData.join('')); } } ts.p.totaltime = new Date() - startReq; if(ir>0) { if(ts.p.records===0) { ts.p.records=gl;} } rowData =null; if(!ts.p.treeGrid && !ts.p.scroll) {ts.grid.bDiv.scrollTop = 0;} ts.p.reccount=ir; ts.p.treeANode = -1; if(ts.p.userDataOnFooter) { $(ts).jqGrid("footerData","set",ts.p.userData,true); } if(locdata) { ts.p.records = gl; ts.p.lastpage = Math.ceil(gl/ rn); } if (!more) { ts.updatepager(false,true); } if(locdata) { while (ir<gl) { xmlr = gxml[ir]; rid = getId(xmlr,ir); if(ts.p.xmlReader.repeatitems){ if (!F) { F=orderedCols(gi+si+ni); } var cells2 = $(ts.p.xmlReader.cell,xmlr); $.each(F, function (k) { var cell = cells2[this]; if (!cell) { return false; } v = cell.textContent || cell.text; rd[ts.p.colModel[k+gi+si+ni].name] = v; }); } else { for(i = 0; i < f.length;i++) { v = $(f[i],xmlr).text(); rd[ts.p.colModel[i+gi+si+ni].name] = v; } } rd[xmlid] = rid; ts.p.data.push(rd); rd = {}; ir++; } refreshIndex(); } }, addJSONData = function(data,t, rcnt, more, adjust) { var startReq = new Date(); if(data) { if(ts.p.treeANode === -1 && !ts.p.scroll) { emptyRows(t,false); rcnt=1; } else { rcnt = rcnt > 1 ? rcnt :1; } } else { return; } var dReader, locid, frd, locdata = (ts.p.datatype != "local" && ts.p.loadonce) || ts.p.datatype == "jsonstring"; if(locdata) { ts.p.data = []; ts.p._index = {}; locid = ts.p.localReader.id = "_id_";} ts.p.reccount = 0; if(ts.p.datatype == "local") { dReader = ts.p.localReader; frd= 'local'; } else { dReader = ts.p.jsonReader; frd='json'; } var ir=0,v,i,j,row,f=[],F,cur,gi=0,si=0,ni=0,len,drows,idn,rd={}, fpos, idr,rowData=[],cn=(ts.p.altRows === true) ? " "+ts.p.altclass:"",cn1,lp; ts.p.page = $.jgrid.getAccessor(data,dReader.page) || 0; lp = $.jgrid.getAccessor(data,dReader.total); ts.p.lastpage = lp === undefined ? 1 : lp; ts.p.records = $.jgrid.getAccessor(data,dReader.records) || 0; ts.p.userData = $.jgrid.getAccessor(data,dReader.userdata) || {}; if(!dReader.repeatitems) { F = f = reader(frd); } if( ts.p.keyIndex===false ) { idn = dReader.id; } else { idn = ts.p.keyIndex; } if(f.length>0 && !isNaN(idn)) { if (ts.p.remapColumns && ts.p.remapColumns.length) { idn = $.inArray(idn, ts.p.remapColumns); } idn=f[idn]; } drows = $.jgrid.getAccessor(data,dReader.root); if (!drows) { drows = []; } len = drows.length; i=0; var rn = parseInt(ts.p.rowNum,10),br=ts.p.scroll?(parseInt(ts.p.page,10)-1)*rn+1:1, altr; if (adjust) { rn *= adjust+1; } var afterInsRow = $.isFunction(ts.p.afterInsertRow), grpdata={}, hiderow=""; if(ts.p.grouping && ts.p.groupingView.groupCollapse === true) { hiderow = " style=\"display:none;\""; } while (i<len) { cur = drows[i]; idr = $.jgrid.getAccessor(cur,idn); if(idr === undefined) { idr = br+i; if(f.length===0){ if(dReader.cell){ var ccur = cur[dReader.cell]; idr = ccur[idn] || idr; ccur=null; } } } altr = rcnt === 1 ? 0 : rcnt; cn1 = (altr+i)%2 == 1 ? cn : ''; rowData.push("<tr"+hiderow+" id=\""+ idr +"\" role=\"row\" class= \"ui-widget-content jqgrow ui-row-"+ts.p.direction+""+cn1+"\">"); if(ts.p.rownumbers===true) { rowData.push( addRowNum(0,i,ts.p.page,ts.p.rowNum) ); ni=1; } if(ts.p.multiselect){ rowData.push( addMulti(idr,ni,i) ); gi = 1; } if (ts.p.subGrid) { rowData.push( $(ts).jqGrid("addSubGridCell",gi+ni,i+rcnt) ); si= 1; } if (dReader.repeatitems) { if(dReader.cell) {cur = $.jgrid.getAccessor(cur,dReader.cell);} if (!F) { F=orderedCols(gi+si+ni); } } for (j=0;j<F.length;j++) { v = $.jgrid.getAccessor(cur,F[j]); rowData.push( addCell(idr,v,j+gi+si+ni,i+rcnt,cur) ); rd[ts.p.colModel[j+gi+si+ni].name] = v; } rowData.push( "</tr>" ); if(ts.p.grouping) { var grlen = ts.p.groupingView.groupField.length, grpitem = []; for(var z=0;z<grlen;z++) { grpitem.push(rd[ts.p.groupingView.groupField[z]]); } grpdata = $(ts).jqGrid('groupingPrepare',rowData, grpitem, grpdata, rd); rowData = []; } if(locdata) { rd[locid] = idr; ts.p.data.push(rd); } if(ts.p.gridview === false ) { if( ts.p.treeGrid === true) { fpos = ts.p.treeANode > -1 ? ts.p.treeANode: 0; row = $(rowData.join(''))[0]; $(ts.rows[i+fpos]).after(row); try {$(ts).jqGrid("setTreeNode",rd,row);} catch (e) {} } else { $("#"+ts.p.id+" tbody:first").append(rowData.join('')); } if(ts.p.subGrid === true ) { try { $(ts).jqGrid("addSubGrid",ts.rows[ts.rows.length-1],gi+ni);} catch (_){} } if(afterInsRow) {ts.p.afterInsertRow.call(ts,idr,rd,cur);} rowData=[];//ari=0; } rd={}; ir++; i++; if(ir==rn) { break; } } if(ts.p.gridview === true ) { if(ts.p.grouping) { $(ts).jqGrid('groupingRender',grpdata,ts.p.colModel.length); grpdata = null; } else { $("#"+ts.p.id+" tbody:first").append(rowData.join('')); } } ts.p.totaltime = new Date() - startReq; if(ir>0) { if(ts.p.records===0) { ts.p.records=len; } } rowData = null; if(!ts.p.treeGrid && !ts.p.scroll) {ts.grid.bDiv.scrollTop = 0;} ts.p.reccount=ir; ts.p.treeANode = -1; if(ts.p.userDataOnFooter) { $(ts).jqGrid("footerData","set",ts.p.userData,true); } if(locdata) { ts.p.records = len; ts.p.lastpage = Math.ceil(len/ rn); } if (!more) { ts.updatepager(false,true); } if(locdata) { while (ir<len) { cur = drows[ir]; idr = $.jgrid.getAccessor(cur,idn); if(idr === undefined) { idr = br+ir; if(f.length===0){ if(dReader.cell){ var ccur2 = cur[dReader.cell]; idr = ccur2[idn] || idr; ccur2=null; } } } if(cur) { if (dReader.repeatitems) { if(dReader.cell) {cur = $.jgrid.getAccessor(cur,dReader.cell);} if (!F) { F=orderedCols(gi+si+ni); } } for (j=0;j<F.length;j++) { v = $.jgrid.getAccessor(cur,F[j]); rd[ts.p.colModel[j+gi+si+ni].name] = v; } rd[locid] = idr; ts.p.data.push(rd); rd = {}; } ir++; } refreshIndex(); } }, addLocalData = function() { var st, fndsort=false, cmtypes=[], grtypes=[], grindexes=[], srcformat, sorttype, newformat; if(!$.isArray(ts.p.data)) { return; } var grpview = ts.p.grouping ? ts.p.groupingView : false; $.each(ts.p.colModel,function(i,v){ sorttype = this.sorttype || "text"; if(sorttype == "date" || sorttype == "datetime") { if(this.formatter && typeof(this.formatter) === 'string' && this.formatter == 'date') { if(this.formatoptions && this.formatoptions.srcformat) { srcformat = this.formatoptions.srcformat; } else { srcformat = $.jgrid.formatter.date.srcformat; } if(this.formatoptions && this.formatoptions.newformat) { newformat = this.formatoptions.newformat; } else { newformat = $.jgrid.formatter.date.newformat; } } else { srcformat = newformat = this.datefmt || "Y-m-d"; } cmtypes[this.name] = {"stype": sorttype, "srcfmt": srcformat,"newfmt":newformat}; } else { cmtypes[this.name] = {"stype": sorttype, "srcfmt":'',"newfmt":''}; } if(ts.p.grouping && this.name == grpview.groupField[0]) { var grindex = this.name if (typeof this.index != 'undefined') { grindex = this.index; } grtypes[0] = cmtypes[grindex]; grindexes.push(grindex); } if(!fndsort && (this.index == ts.p.sortname || this.name == ts.p.sortname)){ st = this.name; // ??? fndsort = true; } }); if(ts.p.treeGrid) { $(ts).jqGrid("SortTree", st, ts.p.sortorder, cmtypes[st].stype, cmtypes[st].srcfmt); return; } var compareFnMap = { 'eq':function(queryObj) {return queryObj.equals;}, 'ne':function(queryObj) {return queryObj.not().equals;}, 'lt':function(queryObj) {return queryObj.less;}, 'le':function(queryObj) {return queryObj.lessOrEquals;}, 'gt':function(queryObj) {return queryObj.greater;}, 'ge':function(queryObj) {return queryObj.greaterOrEquals;}, 'cn':function(queryObj) {return queryObj.contains;}, 'nc':function(queryObj) {return queryObj.not().contains;}, 'bw':function(queryObj) {return queryObj.startsWith;}, 'bn':function(queryObj) {return queryObj.not().startsWith;}, 'en':function(queryObj) {return queryObj.not().endsWith;}, 'ew':function(queryObj) {return queryObj.endsWith;}, 'ni':function(queryObj) {return queryObj.not().equals;}, 'in':function(queryObj) {return queryObj.equals;} }, query = $.jgrid.from(ts.p.data); if (ts.p.ignoreCase) { query = query.ignoreCase(); } if (ts.p.search === true) { var srules = ts.p.postData.filters, opr; if(srules) { if(typeof srules == "string") { srules = $.jgrid.parse(srules);} for (var i=0, l= srules.rules.length, rule; i<l; i++) { rule = srules.rules[i]; opr = srules.groupOp; if (compareFnMap[rule.op] && rule.field && rule.data && opr) { if(opr.toUpperCase() == "OR") { query = compareFnMap[rule.op](query)(rule.field, rule.data, cmtypes[rule.field]).or(); } else { query = compareFnMap[rule.op](query)(rule.field, rule.data, cmtypes[rule.field]); } } } } else { try { query = compareFnMap[ts.p.postData.searchOper](query)(ts.p.postData.searchField, ts.p.postData.searchString,cmtypes[ts.p.postData.searchField]); } catch (se){} } } if(ts.p.grouping) { query.orderBy(grindexes,grpview.groupOrder[0],grtypes[0].stype, grtypes[0].srcfmt); grpview.groupDataSorted = true; } if (st && ts.p.sortorder && fndsort) { if(ts.p.sortorder.toUpperCase() == "DESC") { query.orderBy(ts.p.sortname, "d", cmtypes[st].stype, cmtypes[st].srcfmt); } else { query.orderBy(ts.p.sortname, "a", cmtypes[st].stype, cmtypes[st].srcfmt); } } var queryResults = query.select(), recordsperpage = parseInt(ts.p.rowNum,10), total = queryResults.length, page = parseInt(ts.p.page,10), totalpages = Math.ceil(total / recordsperpage), retresult = {}; queryResults = queryResults.slice( (page-1)*recordsperpage , page*recordsperpage ); query = null; cmtypes = null; retresult[ts.p.localReader.total] = totalpages; retresult[ts.p.localReader.page] = page; retresult[ts.p.localReader.records] = total; retresult[ts.p.localReader.root] = queryResults; queryResults = null; return retresult; }, updatepager = function(rn, dnd) { var cp, last, base, from,to,tot,fmt, pgboxes = ""; base = parseInt(ts.p.page,10)-1; if(base < 0) { base = 0; } base = base*parseInt(ts.p.rowNum,10); to = base + ts.p.reccount; if (ts.p.scroll) { var rows = $("tbody:first > tr:gt(0)", ts.grid.bDiv); base = to - rows.length; ts.p.reccount = rows.length; var rh = rows.outerHeight() || ts.grid.prevRowHeight; if (rh) { var top = base * rh; var height = parseInt(ts.p.records,10) * rh; $(">div:first",ts.grid.bDiv).css({height : height}).children("div:first").css({height:top,display:top?"":"none"}); } ts.grid.bDiv.scrollLeft = ts.grid.hDiv.scrollLeft; } pgboxes = ts.p.pager ? ts.p.pager : ""; pgboxes += ts.p.toppager ? (pgboxes ? "," + ts.p.toppager : ts.p.toppager) : ""; if(pgboxes) { fmt = $.jgrid.formatter.integer || {}; cp = intNum(ts.p.page); last = intNum(ts.p.lastpage); $(".selbox",pgboxes).attr("disabled",false); if(ts.p.pginput===true) { $('.ui-pg-input',pgboxes).val(ts.p.page); $('#sp_1',pgboxes).html($.fmatter ? $.fmatter.util.NumberFormat(ts.p.lastpage,fmt):ts.p.lastpage); } if (ts.p.viewrecords){ if(ts.p.reccount === 0) { $(".ui-paging-info",pgboxes).html(ts.p.emptyrecords); } else { from = base+1; tot=ts.p.records; if($.fmatter) { from = $.fmatter.util.NumberFormat(from,fmt); to = $.fmatter.util.NumberFormat(to,fmt); tot = $.fmatter.util.NumberFormat(tot,fmt); } $(".ui-paging-info",pgboxes).html($.jgrid.format(ts.p.recordtext,from,to,tot)); } } if(ts.p.pgbuttons===true) { if(cp<=0) {cp = last = 0;} if(cp==1 || cp === 0) { $("#first, #prev",ts.p.pager).addClass('ui-state-disabled').removeClass('ui-state-hover'); if(ts.p.toppager) { $("#first_t, #prev_t",ts.p.toppager).addClass('ui-state-disabled').removeClass('ui-state-hover'); } } else { $("#first, #prev",ts.p.pager).removeClass('ui-state-disabled'); if(ts.p.toppager) { $("#first_t, #prev_t",ts.p.toppager).removeClass('ui-state-disabled'); } } if(cp==last || cp === 0) { $("#next, #last",ts.p.pager).addClass('ui-state-disabled').removeClass('ui-state-hover'); if(ts.p.toppager) { $("#next_t, #last_t",ts.p.toppager).addClass('ui-state-disabled').removeClass('ui-state-hover'); } } else { $("#next, #last",ts.p.pager).removeClass('ui-state-disabled'); if(ts.p.toppager) { $("#next_t, #last_t",ts.p.toppager).removeClass('ui-state-disabled'); } } } } if(rn===true && ts.p.rownumbers === true) { $("td.jqgrid-rownum",ts.rows).each(function(i){ $(this).html(base+1+i); }); } if(dnd && ts.p.jqgdnd) { $(ts).jqGrid('gridDnD','updateDnD');} if($.isFunction(ts.p.gridComplete)) {ts.p.gridComplete.call(ts);} }, beginReq = function() { ts.grid.hDiv.loading = true; if(ts.p.hiddengrid) { return;} switch(ts.p.loadui) { case "disable": break; case "enable": $("#load_"+ts.p.id).show(); break; case "block": $("#lui_"+ts.p.id).show(); $("#load_"+ts.p.id).show(); break; } }, endReq = function() { ts.grid.hDiv.loading = false; switch(ts.p.loadui) { case "disable": break; case "enable": $("#load_"+ts.p.id).hide(); break; case "block": $("#lui_"+ts.p.id).hide(); $("#load_"+ts.p.id).hide(); break; } }, populate = function (npage) { if(!ts.grid.hDiv.loading) { var pvis = ts.p.scroll && npage === false; var prm = {}, dt, dstr, pN=ts.p.prmNames; if(ts.p.page <=0) { ts.p.page = 1; } if(pN.search !== null) {prm[pN.search] = ts.p.search;} if(pN.nd !== null) {prm[pN.nd] = new Date().getTime();} if(pN.rows !== null) {prm[pN.rows]= ts.p.rowNum;} if(pN.page !== null) {prm[pN.page]= ts.p.page;} if(pN.sort !== null) {prm[pN.sort]= ts.p.sortname;} if(pN.order !== null) {prm[pN.order]= ts.p.sortorder;} if(ts.p.rowTotal !== null && pN.totalrows !== null) { prm[pN.totalrows]= ts.p.rowTotal; } var lc = ts.p.loadComplete; var lcf = $.isFunction(lc); if (!lcf) { lc = null; } var adjust = 0; npage = npage || 1; if (npage > 1) { if(pN.npage !== null) { prm[pN.npage] = npage; adjust = npage - 1; npage = 1; } else { lc = function(req) { ts.p.page++; ts.grid.hDiv.loading = false; if (lcf) { ts.p.loadComplete.call(ts,req); } populate(npage-1); }; } } else if (pN.npage !== null) { delete ts.p.postData[pN.npage]; } if(ts.p.grouping) { $(ts).jqGrid('groupingSetup'); if(ts.p.groupingView.groupDataSorted === true) { prm[pN.sort] = ts.p.groupingView.groupField[0] +" "+ ts.p.groupingView.groupOrder[0]+", "+prm[pN.sort]; } } $.extend(ts.p.postData,prm); var rcnt = !ts.p.scroll ? 1 : ts.rows.length-1; if ($.isFunction(ts.p.datatype)) { ts.p.datatype.call(ts,ts.p.postData,"load_"+ts.p.id); return;} else if($.isFunction(ts.p.beforeRequest)) {ts.p.beforeRequest.call(ts);} dt = ts.p.datatype.toLowerCase(); switch(dt) { case "json": case "jsonp": case "xml": case "script": $.ajax($.extend({ url:ts.p.url, type:ts.p.mtype, dataType: dt , data: $.isFunction(ts.p.serializeGridData)? ts.p.serializeGridData.call(ts,ts.p.postData) : ts.p.postData, success:function(data,st) { if(dt === "xml") { addXmlData(data,ts.grid.bDiv,rcnt,npage>1,adjust); } else { addJSONData(data,ts.grid.bDiv,rcnt,npage>1,adjust); } if(lc) { lc.call(ts,data); } if (pvis) { ts.grid.populateVisible(); } if( ts.p.loadonce || ts.p.treeGrid) {ts.p.datatype = "local";} data=null; endReq(); }, error:function(xhr,st,err){ if($.isFunction(ts.p.loadError)) { ts.p.loadError.call(ts,xhr,st,err); } endReq(); xhr=null; }, beforeSend: function(xhr){ beginReq(); if($.isFunction(ts.p.loadBeforeSend)) { ts.p.loadBeforeSend.call(ts,xhr); } } },$.jgrid.ajaxOptions, ts.p.ajaxGridOptions)); break; case "xmlstring": beginReq(); dstr = $.jgrid.stringToDoc(ts.p.datastr); addXmlData(dstr,ts.grid.bDiv); if(lcf) {ts.p.loadComplete.call(ts,dstr);} ts.p.datatype = "local"; ts.p.datastr = null; endReq(); break; case "jsonstring": beginReq(); if(typeof ts.p.datastr == 'string') { dstr = $.jgrid.parse(ts.p.datastr); } else { dstr = ts.p.datastr; } addJSONData(dstr,ts.grid.bDiv); if(lcf) {ts.p.loadComplete.call(ts,dstr);} ts.p.datatype = "local"; ts.p.datastr = null; endReq(); break; case "local": case "clientside": beginReq(); ts.p.datatype = "local"; var req = addLocalData(); addJSONData(req,ts.grid.bDiv,rcnt,npage>1,adjust); if(lc) { lc.call(ts,req); } if (pvis) { ts.grid.populateVisible(); } endReq(); break; } } }, setPager = function (pgid, tp){ var sep = "<td class='ui-pg-button ui-state-disabled' style='width:4px;'><span class='ui-separator'></span></td>", pginp = "", pgl="<table cellspacing='0' cellpadding='0' border='0' style='table-layout:auto;' class='ui-pg-table'><tbody><tr>", str="", pgcnt, lft, cent, rgt, twd, tdw, i, clearVals = function(onpaging){ var ret; if ($.isFunction(ts.p.onPaging) ) { ret = ts.p.onPaging.call(ts,onpaging); } ts.p.selrow = null; if(ts.p.multiselect) {ts.p.selarrrow =[];$('#cb_'+$.jgrid.jqID(ts.p.id),ts.grid.hDiv).attr("checked",false);} ts.p.savedRow = []; if(ret=='stop') {return false;} return true; }; pgid = pgid.substr(1); pgcnt = "pg_"+pgid; lft = pgid+"_left"; cent = pgid+"_center"; rgt = pgid+"_right"; $("#"+pgid) .append("<div id='"+pgcnt+"' class='ui-pager-control' role='group'><table cellspacing='0' cellpadding='0' border='0' class='ui-pg-table' style='width:100%;table-layout:fixed;height:100%;' role='row'><tbody><tr><td id='"+lft+"' align='left'></td><td id='"+cent+"' align='center' style='white-space:pre;'></td><td id='"+rgt+"' align='right'></td></tr></tbody></table></div>") .attr("dir","ltr"); //explicit setting if(ts.p.rowList.length >0){ str = "<td dir='"+dir+"'>"; str +="<select class='ui-pg-selbox' role='listbox'>"; for(i=0;i<ts.p.rowList.length;i++){ str +="<option role=\"option\" value=\""+ts.p.rowList[i]+"\""+((ts.p.rowNum == ts.p.rowList[i])?" selected=\"selected\"":"")+">"+ts.p.rowList[i]+"</option>"; } str +="</select></td>"; } if(dir=="rtl") { pgl += str; } if(ts.p.pginput===true) { pginp= "<td dir='"+dir+"'>"+$.jgrid.format(ts.p.pgtext || "","<input class='ui-pg-input' type='text' size='2' maxlength='7' value='0' role='textbox'/>","<span id='sp_1'></span>")+"</td>";} if(ts.p.pgbuttons===true) { var po=["first"+tp,"prev"+tp, "next"+tp,"last"+tp]; if(dir=="rtl") { po.reverse(); } pgl += "<td id='"+po[0]+"' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-first'></span></td>"; pgl += "<td id='"+po[1]+"' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-prev'></span></td>"; pgl += pginp !== "" ? sep+pginp+sep:""; pgl += "<td id='"+po[2]+"' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-next'></span></td>"; pgl += "<td id='"+po[3]+"' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-end'></span></td>"; } else if (pginp !== "") { pgl += pginp; } if(dir=="ltr") { pgl += str; } pgl += "</tr></tbody></table>"; if(ts.p.viewrecords===true) {$("td#"+pgid+"_"+ts.p.recordpos,"#"+pgcnt).append("<div dir='"+dir+"' style='text-align:"+ts.p.recordpos+"' class='ui-paging-info'></div>");} $("td#"+pgid+"_"+ts.p.pagerpos,"#"+pgcnt).append(pgl); tdw = $(".ui-jqgrid").css("font-size") || "11px"; $(document.body).append("<div id='testpg' class='ui-jqgrid ui-widget ui-widget-content' style='font-size:"+tdw+";visibility:hidden;' ></div>"); twd = $(pgl).clone().appendTo("#testpg").width(); $("#testpg").remove(); if(twd > 0) { if(pginp !="") { twd += 50; } //should be param $("td#"+pgid+"_"+ts.p.pagerpos,"#"+pgcnt).width(twd); } ts.p._nvtd = []; ts.p._nvtd[0] = twd ? Math.floor((ts.p.width - twd)/2) : Math.floor(ts.p.width/3); ts.p._nvtd[1] = 0; pgl=null; $('.ui-pg-selbox',"#"+pgcnt).bind('change',function() { ts.p.page = Math.round(ts.p.rowNum*(ts.p.page-1)/this.value-0.5)+1; ts.p.rowNum = this.value; if(tp) { $('.ui-pg-selbox',ts.p.pager).val(this.value); } else if(ts.p.toppager) { $('.ui-pg-selbox',ts.p.toppager).val(this.value); } if(!clearVals('records')) { return false; } populate(); return false; }); if(ts.p.pgbuttons===true) { $(".ui-pg-button","#"+pgcnt).hover(function(e){ if($(this).hasClass('ui-state-disabled')) { this.style.cursor='default'; } else { $(this).addClass('ui-state-hover'); this.style.cursor='pointer'; } },function(e) { if($(this).hasClass('ui-state-disabled')) { } else { $(this).removeClass('ui-state-hover'); this.style.cursor= "default"; } }); $("#first"+tp+", #prev"+tp+", #next"+tp+", #last"+tp,"#"+pgid).click( function(e) { var cp = intNum(ts.p.page,1), last = intNum(ts.p.lastpage,1), selclick = false, fp=true, pp=true, np=true,lp=true; if(last ===0 || last===1) {fp=false;pp=false;np=false;lp=false; } else if( last>1 && cp >=1) { if( cp === 1) { fp=false; pp=false; } else if( cp>1 && cp <last){ } else if( cp===last){ np=false;lp=false; } } else if( last>1 && cp===0 ) { np=false;lp=false; cp=last-1;} if( this.id === 'first'+tp && fp ) { ts.p.page=1; selclick=true;} if( this.id === 'prev'+tp && pp) { ts.p.page=(cp-1); selclick=true;} if( this.id === 'next'+tp && np) { ts.p.page=(cp+1); selclick=true;} if( this.id === 'last'+tp && lp) { ts.p.page=last; selclick=true;} if(selclick) { if(!clearVals(this.id)) { return false; } populate(); } return false; }); } if(ts.p.pginput===true) { $('input.ui-pg-input',"#"+pgcnt).keypress( function(e) { var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0; if(key == 13) { ts.p.page = ($(this).val()>0) ? $(this).val():ts.p.page; if(!clearVals('user')) { return false; } populate(); return false; } return this; }); } }, sortData = function (index, idxcol,reload,sor){ if(!ts.p.colModel[idxcol].sortable) { return; } var so; if(ts.p.savedRow.length > 0) {return;} if(!reload) { if( ts.p.lastsort == idxcol ) { if( ts.p.sortorder == 'asc') { ts.p.sortorder = 'desc'; } else if(ts.p.sortorder == 'desc') { ts.p.sortorder = 'asc';} } else { ts.p.sortorder = ts.p.colModel[idxcol].firstsortorder || 'asc'; } ts.p.page = 1; } if(sor) { if(ts.p.lastsort == idxcol && ts.p.sortorder == sor && !reload) { return; } else { ts.p.sortorder = sor; } } var thd= $("thead:first",ts.grid.hDiv).get(0); $("tr th:eq("+ts.p.lastsort+") span.ui-grid-ico-sort",thd).addClass('ui-state-disabled'); $("tr th:eq("+ts.p.lastsort+")",thd).attr("aria-selected","false"); $("tr th:eq("+idxcol+") span.ui-icon-"+ts.p.sortorder,thd).removeClass('ui-state-disabled'); $("tr th:eq("+idxcol+")",thd).attr("aria-selected","true"); if(!ts.p.viewsortcols[0]) { if(ts.p.lastsort != idxcol) { $("tr th:eq("+ts.p.lastsort+") span.s-ico",thd).hide(); $("tr th:eq("+idxcol+") span.s-ico",thd).show(); } } index = index.substring(5); ts.p.sortname = ts.p.colModel[idxcol].index || index; so = ts.p.sortorder; if($.isFunction(ts.p.onSortCol)) {if (ts.p.onSortCol.call(ts,index,idxcol,so)=='stop') {ts.p.lastsort = idxcol; return;}} if(ts.p.datatype == "local") { if(ts.p.deselectAfterSort) {$(ts).jqGrid("resetSelection");} } else { ts.p.selrow = null; if(ts.p.multiselect){$("#cb_"+$.jgrid.jqID(ts.p.id),ts.grid.hDiv).attr("checked",false);} ts.p.selarrrow =[]; ts.p.savedRow =[]; } if(ts.p.scroll) { var sscroll = ts.grid.bDiv.scrollLeft; emptyRows(ts.grid.bDiv,true); ts.grid.hDiv.scrollLeft = sscroll; } if(ts.p.subGrid && ts.p.datatype=='local') { $("td.sgexpanded","#"+ts.p.id).each(function(){ $(this).trigger("click"); }); } populate(); ts.p.lastsort = idxcol; if(ts.p.sortname != index && idxcol) {ts.p.lastsort = idxcol;} }, setColWidth = function () { var initwidth = 0, brd=ts.p.cellLayout, vc=0, lvc, scw=ts.p.scrollOffset,cw,hs=false,aw,tw=0,gw=0, cl = 0, cr; if (isSafari) { brd=0; } $.each(ts.p.colModel, function(i) { if(typeof this.hidden === 'undefined') {this.hidden=false;} if(this.hidden===false){ initwidth += intNum(this.width,0); if(this.fixed) { tw += this.width; gw += this.width+brd; } else { vc++; } cl++; } }); if(isNaN(ts.p.width)) {ts.p.width = grid.width = initwidth;} else { grid.width = ts.p.width;} ts.p.tblwidth = initwidth; if(ts.p.shrinkToFit ===false && ts.p.forceFit === true) {ts.p.forceFit=false;} if(ts.p.shrinkToFit===true && vc > 0) { aw = grid.width-brd*vc-gw; if(isNaN(ts.p.height)) { } else { aw -= scw; hs = true; } initwidth =0; $.each(ts.p.colModel, function(i) { if(this.hidden === false && !this.fixed){ cw = Math.round(aw*this.width/(ts.p.tblwidth-tw)); this.width =cw; initwidth += cw; lvc = i; } }); cr =0; if (hs) { if(grid.width-gw-(initwidth+brd*vc) !== scw){ cr = grid.width-gw-(initwidth+brd*vc)-scw; } } else if(!hs && Math.abs(grid.width-gw-(initwidth+brd*vc)) !== 1) { cr = grid.width-gw-(initwidth+brd*vc); } ts.p.colModel[lvc].width += cr; ts.p.tblwidth = initwidth+cr+tw+cl*brd; if(ts.p.tblwidth > ts.p.width) { ts.p.colModel[lvc].width -= (ts.p.tblwidth - parseInt(ts.p.width,10)); ts.p.tblwidth = ts.p.width; } } }, nextVisible= function(iCol) { var ret = iCol, j=iCol, i; for (i = iCol+1;i<ts.p.colModel.length;i++){ if(ts.p.colModel[i].hidden !== true ) { j=i; break; } } return j-ret; }, getOffset = function (iCol) { var i, ret = {}, brd1 = isSafari ? 0 : ts.p.cellLayout; ret[0] = ret[1] = ret[2] = 0; for(i=0;i<=iCol;i++){ if(ts.p.colModel[i].hidden === false ) { ret[0] += ts.p.colModel[i].width+brd1; } } if(ts.p.direction=="rtl") { ret[0] = ts.p.width - ret[0]; } ret[0] = ret[0] - ts.grid.bDiv.scrollLeft; if($(ts.grid.cDiv).is(":visible")) {ret[1] += $(ts.grid.cDiv).height() +parseInt($(ts.grid.cDiv).css("padding-top"),10)+parseInt($(ts.grid.cDiv).css("padding-bottom"),10);} if(ts.p.toolbar[0]===true && (ts.p.toolbar[1]=='top' || ts.p.toolbar[1]=='both')) {ret[1] += $(ts.grid.uDiv).height()+parseInt($(ts.grid.uDiv).css("border-top-width"),10)+parseInt($(ts.grid.uDiv).css("border-bottom-width"),10);} if(ts.p.toppager) {ret[1] += $(ts.grid.topDiv).height()+parseInt($(ts.grid.topDiv).css("border-bottom-width"),10);} ret[2] += $(ts.grid.bDiv).height() + $(ts.grid.hDiv).height(); return ret; }; this.p.id = this.id; if ($.inArray(ts.p.multikey,sortkeys) == -1 ) {ts.p.multikey = false;} ts.p.keyIndex=false; for (i=0; i<ts.p.colModel.length;i++) { clm = ts.p.colModel[i]; clm = $.extend(clm, ts.p.cmTemplate, clm.template || {}); if (ts.p.keyIndex === false && ts.p.colModel[i].key===true) { ts.p.keyIndex = i; } } ts.p.sortorder = ts.p.sortorder.toLowerCase(); if(ts.p.grouping===true) { ts.p.scroll = false; ts.p.rownumbers = false; ts.p.subGrid = false; ts.p.treeGrid = false; ts.p.gridview = true; } if(this.p.treeGrid === true) { try { $(this).jqGrid("setTreeGrid");} catch (_) {} if(ts.p.datatype != "local") { ts.p.localReader = {id: "_id_"}; } } if(this.p.subGrid) { try { $(ts).jqGrid("setSubGrid");} catch (_){} } if(this.p.multiselect) { this.p.colNames.unshift("<input role='checkbox' id='cb_"+this.p.id+"' class='cbox' type='checkbox'/>"); this.p.colModel.unshift({name:'cb',width:isSafari ? ts.p.multiselectWidth+ts.p.cellLayout : ts.p.multiselectWidth,sortable:false,resizable:false,hidedlg:true,search:false,align:'center',fixed:true}); } if(this.p.rownumbers) { this.p.colNames.unshift(""); this.p.colModel.unshift({name:'rn',width:ts.p.rownumWidth,sortable:false,resizable:false,hidedlg:true,search:false,align:'center',fixed:true}); } ts.p.xmlReader = $.extend(true,{ root: "rows", row: "row", page: "rows>page", total: "rows>total", records : "rows>records", repeatitems: true, cell: "cell", id: "[id]", userdata: "userdata", subgrid: {root:"rows", row: "row", repeatitems: true, cell:"cell"} }, ts.p.xmlReader); ts.p.jsonReader = $.extend(true,{ root: "rows", page: "page", total: "total", records: "records", repeatitems: true, cell: "cell", id: "id", userdata: "userdata", subgrid: {root:"rows", repeatitems: true, cell:"cell"} },ts.p.jsonReader); ts.p.localReader = $.extend(true,{ root: "rows", page: "page", total: "total", records: "records", repeatitems: false, cell: "cell", id: "id", userdata: "userdata", subgrid: {root:"rows", repeatitems: true, cell:"cell"} },ts.p.localReader); if(ts.p.scroll){ ts.p.pgbuttons = false; ts.p.pginput=false; ts.p.rowList=[]; } if(ts.p.data.length) { refreshIndex(); } var thead = "<thead><tr class='ui-jqgrid-labels' role='rowheader'>", tdc, idn, w, res, sort, td, ptr, tbody, imgs,iac="",idc=""; if(ts.p.shrinkToFit===true && ts.p.forceFit===true) { for (i=ts.p.colModel.length-1;i>=0;i--){ if(!ts.p.colModel[i].hidden) { ts.p.colModel[i].resizable=false; break; } } } if(ts.p.viewsortcols[1] == 'horizontal') {iac=" ui-i-asc";idc=" ui-i-desc";} tdc = isMSIE ? "class='ui-th-div-ie'" :""; imgs = "<span class='s-ico' style='display:none'><span sort='asc' class='ui-grid-ico-sort ui-icon-asc"+iac+" ui-state-disabled ui-icon ui-icon-triangle-1-n ui-sort-"+dir+"'></span>"; imgs += "<span sort='desc' class='ui-grid-ico-sort ui-icon-desc"+idc+" ui-state-disabled ui-icon ui-icon-triangle-1-s ui-sort-"+dir+"'></span></span>"; for(i=0;i<this.p.colNames.length;i++){ var tooltip = ts.p.headertitles ? (" title=\""+$.jgrid.stripHtml(ts.p.colNames[i])+"\"") :""; thead += "<th id='"+ts.p.id+"_"+ts.p.colModel[i].name+"' role='columnheader' class='ui-state-default ui-th-column ui-th-"+dir+"'"+ tooltip+">"; idn = ts.p.colModel[i].index || ts.p.colModel[i].name; thead += "<div id='jqgh_"+ts.p.colModel[i].name+"' "+tdc+">"+ts.p.colNames[i]; if(!ts.p.colModel[i].width) { ts.p.colModel[i].width = 150; } else { ts.p.colModel[i].width = parseInt(ts.p.colModel[i].width,10); } if(typeof(ts.p.colModel[i].title) !== "boolean") { ts.p.colModel[i].title = true; } if (idn == ts.p.sortname) { ts.p.lastsort = i; } thead += imgs+"</div></th>"; } thead += "</tr></thead>"; imgs = null; $(this).append(thead); $("thead tr:first th",this).hover(function(){$(this).addClass('ui-state-hover');},function(){$(this).removeClass('ui-state-hover');}); if(this.p.multiselect) { var emp=[], chk; $('#cb_'+$.jgrid.jqID(ts.p.id),this).bind('click',function(){ if (this.checked) { $("[id^=jqg_"+ts.p.id+"_"+"]").attr("checked","checked"); $(ts.rows).each(function(i) { if ( i>0 ) { if(!$(this).hasClass("subgrid") && !$(this).hasClass("jqgroup")){ $(this).addClass("ui-state-highlight").attr("aria-selected","true"); ts.p.selarrrow.push(this.id); ts.p.selrow = this.id; } } }); chk=true; emp=[]; } else { $("[id^=jqg_"+ts.p.id+"_"+"]").removeAttr("checked"); $(ts.rows).each(function(i) { if(i>0) { if(!$(this).hasClass("subgrid")){ $(this).removeClass("ui-state-highlight").attr("aria-selected","false"); emp.push(this.id); } } }); ts.p.selarrrow = []; ts.p.selrow = null; chk=false; } if($.isFunction(ts.p.onSelectAll)) {ts.p.onSelectAll.call(ts, chk ? ts.p.selarrrow : emp,chk);} }); } if(ts.p.autowidth===true) { var pw = $(eg).innerWidth(); ts.p.width = pw > 0? pw: 'nw'; } setColWidth(); $(eg).css("width",grid.width+"px").append("<div class='ui-jqgrid-resize-mark' id='rs_m"+ts.p.id+"'>&#160;</div>"); $(gv).css("width",grid.width+"px"); thead = $("thead:first",ts).get(0); var tfoot = ""; if(ts.p.footerrow) { tfoot += "<table role='grid' style='width:"+ts.p.tblwidth+"px' class='ui-jqgrid-ftable' cellspacing='0' cellpadding='0' border='0'><tbody><tr role='row' class='ui-widget-content footrow footrow-"+dir+"'>"; } var thr = $("tr:first",thead), firstr = "<tr class='jqgfirstrow' role='row' style='height:auto'>"; ts.p.disableClick=false; $("th",thr).each(function ( j ) { w = ts.p.colModel[j].width; if(typeof ts.p.colModel[j].resizable === 'undefined') {ts.p.colModel[j].resizable = true;} if(ts.p.colModel[j].resizable){ res = document.createElement("span"); $(res).html("&#160;").addClass('ui-jqgrid-resize ui-jqgrid-resize-'+dir); if(!$.browser.opera) { $(res).css("cursor","col-resize"); } $(this).addClass(ts.p.resizeclass); } else { res = ""; } $(this).css("width",w+"px").prepend(res); var hdcol = ""; if( ts.p.colModel[j].hidden ) { $(this).css("display","none"); hdcol = "display:none;"; } firstr += "<td role='gridcell' style='height:0px;width:"+w+"px;"+hdcol+"'></td>"; grid.headers[j] = { width: w, el: this }; sort = ts.p.colModel[j].sortable; if( typeof sort !== 'boolean') {ts.p.colModel[j].sortable = true; sort=true;} var nm = ts.p.colModel[j].name; if( !(nm == 'cb' || nm=='subgrid' || nm=='rn') ) { if(ts.p.viewsortcols[2]){ $("div",this).addClass('ui-jqgrid-sortable'); } } if(sort) { if(ts.p.viewsortcols[0]) {$("div span.s-ico",this).show(); if(j==ts.p.lastsort){ $("div span.ui-icon-"+ts.p.sortorder,this).removeClass("ui-state-disabled");}} else if( j == ts.p.lastsort) {$("div span.s-ico",this).show();$("div span.ui-icon-"+ts.p.sortorder,this).removeClass("ui-state-disabled");} } if(ts.p.footerrow) { tfoot += "<td role='gridcell' "+formatCol(j,0,'')+">&#160;</td>"; } }).mousedown(function(e) { if ($(e.target).closest("th>span.ui-jqgrid-resize").length != 1) { return; } var ci = $.jgrid.getCellIndex(this); if(ts.p.forceFit===true) {ts.p.nv= nextVisible(ci);} grid.dragStart(ci, e, getOffset(ci)); return false; }).click(function(e) { if (ts.p.disableClick) { ts.p.disableClick = false; return false; } var s = "th>div.ui-jqgrid-sortable",r,d; if (!ts.p.viewsortcols[2]) { s = "th>div>span>span.ui-grid-ico-sort"; } var t = $(e.target).closest(s); if (t.length != 1) { return; } var ci = $.jgrid.getCellIndex(this); if (!ts.p.viewsortcols[2]) { r=true;d=t.attr("sort"); } sortData($('div',this)[0].id,ci,r,d); return false; }); if (ts.p.sortable && $.fn.sortable) { try { $(ts).jqGrid("sortableColumns", thr); } catch (e){} } if(ts.p.footerrow) { tfoot += "</tr></tbody></table>"; } firstr += "</tr>"; tbody = document.createElement("tbody"); this.appendChild(tbody); $(this).addClass('ui-jqgrid-btable').append(firstr); firstr = null; var hTable = $("<table class='ui-jqgrid-htable' style='width:"+ts.p.tblwidth+"px' role='grid' aria-labelledby='gbox_"+this.id+"' cellspacing='0' cellpadding='0' border='0'></table>").append(thead), hg = (ts.p.caption && ts.p.hiddengrid===true) ? true : false, hb = $("<div class='ui-jqgrid-hbox" + (dir=="rtl" ? "-rtl" : "" )+"'></div>"); thead = null; grid.hDiv = document.createElement("div"); $(grid.hDiv) .css({ width: grid.width+"px"}) .addClass("ui-state-default ui-jqgrid-hdiv") .append(hb); $(hb).append(hTable); hTable = null; if(hg) { $(grid.hDiv).hide(); } if(ts.p.pager){ if(typeof ts.p.pager == "string") {if(ts.p.pager.substr(0,1) !="#") { ts.p.pager = "#"+ts.p.pager;} } else { ts.p.pager = "#"+ $(ts.p.pager).attr("id");} $(ts.p.pager).css({width: grid.width+"px"}).appendTo(eg).addClass('ui-state-default ui-jqgrid-pager ui-corner-bottom'); if(hg) {$(ts.p.pager).hide();} setPager(ts.p.pager,''); } if( ts.p.cellEdit === false && ts.p.hoverrows === true) { $(ts).bind('mouseover',function(e) { ptr = $(e.target).closest("tr.jqgrow"); if($(ptr).attr("class") !== "subgrid") { $(ptr).addClass("ui-state-hover"); } return false; }).bind('mouseout',function(e) { ptr = $(e.target).closest("tr.jqgrow"); $(ptr).removeClass("ui-state-hover"); return false; }); } var ri,ci; $(ts).before(grid.hDiv).click(function(e) { td = e.target; var scb = $(td).hasClass("cbox"); ptr = $(td,ts.rows).closest("tr.jqgrow"); if($(ptr).length === 0 ) { return this; } var cSel = true; if($.isFunction(ts.p.beforeSelectRow)) { cSel = ts.p.beforeSelectRow.call(ts,ptr[0].id, e); } if (td.tagName == 'A' || ((td.tagName == 'INPUT' || td.tagName == 'TEXTAREA' || td.tagName == 'OPTION' || td.tagName == 'SELECT' ) && !scb) ) { return this; } if(cSel === true) { if(ts.p.cellEdit === true) { if(ts.p.multiselect && scb){ $(ts).jqGrid("setSelection",ptr[0].id,true); } else { ri = ptr[0].rowIndex; ci = $.jgrid.getCellIndex(td); try {$(ts).jqGrid("editCell",ri,ci,true);} catch (_) {} } } else if ( !ts.p.multikey ) { if(ts.p.multiselect && ts.p.multiboxonly) { if(scb){$(ts).jqGrid("setSelection",ptr[0].id,true);} else { $(ts.p.selarrrow).each(function(i,n){ var ind = ts.rows.namedItem(n); $(ind).removeClass("ui-state-highlight"); $("#jqg_"+ts.p.id+"_"+$.jgrid.jqID(n)).attr("checked",false); }); ts.p.selarrrow = []; $("#cb_"+$.jgrid.jqID(ts.p.id),ts.grid.hDiv).attr("checked",false); $(ts).jqGrid("setSelection",ptr[0].id,true); } } else { $(ts).jqGrid("setSelection",ptr[0].id,true); } } else { if(e[ts.p.multikey]) { $(ts).jqGrid("setSelection",ptr[0].id,true); } else if(ts.p.multiselect && scb) { scb = $("[id^=jqg_"+ts.p.id+"_"+"]").attr("checked"); $("[id^=jqg_"+ts.p.id+"_"+"]").attr("checked",!scb); } } if($.isFunction(ts.p.onCellSelect)) { ri = ptr[0].id; ci = $.jgrid.getCellIndex(td); ts.p.onCellSelect.call(ts,ri,ci,$(td).html(),e); } e.stopPropagation(); } else { return this; } }).bind('reloadGrid', function(e,opts) { if(ts.p.treeGrid ===true) { ts.p.datatype = ts.p.treedatatype;} if (opts && opts.current) { ts.grid.selectionPreserver(ts); } if(ts.p.datatype=="local"){ $(ts).jqGrid("resetSelection"); if(ts.p.data.length) { refreshIndex();} } else if(!ts.p.treeGrid) { ts.p.selrow=null; if(ts.p.multiselect) {ts.p.selarrrow =[];$('#cb_'+$.jgrid.jqID(ts.p.id),ts.grid.hDiv).attr("checked",false);} ts.p.savedRow = []; } if(ts.p.scroll) {emptyRows(ts.grid.bDiv,true);} if (opts && opts.page) { var page = opts.page; if (page > ts.p.lastpage) { page = ts.p.lastpage; } if (page < 1) { page = 1; } ts.p.page = page; if (ts.grid.prevRowHeight) { ts.grid.bDiv.scrollTop = (page - 1) * ts.grid.prevRowHeight * ts.p.rowNum; } else { ts.grid.bDiv.scrollTop = 0; } } if (ts.grid.prevRowHeight && ts.p.scroll) { delete ts.p.lastpage; ts.grid.populateVisible(); } else { ts.grid.populate(); } return false; }); if( $.isFunction(this.p.ondblClickRow) ) { $(this).dblclick(function(e) { td = e.target; ptr = $(td,ts.rows).closest("tr.jqgrow"); if($(ptr).length === 0 ){return false;} ri = ptr[0].rowIndex; ci = $.jgrid.getCellIndex(td); ts.p.ondblClickRow.call(ts,$(ptr).attr("id"),ri,ci, e); return false; }); } if ($.isFunction(this.p.onRightClickRow)) { $(this).bind('contextmenu', function(e) { td = e.target; ptr = $(td,ts.rows).closest("tr.jqgrow"); if($(ptr).length === 0 ){return false;} if(!ts.p.multiselect) { $(ts).jqGrid("setSelection",ptr[0].id,true); } ri = ptr[0].rowIndex; ci = $.jgrid.getCellIndex(td); ts.p.onRightClickRow.call(ts,$(ptr).attr("id"),ri,ci, e); return false; }); } grid.bDiv = document.createElement("div"); $(grid.bDiv) .append($('<div style="position:relative;'+(isMSIE && $.browser.version < 8 ? "height:0.01%;" : "")+'"></div>').append('<div></div>').append(this)) .addClass("ui-jqgrid-bdiv") .css({ height: ts.p.height+(isNaN(ts.p.height)?"":"px"), width: (grid.width)+"px"}) .scroll(grid.scrollGrid); $("table:first",grid.bDiv).css({width:ts.p.tblwidth+"px"}); if( isMSIE ) { if( $("tbody",this).size() == 2 ) { $("tbody:gt(0)",this).remove();} if( ts.p.multikey) {$(grid.bDiv).bind("selectstart",function(){return false;});} } else { if( ts.p.multikey) {$(grid.bDiv).bind("mousedown",function(){return false;});} } if(hg) {$(grid.bDiv).hide();} grid.cDiv = document.createElement("div"); var arf = ts.p.hidegrid===true ? $("<a role='link' href='javascript:void(0)'/>").addClass('ui-jqgrid-titlebar-close HeaderButton').hover( function(){ arf.addClass('ui-state-hover');}, function() {arf.removeClass('ui-state-hover');}) .append("<span class='ui-icon ui-icon-circle-triangle-n'></span>").css((dir=="rtl"?"left":"right"),"0px") : ""; $(grid.cDiv).append(arf).append("<span class='ui-jqgrid-title"+(dir=="rtl" ? "-rtl" :"" )+"'>"+ts.p.caption+"</span>") .addClass("ui-jqgrid-titlebar ui-widget-header ui-corner-top ui-helper-clearfix"); $(grid.cDiv).insertBefore(grid.hDiv); if( ts.p.toolbar[0] ) { grid.uDiv = document.createElement("div"); if(ts.p.toolbar[1] == "top") {$(grid.uDiv).insertBefore(grid.hDiv);} else if (ts.p.toolbar[1]=="bottom" ) {$(grid.uDiv).insertAfter(grid.hDiv);} if(ts.p.toolbar[1]=="both") { grid.ubDiv = document.createElement("div"); $(grid.uDiv).insertBefore(grid.hDiv).addClass("ui-userdata ui-state-default").attr("id","t_"+this.id); $(grid.ubDiv).insertAfter(grid.hDiv).addClass("ui-userdata ui-state-default").attr("id","tb_"+this.id); if(hg) {$(grid.ubDiv).hide();} } else { $(grid.uDiv).width(grid.width).addClass("ui-userdata ui-state-default").attr("id","t_"+this.id); } if(hg) {$(grid.uDiv).hide();} } if(ts.p.toppager) { ts.p.toppager = ts.p.id+"_toppager"; grid.topDiv = $("<div id='"+ts.p.toppager+"'></div>")[0]; ts.p.toppager = "#"+ts.p.toppager; $(grid.topDiv).insertBefore(grid.hDiv).addClass('ui-state-default ui-jqgrid-toppager').width(grid.width); setPager(ts.p.toppager,'_t'); } if(ts.p.footerrow) { grid.sDiv = $("<div class='ui-jqgrid-sdiv'></div>")[0]; hb = $("<div class='ui-jqgrid-hbox"+(dir=="rtl"?"-rtl":"")+"'></div>"); $(grid.sDiv).append(hb).insertAfter(grid.hDiv).width(grid.width); $(hb).append(tfoot); grid.footers = $(".ui-jqgrid-ftable",grid.sDiv)[0].rows[0].cells; if(ts.p.rownumbers) { grid.footers[0].className = 'ui-state-default jqgrid-rownum'; } if(hg) {$(grid.sDiv).hide();} } hb = null; if(ts.p.caption) { var tdt = ts.p.datatype; if(ts.p.hidegrid===true) { $(".ui-jqgrid-titlebar-close",grid.cDiv).click( function(e){ var onHdCl = $.isFunction(ts.p.onHeaderClick), elems = ".ui-jqgrid-bdiv, .ui-jqgrid-hdiv, .ui-jqgrid-pager, .ui-jqgrid-sdiv", counter, self = this; if(ts.p.toolbar[0]===true) { if( ts.p.toolbar[1]=='both') { elems += ', #' + $(grid.ubDiv).attr('id'); } elems += ', #' + $(grid.uDiv).attr('id'); } counter = $(elems,"#gview_"+ts.p.id).length; if(ts.p.gridstate == 'visible') { $(elems,"#gbox_"+ts.p.id).slideUp("fast", function() { counter--; if (counter == 0) { $("span",self).removeClass("ui-icon-circle-triangle-n").addClass("ui-icon-circle-triangle-s"); ts.p.gridstate = 'hidden'; if($("#gbox_"+ts.p.id).hasClass("ui-resizable")) { $(".ui-resizable-handle","#gbox_"+ts.p.id).hide(); } if(onHdCl) {if(!hg) {ts.p.onHeaderClick.call(ts,ts.p.gridstate,e);}} } }); } else if(ts.p.gridstate == 'hidden'){ $(elems,"#gbox_"+ts.p.id).slideDown("fast", function() { counter--; if (counter == 0) { $("span",self).removeClass("ui-icon-circle-triangle-s").addClass("ui-icon-circle-triangle-n"); if(hg) {ts.p.datatype = tdt;populate();hg=false;} ts.p.gridstate = 'visible'; if($("#gbox_"+ts.p.id).hasClass("ui-resizable")) { $(".ui-resizable-handle","#gbox_"+ts.p.id).show(); } if(onHdCl) {if(!hg) {ts.p.onHeaderClick.call(ts,ts.p.gridstate,e);}} } }); } return false; }); if(hg) {ts.p.datatype="local"; $(".ui-jqgrid-titlebar-close",grid.cDiv).trigger("click");} } } else {$(grid.cDiv).hide();} $(grid.hDiv).after(grid.bDiv) .mousemove(function (e) { if(grid.resizing){grid.dragMove(e);return false;} }); $(".ui-jqgrid-labels",grid.hDiv).bind("selectstart", function () { return false; }); $(document).mouseup(function (e) { if(grid.resizing) { grid.dragEnd(); return false;} return true; }); ts.formatCol = formatCol; ts.sortData = sortData; ts.updatepager = updatepager; ts.refreshIndex = refreshIndex; ts.formatter = function ( rowId, cellval , colpos, rwdat, act){return formatter(rowId, cellval , colpos, rwdat, act);}; $.extend(grid,{populate : populate, emptyRows: emptyRows}); this.grid = grid; ts.addXmlData = function(d) {addXmlData(d,ts.grid.bDiv);}; ts.addJSONData = function(d) {addJSONData(d,ts.grid.bDiv);}; this.grid.cols = this.rows[0].cells; populate();ts.p.hiddengrid=false; $(window).unload(function () { ts = null; }); }); }; $.jgrid.extend({ getGridParam : function(pName) { var $t = this[0]; if (!$t || !$t.grid) {return;} if (!pName) { return $t.p; } else {return typeof($t.p[pName]) != "undefined" ? $t.p[pName] : null;} }, setGridParam : function (newParams){ return this.each(function(){ if (this.grid && typeof(newParams) === 'object') {$.extend(true,this.p,newParams);} }); }, getDataIDs : function () { var ids=[], i=0, len, j=0; this.each(function(){ len = this.rows.length; if(len && len>0){ while(i<len) { if($(this.rows[i]).hasClass('jqgrow')) { ids[j] = this.rows[i].id; j++; } i++; } } }); return ids; }, setSelection : function(selection,onsr) { return this.each(function(){ var $t = this, stat,pt, ner, ia, tpsr; if(selection === undefined) { return; } onsr = onsr === false ? false : true; pt=$t.rows.namedItem(selection+""); if(!pt) { return; } function scrGrid(iR){ var ch = $($t.grid.bDiv)[0].clientHeight, st = $($t.grid.bDiv)[0].scrollTop, rpos = $t.rows[iR].offsetTop, rh = $t.rows[iR].clientHeight; if(rpos+rh >= ch+st) { $($t.grid.bDiv)[0].scrollTop = rpos-(ch+st)+rh+st; } else if(rpos < ch+st) { if(rpos < st) { $($t.grid.bDiv)[0].scrollTop = rpos; } } } if($t.p.scrollrows===true) { ner = $t.rows.namedItem(selection).rowIndex; if(ner >=0 ){ scrGrid(ner); } } if(!$t.p.multiselect) { if(pt.className !== "ui-subgrid") { if( $t.p.selrow ) { $($t.rows.namedItem($t.p.selrow)).removeClass("ui-state-highlight").attr("aria-selected","false"); } if( $t.p.selrow != pt.id) { $t.p.selrow = pt.id; $(pt).addClass("ui-state-highlight").attr("aria-selected","true"); if( $t.p.onSelectRow && onsr) { $t.p.onSelectRow.call($t,$t.p.selrow, true); } } else {$t.p.selrow = null;} } } else { $t.p.selrow = pt.id; ia = $.inArray($t.p.selrow,$t.p.selarrrow); if ( ia === -1 ){ if(pt.className !== "ui-subgrid") { $(pt).addClass("ui-state-highlight").attr("aria-selected","true");} stat = true; $("#jqg_"+$t.p.id+"_"+$.jgrid.jqID($t.p.selrow)).attr("checked",stat); $t.p.selarrrow.push($t.p.selrow); if( $t.p.onSelectRow && onsr) { $t.p.onSelectRow.call($t,$t.p.selrow, stat); } } else { if(pt.className !== "ui-subgrid") { $(pt).removeClass("ui-state-highlight").attr("aria-selected","false");} stat = false; $("#jqg_"+$t.p.id+"_"+$.jgrid.jqID($t.p.selrow)).attr("checked",stat); $t.p.selarrrow.splice(ia,1); if( $t.p.onSelectRow && onsr) { $t.p.onSelectRow.call($t,$t.p.selrow, stat); } tpsr = $t.p.selarrrow[0]; $t.p.selrow = (tpsr === undefined) ? null : tpsr; } } }); }, resetSelection : function(){ return this.each(function(){ var t = this, ind; if(!t.p.multiselect) { if(t.p.selrow) { $("#"+t.p.id+" tbody:first tr#"+$.jgrid.jqID(t.p.selrow)).removeClass("ui-state-highlight").attr("aria-selected","false"); t.p.selrow = null; } } else { $(t.p.selarrrow).each(function(i,n){ ind = t.rows.namedItem(n); $(ind).removeClass("ui-state-highlight").attr("aria-selected","false"); $("#jqg_"+t.p.id+"_"+$.jgrid.jqID(n)).attr("checked",false); }); $("#cb_"+$.jgrid.jqID(t.p.id)).attr("checked",false); t.p.selarrrow = []; } t.p.savedRow = []; }); }, getRowData : function( rowid ) { var res = {}, resall, getall=false, len, j=0; this.each(function(){ var $t = this,nm,ind; if(typeof(rowid) == 'undefined') { getall = true; resall = []; len = $t.rows.length; } else { ind = $t.rows.namedItem(rowid); if(!ind) { return res; } len = 2; } while(j<len){ if(getall) { ind = $t.rows[j]; } if( $(ind).hasClass('jqgrow') ) { $('td',ind).each( function(i) { nm = $t.p.colModel[i].name; if ( nm !== 'cb' && nm !== 'subgrid' && nm !== 'rn') { if($t.p.treeGrid===true && nm == $t.p.ExpandColumn) { res[nm] = $.jgrid.htmlDecode($("span:first",this).html()); } else { try { res[nm] = $.unformat(this,{rowId:ind.id, colModel:$t.p.colModel[i]},i); } catch (e){ res[nm] = $.jgrid.htmlDecode($(this).html()); } } } }); if(getall) { resall.push(res); res={}; } } j++; } }); return resall ? resall: res; }, delRowData : function(rowid) { var success = false, rowInd, ia, ri; this.each(function() { var $t = this; rowInd = $t.rows.namedItem(rowid); if(!rowInd) {return false;} else { ri = rowInd.rowIndex; $(rowInd).remove(); $t.p.records--; $t.p.reccount--; $t.updatepager(true,false); success=true; if($t.p.multiselect) { ia = $.inArray(rowid,$t.p.selarrrow); if(ia != -1) { $t.p.selarrrow.splice(ia,1);} } if(rowid == $t.p.selrow) {$t.p.selrow=null;} } if($t.p.datatype == 'local') { var pos = $t.p._index[rowid]; if(typeof(pos) != 'undefined') { $t.p.data.splice(pos,1); $t.refreshIndex(); } } if( $t.p.altRows === true && success ) { var cn = $t.p.altclass; $($t.rows).each(function(i){ if(i % 2 ==1) { $(this).addClass(cn); } else { $(this).removeClass(cn); } }); } }); return success; }, setRowData : function(rowid, data, cssp) { var nm, success=true, title; this.each(function(){ if(!this.grid) {return false;} var t = this, vl, ind, cp = typeof cssp, lcdata={}; ind = t.rows.namedItem(rowid); if(!ind) { return false; } if( data ) { try { $(this.p.colModel).each(function(i){ nm = this.name; if( data[nm] !== undefined) { lcdata[nm] = this.formatter && typeof(this.formatter) === 'string' && this.formatter == 'date' ? $.unformat.date(data[nm],this) : data[nm]; vl = t.formatter( rowid, data[nm], i, data, 'edit'); title = this.title ? {"title":$.jgrid.stripHtml(vl)} : {}; if(t.p.treeGrid===true && nm == t.p.ExpandColumn) { $("td:eq("+i+") > span:first",ind).html(vl).attr(title); } else { $("td:eq("+i+")",ind).html(vl).attr(title); } } }); if(t.p.datatype == 'local') { var pos = t.p._index[rowid]; if(typeof(pos) != 'undefined') { t.p.data[pos] = $.extend(true, t.p.data[pos], lcdata); } lcdata = null; } } catch (e) { success = false; } } if(success) { if(cp === 'string') {$(ind).addClass(cssp);} else if(cp === 'object') {$(ind).css(cssp);} } }); return success; }, addRowData : function(rowid,rdata,pos,src) { if(!pos) {pos = "last";} var success = false, nm, row, gi, si, ni,sind, i, v, prp="", aradd, cnm, cn, data, cm; if(rdata) { if($.isArray(rdata)) { aradd=true; pos = "last"; cnm = rowid; } else { rdata = [rdata]; aradd = false; } this.each(function() { var t = this, datalen = rdata.length; ni = t.p.rownumbers===true ? 1 :0; gi = t.p.multiselect ===true ? 1 :0; si = t.p.subGrid===true ? 1 :0; if(!aradd) { if(typeof(rowid) != 'undefined') { rowid = rowid+"";} else { rowid = (t.p.records+1)+""; if(t.p.keyIndex !== false) { cnm = t.p.colModel[t.p.keyIndex+gi+si+ni].name; if(typeof rdata[0][cnm] != "undefined") { rowid = rdata[0][cnm]; } } } } cn = t.p.altclass; var k = 0, cna ="", lcdata = {}, air = $.isFunction(t.p.afterInsertRow) ? true : false; while(k < datalen) { data = rdata[k]; row=""; if(aradd) { try {rowid = data[cnm];} catch (e) {rowid = (t.p.records+1)+"";} cna = t.p.altRows === true ? (t.rows.length-1)%2 === 0 ? cn : "" : ""; } if(ni){ prp = t.formatCol(0,1,''); row += "<td role=\"gridcell\" aria-describedby=\""+t.p.id+"_rn\" class=\"ui-state-default jqgrid-rownum\" "+prp+">0</td>"; } if(gi) { v = "<input role=\"checkbox\" type=\"checkbox\""+" id=\"jqg_"+t.p.id+"_"+rowid+"\" class=\"cbox\"/>"; prp = t.formatCol(ni,1,''); row += "<td role=\"gridcell\" aria-describedby=\""+t.p.id+"_cb\" "+prp+">"+v+"</td>"; } if(si) { row += $(t).jqGrid("addSubGridCell",gi+ni,1); } for(i = gi+si+ni; i < t.p.colModel.length;i++){ cm = t.p.colModel[i]; nm = cm.name; lcdata[nm] = cm.formatter && typeof(cm.formatter) === 'string' && cm.formatter == 'date' ? $.unformat.date(data[nm],cm) : data[nm]; v = t.formatter( rowid, $.jgrid.getAccessor(data,nm), i, data, 'edit'); prp = t.formatCol(i,1,v); row += "<td role=\"gridcell\" aria-describedby=\""+t.p.id+"_"+nm+"\" "+prp+">"+v+"</td>"; } row = "<tr id=\""+rowid+"\" role=\"row\" class=\"ui-widget-content jqgrow ui-row-"+t.p.direction+" "+cna+"\">" + row+"</tr>"; if(t.p.subGrid===true) { row = $(row)[0]; $(t).jqGrid("addSubGrid",row,gi+ni); } if(t.rows.length === 0){ $("table:first",t.grid.bDiv).append(row); } else { switch (pos) { case 'last': $(t.rows[t.rows.length-1]).after(row); break; case 'first': $(t.rows[0]).after(row); break; case 'after': sind = t.rows.namedItem(src); if (sind) { if($(t.rows[sind.rowIndex+1]).hasClass("ui-subgrid")) { $(t.rows[sind.rowIndex+1]).after(row); } else { $(sind).after(row); } } break; case 'before': sind = t.rows.namedItem(src); if(sind) {$(sind).before(row);sind=sind.rowIndex;} break; } } t.p.records++; t.p.reccount++; if(air) { t.p.afterInsertRow.call(t,rowid,data,data); } k++; if(t.p.datatype == 'local') { t.p._index[rowid] = t.p.data.length; t.p.data.push(lcdata); lcdata = {}; } } if( t.p.altRows === true && !aradd) { if (pos == "last") { if ((t.rows.length-1)%2 == 1) {$(t.rows[t.rows.length-1]).addClass(cn);} } else { $(t.rows).each(function(i){ if(i % 2 ==1) { $(this).addClass(cn); } else { $(this).removeClass(cn); } }); } } t.updatepager(true,true); success = true; }); } return success; }, footerData : function(action,data, format) { var nm, success=false, res={}, title; function isEmpty(obj) { for(var i in obj) { if (obj.hasOwnProperty(i)) { return false; } } return true; } if(typeof(action) == "undefined") { action = "get"; } if(typeof(format) != "boolean") { format = true; } action = action.toLowerCase(); this.each(function(){ var t = this, vl; if(!t.grid || !t.p.footerrow) {return false;} if(action == "set") { if(isEmpty(data)) { return false; } } success=true; $(this.p.colModel).each(function(i){ nm = this.name; if(action == "set") { if( data[nm] !== undefined) { vl = format ? t.formatter( "", data[nm], i, data, 'edit') : data[nm]; title = this.title ? {"title":$.jgrid.stripHtml(vl)} : {}; $("tr.footrow td:eq("+i+")",t.grid.sDiv).html(vl).attr(title); success = true; } } else if(action == "get") { res[nm] = $("tr.footrow td:eq("+i+")",t.grid.sDiv).html(); } }); }); return action == "get" ? res : success; }, ShowHideCol : function(colname,show) { return this.each(function() { var $t = this, fndh=false; if (!$t.grid ) {return;} if( typeof colname === 'string') {colname=[colname];} show = show != "none" ? "" : "none"; var sw = show === "" ? true :false; $(this.p.colModel).each(function(i) { if ($.inArray(this.name,colname) !== -1 && this.hidden === sw) { $("tr",$t.grid.hDiv).each(function(){ $("th:eq("+i+")",this).css("display",show); }); $($t.rows).each(function(j){ $("td:eq("+i+")",$t.rows[j]).css("display",show); }); if($t.p.footerrow) { $("td:eq("+i+")",$t.grid.sDiv).css("display", show); } if(show == "none") { $t.p.tblwidth -= this.width+$t.p.cellLayout;} else {$t.p.tblwidth += this.width;} this.hidden = !sw; fndh=true; } }); if(fndh===true) { $("table:first",$t.grid.hDiv).width($t.p.tblwidth); $("table:first",$t.grid.bDiv).width($t.p.tblwidth); $t.grid.hDiv.scrollLeft = $t.grid.bDiv.scrollLeft; if($t.p.footerrow) { $("table:first",$t.grid.sDiv).width($t.p.tblwidth); $t.grid.sDiv.scrollLeft = $t.grid.bDiv.scrollLeft; } if($t.p.shrinkToFit===true) { $($t).jqGrid("setGridWidth",$t.grid.width-0.001,true); } } }); }, hideCol : function (colname) { return this.each(function(){$(this).jqGrid("ShowHideCol",colname,"none");}); }, showCol : function(colname) { return this.each(function(){$(this).jqGrid("ShowHideCol",colname,"");}); }, remapColumns : function(permutation, updateCells, keepHeader) { function resortArray(a) { var ac; if (a.length) { ac = $.makeArray(a); } else { ac = $.extend({}, a); } $.each(permutation, function(i) { a[i] = ac[this]; }); } var ts = this.get(0); function resortRows(parent, clobj) { $(">tr"+(clobj||""), parent).each(function() { var row = this; var elems = $.makeArray(row.cells); $.each(permutation, function() { var e = elems[this]; if (e) { row.appendChild(e); } }); }); } resortArray(ts.p.colModel); resortArray(ts.p.colNames); resortArray(ts.grid.headers); resortRows($("thead:first", ts.grid.hDiv), keepHeader && ":not(.ui-jqgrid-labels)"); if (updateCells) { resortRows($("#"+ts.p.id+" tbody:first"), ".jqgfirstrow, tr.jqgrow, tr.jqfoot"); } if (ts.p.footerrow) { resortRows($("tbody:first", ts.grid.sDiv)); } if (ts.p.remapColumns) { if (!ts.p.remapColumns.length){ ts.p.remapColumns = $.makeArray(permutation); } else { resortArray(ts.p.remapColumns); } } ts.p.lastsort = $.inArray(ts.p.lastsort, permutation); if(ts.p.treeGrid) { ts.p.expColInd = $.inArray(ts.p.expColInd, permutation); } }, setGridWidth : function(nwidth, shrink) { return this.each(function(){ if (!this.grid ) {return;} var $t = this, cw, initwidth = 0, brd=$t.p.cellLayout, lvc, vc=0, hs=false, scw=$t.p.scrollOffset, aw, gw=0, tw=0, cl = 0,cr; if(typeof shrink != 'boolean') { shrink=$t.p.shrinkToFit; } if(isNaN(nwidth)) {return;} else { nwidth = parseInt(nwidth,10); $t.grid.width = $t.p.width = nwidth;} $("#gbox_"+$t.p.id).css("width",nwidth+"px"); $("#gview_"+$t.p.id).css("width",nwidth+"px"); $($t.grid.bDiv).css("width",nwidth+"px"); $($t.grid.hDiv).css("width",nwidth+"px"); if($t.p.pager ) {$($t.p.pager).css("width",nwidth+"px");} if($t.p.toppager ) {$($t.p.toppager).css("width",nwidth+"px");} if($t.p.toolbar[0] === true){ $($t.grid.uDiv).css("width",nwidth+"px"); if($t.p.toolbar[1]=="both") {$($t.grid.ubDiv).css("width",nwidth+"px");} } if($t.p.footerrow) { $($t.grid.sDiv).css("width",nwidth+"px"); } if(shrink ===false && $t.p.forceFit === true) {$t.p.forceFit=false;} if(shrink===true) { if ($.browser.safari) { brd=0;} $.each($t.p.colModel, function(i) { if(this.hidden===false){ initwidth += parseInt(this.width,10); if(this.fixed) { tw += this.width; gw += this.width+brd; } else { vc++; } cl++; } }); if(vc === 0) { return; } $t.p.tblwidth = initwidth; aw = nwidth-brd*vc-gw; if(!isNaN($t.p.height)) { if($($t.grid.bDiv)[0].clientHeight < $($t.grid.bDiv)[0].scrollHeight || $t.rows.length === 1){ hs = true; aw -= scw; } } initwidth =0; var cle = $t.grid.cols.length >0; $.each($t.p.colModel, function(i) { if(this.hidden === false && !this.fixed){ cw = Math.round(aw*this.width/($t.p.tblwidth-tw)); if (cw < 0) { return; } this.width =cw; initwidth += cw; $t.grid.headers[i].width=cw; $t.grid.headers[i].el.style.width=cw+"px"; if($t.p.footerrow) { $t.grid.footers[i].style.width = cw+"px"; } if(cle) { $t.grid.cols[i].style.width = cw+"px"; } lvc = i; } }); cr =0; if (hs) { if(nwidth-gw-(initwidth+brd*vc) !== scw){ cr = nwidth-gw-(initwidth+brd*vc)-scw; } } else if( Math.abs(nwidth-gw-(initwidth+brd*vc)) !== 1) { cr = nwidth-gw-(initwidth+brd*vc); } $t.p.colModel[lvc].width += cr; $t.p.tblwidth = initwidth+cr+tw+brd*cl; if($t.p.tblwidth > nwidth) { var delta = $t.p.tblwidth - parseInt(nwidth,10); $t.p.tblwidth = nwidth; cw = $t.p.colModel[lvc].width = $t.p.colModel[lvc].width-delta; } else { cw= $t.p.colModel[lvc].width; } $t.grid.headers[lvc].width = cw; $t.grid.headers[lvc].el.style.width=cw+"px"; if(cle) { $t.grid.cols[lvc].style.width = cw+"px"; } $('table:first',$t.grid.bDiv).css("width",$t.p.tblwidth+"px"); $('table:first',$t.grid.hDiv).css("width",$t.p.tblwidth+"px"); $t.grid.hDiv.scrollLeft = $t.grid.bDiv.scrollLeft; if($t.p.footerrow) { $t.grid.footers[lvc].style.width = cw+"px"; $('table:first',$t.grid.sDiv).css("width",$t.p.tblwidth+"px"); } } }); }, setGridHeight : function (nh) { return this.each(function (){ var $t = this; if(!$t.grid) {return;} $($t.grid.bDiv).css({height: nh+(isNaN(nh)?"":"px")}); $t.p.height = nh; if ($t.p.scroll) { $t.grid.populateVisible(); } }); }, setCaption : function (newcap){ return this.each(function(){ this.p.caption=newcap; $("span.ui-jqgrid-title",this.grid.cDiv).html(newcap); $(this.grid.cDiv).show(); }); }, setLabel : function(colname, nData, prop, attrp ){ return this.each(function(){ var $t = this, pos=-1; if(!$t.grid) {return;} if(isNaN(colname)) { $($t.p.colModel).each(function(i){ if (this.name == colname) { pos = i;return false; } }); } else {pos = parseInt(colname,10);} if(pos>=0) { var thecol = $("tr.ui-jqgrid-labels th:eq("+pos+")",$t.grid.hDiv); if (nData){ var ico = $(".s-ico",thecol); $("[id^=jqgh_]",thecol).empty().html(nData).append(ico); $t.p.colNames[pos] = nData; } if (prop) { if(typeof prop === 'string') {$(thecol).addClass(prop);} else {$(thecol).css(prop);} } if(typeof attrp === 'object') {$(thecol).attr(attrp);} } }); }, setCell : function(rowid,colname,nData,cssp,attrp, forceupd) { return this.each(function(){ var $t = this, pos =-1,v, title; if(!$t.grid) {return;} if(isNaN(colname)) { $($t.p.colModel).each(function(i){ if (this.name == colname) { pos = i;return false; } }); } else {pos = parseInt(colname,10);} if(pos>=0) { var ind = $t.rows.namedItem(rowid); if (ind){ var tcell = $("td:eq("+pos+")",ind); if(nData !== "" || forceupd === true) { v = $t.formatter(rowid, nData, pos,ind,'edit'); title = $t.p.colModel[pos].title ? {"title":$.jgrid.stripHtml(v)} : {}; if($t.p.treeGrid && $(".tree-wrap",$(tcell)).length>0) { $("span",$(tcell)).html(v).attr(title); } else { $(tcell).html(v).attr(title); } if($t.p.datatype == "local") { var cm = $t.p.colModel[pos], index; nData = cm.formatter && typeof(cm.formatter) === 'string' && cm.formatter == 'date' ? $.unformat.date(nData,cm) : nData; index = $t.p._index[rowid]; if(typeof index != "undefined") { $t.p.data[index][cm.name] = nData; } } } if(typeof cssp === 'string'){ $(tcell).addClass(cssp); } else if(cssp) { $(tcell).css(cssp); } if(typeof attrp === 'object') {$(tcell).attr(attrp);} } } }); }, getCell : function(rowid,col) { var ret = false; this.each(function(){ var $t=this, pos=-1; if(!$t.grid) {return;} if(isNaN(col)) { $($t.p.colModel).each(function(i){ if (this.name === col) { pos = i;return false; } }); } else {pos = parseInt(col,10);} if(pos>=0) { var ind = $t.rows.namedItem(rowid); if(ind) { try { ret = $.unformat($("td:eq("+pos+")",ind),{rowId:ind.id, colModel:$t.p.colModel[pos]},pos); } catch (e){ ret = $.jgrid.htmlDecode($("td:eq("+pos+")",ind).html()); } } } }); return ret; }, getCol : function (col, obj, mathopr) { var ret = [], val, sum=0; obj = typeof (obj) != 'boolean' ? false : obj; if(typeof mathopr == 'undefined') { mathopr = false; } this.each(function(){ var $t=this, pos=-1; if(!$t.grid) {return;} if(isNaN(col)) { $($t.p.colModel).each(function(i){ if (this.name === col) { pos = i;return false; } }); } else {pos = parseInt(col,10);} if(pos>=0) { var ln = $t.rows.length, i =0; if (ln && ln>0){ while(i<ln){ if($($t.rows[i]).hasClass('jqgrow')) { try { val = $.unformat($($t.rows[i].cells[pos]),{rowId:$t.rows[i].id, colModel:$t.p.colModel[pos]},pos); } catch (e) { val = $.jgrid.htmlDecode($t.rows[i].cells[pos].innerHTML); } if(mathopr) { sum += parseFloat(val); } else if(obj) { ret.push({id:$t.rows[i].id,value:val}); } else { ret[i]=val; } } i++; } if(mathopr) { switch(mathopr.toLowerCase()){ case 'sum': ret =sum; break; case 'avg': ret = sum/ln; break; case 'count': ret = ln; break; } } } } }); return ret; }, clearGridData : function(clearfooter) { return this.each(function(){ var $t = this; if(!$t.grid) {return;} if(typeof clearfooter != 'boolean') { clearfooter = false; } if($t.p.deepempty) {$("#"+$t.p.id+" tbody:first tr:gt(0)").remove();} else { var trf = $("#"+$t.p.id+" tbody:first tr:first")[0]; $("#"+$t.p.id+" tbody:first").empty().append(trf); } if($t.p.footerrow && clearfooter) { $(".ui-jqgrid-ftable td",$t.grid.sDiv).html("&#160;"); } $t.p.selrow = null; $t.p.selarrrow= []; $t.p.savedRow = []; $t.p.records = 0;$t.p.page=1;$t.p.lastpage=0;$t.p.reccount=0; $t.p.data = []; $t.p_index = {}; $t.updatepager(true,false); }); }, getInd : function(rowid,rc){ var ret =false,rw; this.each(function(){ rw = this.rows.namedItem(rowid); if(rw) { ret = rc===true ? rw: rw.rowIndex; } }); return ret; } }); })(jQuery);
JavaScript
/* Plugin: searchFilter v1.2.9 * Author: Kasey Speakman (kasey@cornerspeed.com) * License: Dual Licensed, MIT and GPL v2 (http://www.gnu.org/licenses/gpl-2.0.html) * * REQUIREMENTS: * jQuery 1.3+ (http://jquery.com/) * A Themeroller Theme (http://jqueryui.com/themeroller/) * * SECURITY WARNING * You should always implement server-side checking to ensure that * the query will fail when forged/invalid data is received. * Clever users can send any value they want through JavaScript and HTTP POST/GET. * * THEMES * Simply include the CSS file for your Themeroller theme. * * DESCRIPTION * This plugin creates a new searchFilter object in the specified container * * INPUT TYPE * fields: an array of field objects. each object has the following properties: * text: a string containing the display name of the field (e.g. "Field 1") * itemval: a string containing the actual field name (e.g. "field1") * optional properties: * ops: an array of operators in the same format as jQuery.fn.searchFilter.defaults.operators * that is: [ { op: 'gt', text: 'greater than'}, { op:'lt', text: 'less than'}, ... ] * if not specified, the passed-in options used, and failting that, jQuery.fn.searchFilter.defaults.operators will be used * *** NOTE *** * Specifying a dataUrl or dataValues property means that a <select ...> (drop-down-list) will be generated * instead of a text input <input type='text'.../> where the user would normally type in their search data * ************ * dataUrl: a url that will return the html select for this field, this url will only be called once for this field * dataValues: the possible values for this field in the form [ { text: 'Data Display Text', value: 'data_actual_value' }, { ... } ] * dataInit: a function that you can use to initialize the data field. this function is passed the jQuery-fied data element * dataEvents: list of events to apply to the data element. uses $("#id").bind(type, [data], fn) to bind events to data element * *** JSON of this object could look like this: *** * var fields = [ * { * text: 'Field Display Name', * itemval: 'field_actual_name', * // below this are optional values * ops: [ // this format is the same as jQuery.fn.searchFilter.defaults.operators * { op: 'gt', text: 'greater than' }, * { op: 'lt', text: 'less than' } * ], * dataUrl: 'http://server/path/script.php?propName=propValue', // using this creates a select for the data input instead of an input type='text' * dataValues: [ // using this creates a select for the data input instead of an input type='text' * { text: 'Data Value Display Name', value: 'data_actual_value' }, * { ... } * ], * dataInit: function(jElem) { jElem.datepicker(options); }, * dataEvents: [ // these are the same options that you pass to $("#id").bind(type, [data], fn) * { type: 'click', data: { i: 7 }, fn: function(e) { console.log(e.data.i); } }, * { type: 'keypress', fn: function(e) { console.log('keypress'); } } * ] * }, * { ... } * ] * options: name:value properties containing various creation options * see jQuery.fn.searchFilter.defaults for the overridable options * * RETURN TYPE: This plugin returns a SearchFilter object, which has additional SearchFilter methods: * Methods * add: Adds a filter. added to the end of the list unless a jQuery event object or valid row number is passed. * del: Removes a filter. removed from the end of the list unless a jQuery event object or valid row number is passed. * reset: resets filters back to original state (only one blank filter), and calls onReset * search: puts the search rules into an object and calls onSearch with it * close: calls the onClose event handler * * USAGE * HTML * <head> * ... * <script src="path/to/jquery.min.js" type="text/javascript"></script> * <link href="path/to/themeroller.css" rel="Stylesheet" type="text/css" /> * <script src="path/to/jquery.searchFilter.js" type="text/javascript"></script> * <link href="path/to/jquery.searchFilter.css" rel="Stylesheet" type="text/css" /> * ... * </head> * <body> * ... * <div id='mySearch'></div> * ... * </body> * JQUERY * Methods * initializing: $("#mySearch").searchFilter([{text: "Field 1", value: "field1"},{text: "Field 2", value: "field2"}], {onSearch: myFilterRuleReceiverFn, onReset: myFilterResetFn }); * Manual Methods (there's no need to call these methods unless you are trying to manipulate searchFilter with script) * add: $("#mySearch").searchFilter().add(); // appends a blank filter * $("#mySearch").searchFilter().add(0); // copies the first filter as second * del: $("#mySearch").searchFilter().del(); // removes the bottom filter * $("#mySearch").searchFilter().del(1); // removes the second filter * search: $("#mySearch").searchFilter().search(); // invokes onSearch, passing it a ruleGroup object * reset: $("#mySearch").searchFilter().reset(); // resets rules and invokes onReset * close: $("#mySearch").searchFilter().close(); // without an onClose handler, equivalent to $("#mySearch").hide(); * * NOTE: You can get the jQuery object back from the SearchFilter object by chaining .$ * Example * $("#mySearch").searchFilter().add().add().reset().$.hide(); * Verbose Example * $("#mySearch") // gets jQuery object for the HTML element with id="mySearch" * .searchFilter() // gets the SearchFilter object for an existing search filter * .add() // adds a new filter to the end of the list * .add() // adds another new filter to the end of the list * .reset() // resets filters back to original state, triggers onReset * .$ // returns jQuery object for $("#mySearch") * .hide(); // equivalent to $("#mySearch").hide(); */ jQuery.fn.searchFilter = function(fields, options) { function SearchFilter(jQ, fields, options) { //--------------------------------------------------------------- // PUBLIC VARS //--------------------------------------------------------------- this.$ = jQ; // makes the jQuery object available as .$ from the return value //--------------------------------------------------------------- // PUBLIC FUNCTIONS //--------------------------------------------------------------- this.add = function(i) { if (i == null) jQ.find(".ui-add-last").click(); else jQ.find(".sf:eq(" + i + ") .ui-add").click(); return this; }; this.del = function(i) { if (i == null) jQ.find(".sf:last .ui-del").click(); else jQ.find(".sf:eq(" + i + ") .ui-del").click(); return this; }; this.search = function(e) { jQ.find(".ui-search").click(); return this; }; this.reset = function(o) { if(o===undefined) o = false; jQ.find(".ui-reset").trigger('click',[o]); return this; }; this.close = function() { jQ.find(".ui-closer").click(); return this; }; //--------------------------------------------------------------- // "CONSTRUCTOR" (in air quotes) //--------------------------------------------------------------- if (fields != null) { // type coercion matches undefined as well as null //--------------------------------------------------------------- // UTILITY FUNCTIONS //--------------------------------------------------------------- function hover() { jQuery(this).toggleClass("ui-state-hover"); return false; } function active(e) { jQuery(this).toggleClass("ui-state-active", (e.type == "mousedown")); return false; } function buildOpt(value, text) { return "<option value='" + value + "'>" + text + "</option>"; } function buildSel(className, options, isHidden) { return "<select class='" + className + "'" + (isHidden ? " style='display:none;'" : "") + ">" + options + "</select>"; } function initData(selector, fn) { var jElem = jQ.find("tr.sf td.data " + selector); if (jElem[0] != null) fn(jElem); } function bindDataEvents(selector, events) { var jElem = jQ.find("tr.sf td.data " + selector); if (jElem[0] != null) { jQuery.each(events, function() { if (this.data != null) jElem.bind(this.type, this.data, this.fn); else jElem.bind(this.type, this.fn); }); } } //--------------------------------------------------------------- // SUPER IMPORTANT PRIVATE VARS //--------------------------------------------------------------- // copies jQuery.fn.searchFilter.defaults.options properties onto an empty object, then options onto that var opts = jQuery.extend({}, jQuery.fn.searchFilter.defaults, options); // this is keeps track of the last asynchronous setup var highest_late_setup = -1; //--------------------------------------------------------------- // CREATION PROCESS STARTS //--------------------------------------------------------------- // generate the global ops var gOps_html = ""; jQuery.each(opts.groupOps, function() { gOps_html += buildOpt(this.op, this.text); }); gOps_html = "<select name='groupOp'>" + gOps_html + "</select>"; /* original content - doesn't minify very well jQ .html("") // clear any old content .addClass("ui-searchFilter") // add classes .append( // add content "\ <div class='ui-widget-overlay' style='z-index: -1'>&nbsp;</div>\ <table class='ui-widget-content ui-corner-all'>\ <thead>\ <tr>\ <td colspan='5' class='ui-widget-header ui-corner-all' style='line-height: 18px;'>\ <div class='ui-closer ui-state-default ui-corner-all ui-helper-clearfix' style='float: right;'>\ <span class='ui-icon ui-icon-close'></span>\ </div>\ " + opts.windowTitle + "\ </td>\ </tr>\ </thead>\ <tbody>\ <tr class='sf'>\ <td class='fields'></td>\ <td class='ops'></td>\ <td class='data'></td>\ <td><div class='ui-del ui-state-default ui-corner-all'><span class='ui-icon ui-icon-minus'></span></div></td>\ <td><div class='ui-add ui-state-default ui-corner-all'><span class='ui-icon ui-icon-plus'></span></div></td>\ </tr>\ <tr>\ <td colspan='5' class='divider'><div>&nbsp;</div></td>\ </tr>\ </tbody>\ <tfoot>\ <tr>\ <td colspan='3'>\ <span class='ui-reset ui-state-default ui-corner-all' style='display: inline-block; float: left;'><span class='ui-icon ui-icon-arrowreturnthick-1-w' style='float: left;'></span><span style='line-height: 18px; padding: 0 7px 0 3px;'>" + opts.resetText + "</span></span>\ <span class='ui-search ui-state-default ui-corner-all' style='display: inline-block; float: right;'><span class='ui-icon ui-icon-search' style='float: left;'></span><span style='line-height: 18px; padding: 0 7px 0 3px;'>" + opts.searchText + "</span></span>\ <span class='matchText'>" + opts.matchText + "</span> \ " + gOps_html + " \ <span class='rulesText'>" + opts.rulesText + "</span>\ </td>\ <td>&nbsp;</td>\ <td><div class='ui-add-last ui-state-default ui-corner-all'><span class='ui-icon ui-icon-plusthick'></span></div></td>\ </tr>\ </tfoot>\ </table>\ "); /* end hard-to-minify code */ /* begin easier to minify code */ jQ.html("").addClass("ui-searchFilter").append("<div class='ui-widget-overlay' style='z-index: -1'>&#160;</div><table class='ui-widget-content ui-corner-all'><thead><tr><td colspan='5' class='ui-widget-header ui-corner-all' style='line-height: 18px;'><div class='ui-closer ui-state-default ui-corner-all ui-helper-clearfix' style='float: right;'><span class='ui-icon ui-icon-close'></span></div>" + opts.windowTitle + "</td></tr></thead><tbody><tr class='sf'><td class='fields'></td><td class='ops'></td><td class='data'></td><td><div class='ui-del ui-state-default ui-corner-all'><span class='ui-icon ui-icon-minus'></span></div></td><td><div class='ui-add ui-state-default ui-corner-all'><span class='ui-icon ui-icon-plus'></span></div></td></tr><tr><td colspan='5' class='divider'><hr class='ui-widget-content' style='margin:1px'/></td></tr></tbody><tfoot><tr><td colspan='3'><span class='ui-reset ui-state-default ui-corner-all' style='display: inline-block; float: left;'><span class='ui-icon ui-icon-arrowreturnthick-1-w' style='float: left;'></span><span style='line-height: 18px; padding: 0 7px 0 3px;'>" + opts.resetText + "</span></span><span class='ui-search ui-state-default ui-corner-all' style='display: inline-block; float: right;'><span class='ui-icon ui-icon-search' style='float: left;'></span><span style='line-height: 18px; padding: 0 7px 0 3px;'>" + opts.searchText + "</span></span><span class='matchText'>" + opts.matchText + "</span> " + gOps_html + " <span class='rulesText'>" + opts.rulesText + "</span></td><td>&#160;</td><td><div class='ui-add-last ui-state-default ui-corner-all'><span class='ui-icon ui-icon-plusthick'></span></div></td></tr></tfoot></table>"); /* end easier-to-minify code */ var jRow = jQ.find("tr.sf"); var jFields = jRow.find("td.fields"); var jOps = jRow.find("td.ops"); var jData = jRow.find("td.data"); // generate the defaults var default_ops_html = ""; jQuery.each(opts.operators, function() { default_ops_html += buildOpt(this.op, this.text); }); default_ops_html = buildSel("default", default_ops_html, true); jOps.append(default_ops_html); var default_data_html = "<input type='text' class='default' style='display:none;' />"; jData.append(default_data_html); // generate the field list as a string var fields_html = ""; var has_custom_ops = false; var has_custom_data = false; jQuery.each(fields, function(i) { var field_num = i; fields_html += buildOpt(this.itemval, this.text); // add custom ops if they exist if (this.ops != null) { has_custom_ops = true; var custom_ops = ""; jQuery.each(this.ops, function() { custom_ops += buildOpt(this.op, this.text); }); custom_ops = buildSel("field" + field_num, custom_ops, true); jOps.append(custom_ops); } // add custom data if it is given if (this.dataUrl != null) { if (i > highest_late_setup) highest_late_setup = i; has_custom_data = true; var dEvents = this.dataEvents; var iEvent = this.dataInit; var bs = this.buildSelect; jQuery.ajax(jQuery.extend({ url : this.dataUrl, complete: function(data) { var $d; if(bs != null) $d =jQuery("<div />").append(bs(data)); else $d = jQuery("<div />").append(data.responseText); $d.find("select").addClass("field" + field_num).hide(); jData.append($d.html()); if (iEvent) initData(".field" + i, iEvent); if (dEvents) bindDataEvents(".field" + i, dEvents); if (i == highest_late_setup) { // change should get called no more than twice when this searchFilter is constructed jQ.find("tr.sf td.fields select[name='field']").change(); } } },opts.ajaxSelectOptions)); } else if (this.dataValues != null) { has_custom_data = true; var custom_data = ""; jQuery.each(this.dataValues, function() { custom_data += buildOpt(this.value, this.text); }); custom_data = buildSel("field" + field_num, custom_data, true); jData.append(custom_data); } else if (this.dataEvents != null || this.dataInit != null) { has_custom_data = true; var custom_data = "<input type='text' class='field" + field_num + "' />"; jData.append(custom_data); } // attach events to data if they exist if (this.dataInit != null && i != highest_late_setup) initData(".field" + i, this.dataInit); if (this.dataEvents != null && i != highest_late_setup) bindDataEvents(".field" + i, this.dataEvents); }); fields_html = "<select name='field'>" + fields_html + "</select>"; jFields.append(fields_html); // setup the field select with an on-change event if there are custom ops or data var jFSelect = jFields.find("select[name='field']"); if (has_custom_ops) jFSelect.change(function(e) { var index = e.target.selectedIndex; var td = jQuery(e.target).parents("tr.sf").find("td.ops"); td.find("select").removeAttr("name").hide(); // disown and hide all elements var jElem = td.find(".field" + index); if (jElem[0] == null) jElem = td.find(".default"); // if there's not an element for that field, use the default one jElem.attr("name", "op").show(); return false; }); else jOps.find(".default").attr("name", "op").show(); if (has_custom_data) jFSelect.change(function(e) { var index = e.target.selectedIndex; var td = jQuery(e.target).parents("tr.sf").find("td.data"); td.find("select,input").removeClass("vdata").hide(); // disown and hide all elements var jElem = td.find(".field" + index); if (jElem[0] == null) jElem = td.find(".default"); // if there's not an element for that field, use the default one jElem.show().addClass("vdata"); return false; }); else jData.find(".default").show().addClass("vdata"); // go ahead and call the change event and setup the ops and data values if (has_custom_ops || has_custom_data) jFSelect.change(); // bind events jQ.find(".ui-state-default").hover(hover, hover).mousedown(active).mouseup(active); // add hover/active effects to all buttons jQ.find(".ui-closer").click(function(e) { opts.onClose(jQuery(jQ.selector)); return false; }); jQ.find(".ui-del").click(function(e) { var row = jQuery(e.target).parents(".sf"); if (row.siblings(".sf").length > 0) { // doesn't remove if there's only one filter left if (opts.datepickerFix === true && jQuery.fn.datepicker !== undefined) row.find(".hasDatepicker").datepicker("destroy"); // clean up datepicker's $.data mess row.remove(); // also unbinds } else { // resets the filter if it's the last one row.find("select[name='field']")[0].selectedIndex = 0; row.find("select[name='op']")[0].selectedIndex = 0; row.find(".data input").val(""); // blank all input values row.find(".data select").each(function() { this.selectedIndex = 0; }); // select first option on all selects row.find("select[name='field']").change(function(event){event.stopPropagation();}); // trigger any change events } return false; }); jQ.find(".ui-add").click(function(e) { var row = jQuery(e.target).parents(".sf"); var newRow = row.clone(true).insertAfter(row); newRow.find(".ui-state-default").removeClass("ui-state-hover ui-state-active"); if (opts.clone) { newRow.find("select[name='field']")[0].selectedIndex = row.find("select[name='field']")[0].selectedIndex; var stupid_browser = (newRow.find("select[name='op']")[0] == null); // true for IE6 if (!stupid_browser) newRow.find("select[name='op']").focus()[0].selectedIndex = row.find("select[name='op']")[0].selectedIndex; var jElem = newRow.find("select.vdata"); if (jElem[0] != null) // select doesn't copy it's selected index when cloned jElem[0].selectedIndex = row.find("select.vdata")[0].selectedIndex; } else { newRow.find(".data input").val(""); // blank all input values newRow.find("select[name='field']").focus(); } if (opts.datepickerFix === true && jQuery.fn.datepicker !== undefined) { // using $.data to associate data with document elements is Not Good row.find(".hasDatepicker").each(function() { var settings = jQuery.data(this, "datepicker").settings; newRow.find("#" + this.id).unbind().removeAttr("id").removeClass("hasDatepicker").datepicker(settings); }); } newRow.find("select[name='field']").change(function(event){event.stopPropagation();} ); return false; }); jQ.find(".ui-search").click(function(e) { var ui = jQuery(jQ.selector); // pointer to search box wrapper element var ruleGroup; var group_op = ui.find("select[name='groupOp'] :selected").val(); // puls "AND" or "OR" if (!opts.stringResult) { ruleGroup = { groupOp: group_op, rules: [] }; } else { ruleGroup = "{\"groupOp\":\"" + group_op + "\",\"rules\":["; } ui.find(".sf").each(function(i) { var tField = jQuery(this).find("select[name='field'] :selected").val(); var tOp = jQuery(this).find("select[name='op'] :selected").val(); var tData = jQuery(this).find("input.vdata,select.vdata :selected").val(); tData += ""; tData = tData.replace(/\\/g,'\\\\').replace(/\"/g,'\\"'); if (!opts.stringResult) { ruleGroup.rules.push({ field: tField, op: tOp, data: tData }); } else { if (i > 0) ruleGroup += ","; ruleGroup += "{\"field\":\"" + tField + "\","; ruleGroup += "\"op\":\"" + tOp + "\","; ruleGroup += "\"data\":\"" + tData + "\"}"; } }); if (opts.stringResult) ruleGroup += "]}"; opts.onSearch(ruleGroup); return false; }); jQ.find(".ui-reset").click(function(e,op) { var ui = jQuery(jQ.selector); ui.find(".ui-del").click(); // removes all filters, resets the last one ui.find("select[name='groupOp']")[0].selectedIndex = 0; // changes the op back to the default one opts.onReset(op); return false; }); jQ.find(".ui-add-last").click(function() { var row = jQuery(jQ.selector + " .sf:last"); var newRow = row.clone(true).insertAfter(row); newRow.find(".ui-state-default").removeClass("ui-state-hover ui-state-active"); newRow.find(".data input").val(""); // blank all input values newRow.find("select[name='field']").focus(); if (opts.datepickerFix === true && jQuery.fn.datepicker !== undefined) { // using $.data to associate data with document elements is Not Good row.find(".hasDatepicker").each(function() { var settings = jQuery.data(this, "datepicker").settings; newRow.find("#" + this.id).unbind().removeAttr("id").removeClass("hasDatepicker").datepicker(settings); }); } newRow.find("select[name='field']").change(function(event){event.stopPropagation();}); return false; }); this.setGroupOp = function(setting) { /* a "setter" for groupping argument. * ("AND" or "OR") * * Inputs: * setting - a string * * Returns: * Does not return anything. May add success / failure reporting in future versions. * * author: Daniel Dotsenko (dotsa@hotmail.com) */ selDOMobj = jQ.find("select[name='groupOp']")[0]; var indexmap = {}, l = selDOMobj.options.length, i; for (i=0; i<l; i++) { indexmap[selDOMobj.options[i].value] = i; } selDOMobj.selectedIndex = indexmap[setting]; jQuery(selDOMobj).change(function(event){event.stopPropagation();}); }; this.setFilter = function(settings) { /* a "setter" for an arbitrary SearchFilter's filter line. * designed to abstract the DOM manipulations required to infer * a particular filter is a fit to the search box. * * Inputs: * settings - an "object" (dictionary) * index (optional*) (to be implemented in the future) : signed integer index (from top to bottom per DOM) of the filter line to fill. * Negative integers (rooted in -1 and lower) denote position of the line from the bottom. * sfref (optional*) : DOM object referencing individual '.sf' (normally a TR element) to be populated. (optional) * filter (mandatory) : object (dictionary) of form {'field':'field_value','op':'op_value','data':'data value'} * * * It is mandatory to have either index or sfref defined. * * Returns: * Does not return anything. May add success / failure reporting in future versions. * * author: Daniel Dotsenko (dotsa@hotmail.com) */ var o = settings['sfref'], filter = settings['filter']; // setting up valueindexmap that we will need to manipulate SELECT elements. var fields = [], i, j , l, lj, li, valueindexmap = {}; // example of valueindexmap: // {'field1':{'index':0,'ops':{'eq':0,'ne':1}},'fieldX':{'index':1,'ops':{'eq':0,'ne':1},'data':{'true':0,'false':1}}}, // if data is undefined it's a INPUT field. If defined, it's SELECT selDOMobj = o.find("select[name='field']")[0]; for (i=0, l=selDOMobj.options.length; i<l; i++) { valueindexmap[selDOMobj.options[i].value] = {'index':i,'ops':{}}; fields.push(selDOMobj.options[i].value); } for (i=0, li=fields.length; i < li; i++) { selDOMobj = o.find(".ops > select[class='field"+i+"']")[0]; if (selDOMobj) { for (j=0, lj=selDOMobj.options.length; j<lj; j++) { valueindexmap[fields[i]]['ops'][selDOMobj.options[j].value] = j; } } selDOMobj = o.find(".data > select[class='field"+i+"']")[0]; if (selDOMobj) { valueindexmap[fields[i]]['data'] = {}; // this setting is the flag that 'data' is contained in a SELECT for (j=0, lj=selDOMobj.options.length; j<lj; j++) { valueindexmap[fields[i]]['data'][selDOMobj.options[j].value] = j; } } } // done populating valueindexmap // preparsing the index values for SELECT elements. var fieldvalue, fieldindex, opindex, datavalue, dataindex; fieldvalue = filter['field']; if (valueindexmap[fieldvalue]) { fieldindex = valueindexmap[fieldvalue]['index']; } if (fieldindex != null) { opindex = valueindexmap[fieldvalue]['ops'][filter['op']]; if(opindex === undefined) { for(i=0,li=options.operators.length; i<li;i++) { if(options.operators[i].op == filter.op ){ opindex = i; break; } } } datavalue = filter['data']; if (valueindexmap[fieldvalue]['data'] == null) { dataindex = -1; // 'data' is not SELECT, Making the var 'defined' } else { dataindex = valueindexmap[fieldvalue]['data'][datavalue]; // 'undefined' may come from here. } } // only if values for 'field' and 'op' and 'data' are 'found' in mapping... if (fieldindex != null && opindex != null && dataindex != null) { o.find("select[name='field']")[0].selectedIndex = fieldindex; o.find("select[name='field']").change(); o.find("select[name='op']")[0].selectedIndex = opindex; o.find("input.vdata").val(datavalue); // if jquery does not find any INPUT, it does not set any. This means we deal with SELECT o = o.find("select.vdata")[0]; if (o) { o.selectedIndex = dataindex; } return true } else { return false } }; // end of this.setFilter fn } // end of if fields != null } return new SearchFilter(this, fields, options); }; jQuery.fn.searchFilter.version = '1.2.9'; /* This property contains the default options */ jQuery.fn.searchFilter.defaults = { /* * PROPERTY * TYPE: boolean * DESCRIPTION: clone a row if it is added from an existing row * when false, any new added rows will be blank. */ clone: true, /* * PROPERTY * TYPE: boolean * DESCRIPTION: current version of datepicker uses a data store, * which is incompatible with $().clone(true) */ datepickerFix: true, /* * FUNCTION * DESCRIPTION: the function that will be called when the user clicks Reset * INPUT TYPE: JS object if stringResult is false, otherwise is JSON string */ onReset: function(data) { alert("Reset Clicked. Data Returned: " + data) }, /* * FUNCTION * DESCRIPTION: the function that will be called when the user clicks Search * INPUT TYPE: JS object if stringResult is false, otherwise is JSON string */ onSearch: function(data) { alert("Search Clicked. Data Returned: " + data) }, /* * FUNCTION * DESCRIPTION: the function that will be called when the user clicks the Closer icon * or the close() function is called * if left null, it simply does a .hide() on the searchFilter * INPUT TYPE: a jQuery object for the searchFilter */ onClose: function(jElem) { jElem.hide(); }, /* * PROPERTY * TYPE: array of objects, each object has the properties op and text * DESCRIPTION: the selectable operators that are applied between rules * e.g. for {op:"AND", text:"all"} * the search filter box will say: match all rules * the server should interpret this as putting the AND op between each rule: * rule1 AND rule2 AND rule3 * text will be the option text, and op will be the option value */ groupOps: [ { op: "AND", text: "all" }, { op: "OR", text: "any" } ], /* * PROPERTY * TYPE: array of objects, each object has the properties op and text * DESCRIPTION: the operators that will appear as drop-down options * text will be the option text, and op will be the option value */ operators: [ { op: "eq", text: "is equal to" }, { op: "ne", text: "is not equal to" }, { op: "lt", text: "is less than" }, { op: "le", text: "is less or equal to" }, { op: "gt", text: "is greater than" }, { op: "ge", text: "is greater or equal to" }, { op: "in", text: "is in" }, { op: "ni", text: "is not in" }, { op: "bw", text: "begins with" }, { op: "bn", text: "does not begin with" }, { op: "ew", text: "ends with" }, { op: "en", text: "does not end with" }, { op: "cn", text: "contains" }, { op: "nc", text: "does not contain" } ], /* * PROPERTY * TYPE: string * DESCRIPTION: part of the phrase: _match_ ANY/ALL rules */ matchText: "match", /* * PROPERTY * TYPE: string * DESCRIPTION: part of the phrase: match ANY/ALL _rules_ */ rulesText: "rules", /* * PROPERTY * TYPE: string * DESCRIPTION: the text that will be displayed in the reset button */ resetText: "Reset", /* * PROPERTY * TYPE: string * DESCRIPTION: the text that will be displayed in the search button */ searchText: "Search", /* * PROPERTY * TYPE: boolean * DESCRIPTION: a flag that, when set, will make the onSearch and onReset return strings instead of objects */ stringResult: true, /* * PROPERTY * TYPE: string * DESCRIPTION: the title of the searchFilter window */ windowTitle: "Search Rules", /* * PROPERTY * TYPE: object * DESCRIPTION: options to extend the ajax request */ ajaxSelectOptions : {} }; /* end of searchFilter */
JavaScript
/* Transform a table to a jqGrid. Peter Romianowski <peter.romianowski@optivo.de> If the first column of the table contains checkboxes or radiobuttons then the jqGrid is made selectable. */ // Addition - selector can be a class or id function tableToGrid(selector, options) { jQuery(selector).each(function() { if(this.grid) {return;} //Adedd from Tony Tomov // This is a small "hack" to make the width of the jqGrid 100% jQuery(this).width("99%"); var w = jQuery(this).width(); // Text whether we have single or multi select var inputCheckbox = jQuery('input[type=checkbox]:first', jQuery(this)); var inputRadio = jQuery('input[type=radio]:first', jQuery(this)); var selectMultiple = inputCheckbox.length > 0; var selectSingle = !selectMultiple && inputRadio.length > 0; var selectable = selectMultiple || selectSingle; //var inputName = inputCheckbox.attr("name") || inputRadio.attr("name"); // Build up the columnModel and the data var colModel = []; var colNames = []; jQuery('th', jQuery(this)).each(function() { if (colModel.length === 0 && selectable) { colModel.push({ name: '__selection__', index: '__selection__', width: 0, hidden: true }); colNames.push('__selection__'); } else { colModel.push({ name: jQuery(this).attr("id") || jQuery.trim(jQuery.jgrid.stripHtml(jQuery(this).html())).split(' ').join('_'), index: jQuery(this).attr("id") || jQuery.trim(jQuery.jgrid.stripHtml(jQuery(this).html())).split(' ').join('_'), width: jQuery(this).width() || 150 }); colNames.push(jQuery(this).html()); } }); var data = []; var rowIds = []; var rowChecked = []; jQuery('tbody > tr', jQuery(this)).each(function() { var row = {}; var rowPos = 0; jQuery('td', jQuery(this)).each(function() { if (rowPos === 0 && selectable) { var input = jQuery('input', jQuery(this)); var rowId = input.attr("value"); rowIds.push(rowId || data.length); if (input.attr("checked")) { rowChecked.push(rowId); } row[colModel[rowPos].name] = input.attr("value"); } else { row[colModel[rowPos].name] = jQuery(this).html(); } rowPos++; }); if(rowPos >0) { data.push(row); } }); // Clear the original HTML table jQuery(this).empty(); // Mark it as jqGrid jQuery(this).addClass("scroll"); jQuery(this).jqGrid(jQuery.extend({ datatype: "local", width: w, colNames: colNames, colModel: colModel, multiselect: selectMultiple //inputName: inputName, //inputValueCol: imputName != null ? "__selection__" : null }, options || {})); // Add data var a; for (a = 0; a < data.length; a++) { var id = null; if (rowIds.length > 0) { id = rowIds[a]; if (id && id.replace) { // We have to do this since the value of a checkbox // or radio button can be anything id = encodeURIComponent(id).replace(/[.\-%]/g, "_"); } } if (id === null) { id = a + 1; } jQuery(this).jqGrid("addRowData",id, data[a]); } // Set the selection for (a = 0; a < rowChecked.length; a++) { jQuery(this).jqGrid("setSelection",rowChecked[a]); } }); };
JavaScript
/* * jqModal - Minimalist Modaling with jQuery * (http://dev.iceburg.net/jquery/jqmodal/) * * Copyright (c) 2007,2008 Brice Burgess <bhb@iceburg.net> * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * $Version: 07/06/2008 +r13 */ (function($) { $.fn.jqm=function(o){ var p={ overlay: 50, closeoverlay : true, overlayClass: 'jqmOverlay', closeClass: 'jqmClose', trigger: '.jqModal', ajax: F, ajaxText: '', target: F, modal: F, toTop: F, onShow: F, onHide: F, onLoad: F }; return this.each(function(){if(this._jqm)return H[this._jqm].c=$.extend({},H[this._jqm].c,o);s++;this._jqm=s; H[s]={c:$.extend(p,$.jqm.params,o),a:F,w:$(this).addClass('jqmID'+s),s:s}; if(p.trigger)$(this).jqmAddTrigger(p.trigger); });}; $.fn.jqmAddClose=function(e){return hs(this,e,'jqmHide');}; $.fn.jqmAddTrigger=function(e){return hs(this,e,'jqmShow');}; $.fn.jqmShow=function(t){return this.each(function(){$.jqm.open(this._jqm,t);});}; $.fn.jqmHide=function(t){return this.each(function(){$.jqm.close(this._jqm,t)});}; $.jqm = { hash:{}, open:function(s,t){var h=H[s],c=h.c,cc='.'+c.closeClass,z=(parseInt(h.w.css('z-index')));z=(z>0)?z:3000;var o=$('<div></div>').css({height:'100%',width:'100%',position:'fixed',left:0,top:0,'z-index':z-1,opacity:c.overlay/100});if(h.a)return F;h.t=t;h.a=true;h.w.css('z-index',z); if(c.modal) {if(!A[0])setTimeout(function(){L('bind');},1);A.push(s);} else if(c.overlay > 0) {if(c.closeoverlay) h.w.jqmAddClose(o);} else o=F; h.o=(o)?o.addClass(c.overlayClass).prependTo('body'):F; if(ie6){$('html,body').css({height:'100%',width:'100%'});if(o){o=o.css({position:'absolute'})[0];for(var y in {Top:1,Left:1})o.style.setExpression(y.toLowerCase(),"(_=(document.documentElement.scroll"+y+" || document.body.scroll"+y+"))+'px'");}} if(c.ajax) {var r=c.target||h.w,u=c.ajax;r=(typeof r == 'string')?$(r,h.w):$(r);u=(u.substr(0,1) == '@')?$(t).attr(u.substring(1)):u; r.html(c.ajaxText).load(u,function(){if(c.onLoad)c.onLoad.call(this,h);if(cc)h.w.jqmAddClose($(cc,h.w));e(h);});} else if(cc)h.w.jqmAddClose($(cc,h.w)); if(c.toTop&&h.o)h.w.before('<span id="jqmP'+h.w[0]._jqm+'"></span>').insertAfter(h.o); (c.onShow)?c.onShow(h):h.w.show();e(h);return F; }, close:function(s){var h=H[s];if(!h.a)return F;h.a=F; if(A[0]){A.pop();if(!A[0])L('unbind');} if(h.c.toTop&&h.o)$('#jqmP'+h.w[0]._jqm).after(h.w).remove(); if(h.c.onHide)h.c.onHide(h);else{h.w.hide();if(h.o)h.o.remove();} return F; }, params:{}}; var s=0,H=$.jqm.hash,A=[],ie6=$.browser.msie&&($.browser.version == "6.0"),F=false, e=function(h){var i=$('<iframe src="javascript:false;document.write(\'\');" class="jqm"></iframe>').css({opacity:0});if(ie6)if(h.o)h.o.html('<p style="width:100%;height:100%"/>').prepend(i);else if(!$('iframe.jqm',h.w)[0])h.w.prepend(i); f(h);}, f=function(h){try{$(':input:visible',h.w)[0].focus();}catch(_){}}, L=function(t){$(document)[t]("keypress",m)[t]("keydown",m)[t]("mousedown",m);}, m=function(e){var h=H[A[A.length-1]],r=(!$(e.target).parents('.jqmID'+h.s)[0]);if(r)f(h);return !r;}, hs=function(w,t,c){return w.each(function(){var s=this._jqm;$(t).each(function() { if(!this[c]){this[c]=[];$(this).click(function(){for(var i in {jqmShow:1,jqmHide:1})for(var s in this[i])if(H[this[i][s]])H[this[i][s]].w[i](this);return F;});}this[c].push(s);});});}; })(jQuery);
JavaScript
;(function($){ /** * jqGrid extension for custom methods * Tony Tomov tony@trirand.com * http://trirand.com/blog/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl-2.0.html **/ $.jgrid.extend({ getColProp : function(colname){ var ret ={}, $t = this[0]; if ( !$t.grid ) { return false; } var cM = $t.p.colModel; for ( var i =0;i<cM.length;i++ ) { if ( cM[i].name == colname ) { ret = cM[i]; break; } } return ret; }, setColProp : function(colname, obj){ //do not set width will not work return this.each(function(){ if ( this.grid ) { if ( obj ) { var cM = this.p.colModel; for ( var i =0;i<cM.length;i++ ) { if ( cM[i].name == colname ) { $.extend(this.p.colModel[i],obj); break; } } } } }); }, sortGrid : function(colname,reload, sor){ return this.each(function(){ var $t=this,idx=-1; if ( !$t.grid ) { return;} if ( !colname ) { colname = $t.p.sortname; } for ( var i=0;i<$t.p.colModel.length;i++ ) { if ( $t.p.colModel[i].index == colname || $t.p.colModel[i].name==colname ) { idx = i; break; } } if ( idx!=-1 ){ var sort = $t.p.colModel[idx].sortable; if ( typeof sort !== 'boolean' ) { sort = true; } if ( typeof reload !=='boolean' ) { reload = false; } if ( sort ) { $t.sortData("jqgh_"+colname, idx, reload, sor); } } }); }, GridDestroy : function () { return this.each(function(){ if ( this.grid ) { if ( this.p.pager ) { // if not part of grid $(this.p.pager).remove(); } var gid = this.id; try { $("#gbox_"+gid).remove(); } catch (_) {} } }); }, GridUnload : function(){ return this.each(function(){ if ( !this.grid ) {return;} var defgrid = {id: $(this).attr('id'),cl: $(this).attr('class')}; if (this.p.pager) { $(this.p.pager).empty().removeClass("ui-state-default ui-jqgrid-pager corner-bottom"); } var newtable = document.createElement('table'); $(newtable).attr({id:defgrid.id}); newtable.className = defgrid.cl; var gid = this.id; $(newtable).removeClass("ui-jqgrid-btable"); if( $(this.p.pager).parents("#gbox_"+gid).length === 1 ) { $(newtable).insertBefore("#gbox_"+gid).show(); $(this.p.pager).insertBefore("#gbox_"+gid); } else { $(newtable).insertBefore("#gbox_"+gid).show(); } $("#gbox_"+gid).remove(); }); }, setGridState : function(state) { return this.each(function(){ if ( !this.grid ) {return;} var $t = this; if(state == 'hidden'){ $(".ui-jqgrid-bdiv, .ui-jqgrid-hdiv","#gview_"+$t.p.id).slideUp("fast"); if($t.p.pager) {$($t.p.pager).slideUp("fast");} if($t.p.toppager) {$($t.p.toppager).slideUp("fast");} if($t.p.toolbar[0]===true) { if( $t.p.toolbar[1]=='both') { $($t.grid.ubDiv).slideUp("fast"); } $($t.grid.uDiv).slideUp("fast"); } if($t.p.footerrow) { $(".ui-jqgrid-sdiv","#gbox_"+$t.p.id).slideUp("fast"); } $(".ui-jqgrid-titlebar-close span",$t.grid.cDiv).removeClass("ui-icon-circle-triangle-n").addClass("ui-icon-circle-triangle-s"); $t.p.gridstate = 'hidden'; } else if(state=='visible') { $(".ui-jqgrid-hdiv, .ui-jqgrid-bdiv","#gview_"+$t.p.id).slideDown("fast"); if($t.p.pager) {$($t.p.pager).slideDown("fast");} if($t.p.toppager) {$($t.p.toppager).slideDown("fast");} if($t.p.toolbar[0]===true) { if( $t.p.toolbar[1]=='both') { $($t.grid.ubDiv).slideDown("fast"); } $($t.grid.uDiv).slideDown("fast"); } if($t.p.footerrow) { $(".ui-jqgrid-sdiv","#gbox_"+$t.p.id).slideDown("fast"); } $(".ui-jqgrid-titlebar-close span",$t.grid.cDiv).removeClass("ui-icon-circle-triangle-s").addClass("ui-icon-circle-triangle-n"); $t.p.gridstate = 'visible'; } }); }, updateGridRows : function (data, rowidname, jsonreader) { var nm, success=false, title; this.each(function(){ var t = this, vl, ind, srow, sid; if(!t.grid) {return false;} if(!rowidname) { rowidname = "id"; } if( data && data.length >0 ) { $(data).each(function(j){ srow = this; ind = t.rows.namedItem(srow[rowidname]); if(ind) { sid = srow[rowidname]; if(jsonreader === true){ if(t.p.jsonReader.repeatitems === true) { if(t.p.jsonReader.cell) {srow = srow[t.p.jsonReader.cell];} for (var k=0;k<srow.length;k++) { vl = t.formatter( sid, srow[k], k, srow, 'edit'); title = t.p.colModel[k].title ? {"title":$.jgrid.stripHtml(vl)} : {}; if(t.p.treeGrid===true && nm == t.p.ExpandColumn) { $("td:eq("+k+") > span:first",ind).html(vl).attr(title); } else { $("td:eq("+k+")",ind).html(vl).attr(title); } } success = true; return true; } } $(t.p.colModel).each(function(i){ nm = jsonreader===true ? this.jsonmap || this.name :this.name; if( srow[nm] !== undefined) { vl = t.formatter( sid, srow[nm], i, srow, 'edit'); title = this.title ? {"title":$.jgrid.stripHtml(vl)} : {}; if(t.p.treeGrid===true && nm == t.p.ExpandColumn) { $("td:eq("+i+") > span:first",ind).html(vl).attr(title); } else { $("td:eq("+i+")",ind).html(vl).attr(title); } success = true; } }); } }); } }); return success; }, filterGrid : function(gridid,p){ p = $.extend({ gridModel : false, gridNames : false, gridToolbar : false, filterModel: [], // label/name/stype/defval/surl/sopt formtype : "horizontal", // horizontal/vertical autosearch: true, // if set to false a serch button should be enabled. formclass: "filterform", tableclass: "filtertable", buttonclass: "filterbutton", searchButton: "Search", clearButton: "Clear", enableSearch : false, enableClear: false, beforeSearch: null, afterSearch: null, beforeClear: null, afterClear: null, url : '', marksearched: true },p || {}); return this.each(function(){ var self = this; this.p = p; if(this.p.filterModel.length === 0 && this.p.gridModel===false) { alert("No filter is set"); return;} if( !gridid) {alert("No target grid is set!"); return;} this.p.gridid = gridid.indexOf("#") != -1 ? gridid : "#"+gridid; var gcolMod = $(this.p.gridid).jqGrid("getGridParam",'colModel'); if(gcolMod) { if( this.p.gridModel === true) { var thegrid = $(this.p.gridid)[0]; var sh; // we should use the options search, edittype, editoptions // additionally surl and defval can be added in grid colModel $.each(gcolMod, function (i,n) { var tmpFil = []; this.search = this.search === false ? false : true; if(this.editrules && this.editrules.searchhidden === true) { sh = true; } else { if(this.hidden === true ) { sh = false; } else { sh = true; } } if( this.search === true && sh === true) { if(self.p.gridNames===true) { tmpFil.label = thegrid.p.colNames[i]; } else { tmpFil.label = ''; } tmpFil.name = this.name; tmpFil.index = this.index || this.name; // we support only text and selects, so all other to text tmpFil.stype = this.edittype || 'text'; if(tmpFil.stype != 'select' ) { tmpFil.stype = 'text'; } tmpFil.defval = this.defval || ''; tmpFil.surl = this.surl || ''; tmpFil.sopt = this.editoptions || {}; tmpFil.width = this.width; self.p.filterModel.push(tmpFil); } }); } else { $.each(self.p.filterModel,function(i,n) { for(var j=0;j<gcolMod.length;j++) { if(this.name == gcolMod[j].name) { this.index = gcolMod[j].index || this.name; break; } } if(!this.index) { this.index = this.name; } }); } } else { alert("Could not get grid colModel"); return; } var triggerSearch = function() { var sdata={}, j=0, v; var gr = $(self.p.gridid)[0], nm; gr.p.searchdata = {}; if($.isFunction(self.p.beforeSearch)){self.p.beforeSearch();} $.each(self.p.filterModel,function(i,n){ nm = this.index; switch (this.stype) { case 'select' : v = $("select[name="+nm+"]",self).val(); if(v) { sdata[nm] = v; if(self.p.marksearched){ $("#jqgh_"+this.name,gr.grid.hDiv).addClass("dirty-cell"); } j++; } else { if(self.p.marksearched){ $("#jqgh_"+this.name,gr.grid.hDiv).removeClass("dirty-cell"); } try { delete gr.p.postData[this.index]; } catch (e) {} } break; default: v = $("input[name="+nm+"]",self).val(); if(v) { sdata[nm] = v; if(self.p.marksearched){ $("#jqgh_"+this.name,gr.grid.hDiv).addClass("dirty-cell"); } j++; } else { if(self.p.marksearched){ $("#jqgh_"+this.name,gr.grid.hDiv).removeClass("dirty-cell"); } try { delete gr.p.postData[this.index]; } catch(e) {} } } }); var sd = j>0 ? true : false; $.extend(gr.p.postData,sdata); var saveurl; if(self.p.url) { saveurl = $(gr).jqGrid("getGridParam",'url'); $(gr).jqGrid("setGridParam",{url:self.p.url}); } $(gr).jqGrid("setGridParam",{search:sd}).trigger("reloadGrid",[{page:1}]); if(saveurl) {$(gr).jqGrid("setGridParam",{url:saveurl});} if($.isFunction(self.p.afterSearch)){self.p.afterSearch();} }; var clearSearch = function(){ var sdata={}, v, j=0; var gr = $(self.p.gridid)[0], nm; if($.isFunction(self.p.beforeClear)){self.p.beforeClear();} $.each(self.p.filterModel,function(i,n){ nm = this.index; v = (this.defval) ? this.defval : ""; if(!this.stype){this.stype='text';} switch (this.stype) { case 'select' : var v1; $("select[name="+nm+"] option",self).each(function (i){ if(i===0) { this.selected = true; } if ($(this).text() == v) { this.selected = true; v1 = $(this).val(); return false; } }); if(v1) { // post the key and not the text sdata[nm] = v1; if(self.p.marksearched){ $("#jqgh_"+this.name,gr.grid.hDiv).addClass("dirty-cell"); } j++; } else { if(self.p.marksearched){ $("#jqgh_"+this.name,gr.grid.hDiv).removeClass("dirty-cell"); } try { delete gr.p.postData[this.index]; } catch (e) {} } break; case 'text': $("input[name="+nm+"]",self).val(v); if(v) { sdata[nm] = v; if(self.p.marksearched){ $("#jqgh_"+this.name,gr.grid.hDiv).addClass("dirty-cell"); } j++; } else { if(self.p.marksearched){ $("#jqgh_"+this.name,gr.grid.hDiv).removeClass("dirty-cell"); } try { delete gr.p.postData[this.index]; } catch (e) {} } break; } }); var sd = j>0 ? true : false; $.extend(gr.p.postData,sdata); var saveurl; if(self.p.url) { saveurl = $(gr).jqGrid("getGridParam",'url'); $(gr).jqGrid("setGridParam",{url:self.p.url}); } $(gr).jqGrid("setGridParam",{search:sd}).trigger("reloadGrid",[{page:1}]); if(saveurl) {$(gr).jqGrid("setGridParam",{url:saveurl});} if($.isFunction(self.p.afterClear)){self.p.afterClear();} }; var tbl; var formFill = function(){ var tr = document.createElement("tr"); var tr1, sb, cb,tl,td; if(self.p.formtype=='horizontal'){ $(tbl).append(tr); } $.each(self.p.filterModel,function(i,n){ tl = document.createElement("td"); $(tl).append("<label for='"+this.name+"'>"+this.label+"</label>"); td = document.createElement("td"); var $t=this; if(!this.stype) { this.stype='text';} switch (this.stype) { case "select": if(this.surl) { // data returned should have already constructed html select $(td).load(this.surl,function(){ if($t.defval) { $("select",this).val($t.defval); } $("select",this).attr({name:$t.index || $t.name, id: "sg_"+$t.name}); if($t.sopt) { $("select",this).attr($t.sopt); } if(self.p.gridToolbar===true && $t.width) { $("select",this).width($t.width); } if(self.p.autosearch===true){ $("select",this).change(function(e){ triggerSearch(); return false; }); } }); } else { // sopt to construct the values if($t.sopt.value) { var oSv = $t.sopt.value; var elem = document.createElement("select"); $(elem).attr({name:$t.index || $t.name, id: "sg_"+$t.name}).attr($t.sopt); var so, sv, ov; if(typeof oSv === "string") { so = oSv.split(";"); for(var k=0; k<so.length;k++){ sv = so[k].split(":"); ov = document.createElement("option"); ov.value = sv[0]; ov.innerHTML = sv[1]; if (sv[1]==$t.defval) { ov.selected ="selected"; } elem.appendChild(ov); } } else if(typeof oSv === "object" ) { for ( var key in oSv) { if(oSv.hasOwnProperty(key)) { i++; ov = document.createElement("option"); ov.value = key; ov.innerHTML = oSv[key]; if (oSv[key]==$t.defval) { ov.selected ="selected"; } elem.appendChild(ov); } } } if(self.p.gridToolbar===true && $t.width) { $(elem).width($t.width); } $(td).append(elem); if(self.p.autosearch===true){ $(elem).change(function(e){ triggerSearch(); return false; }); } } } break; case 'text': var df = this.defval ? this.defval: ""; $(td).append("<input type='text' name='"+(this.index || this.name)+"' id='sg_"+this.name+"' value='"+df+"'/>"); if($t.sopt) { $("input",td).attr($t.sopt); } if(self.p.gridToolbar===true && $t.width) { if($.browser.msie) { $("input",td).width($t.width-4); } else { $("input",td).width($t.width-2); } } if(self.p.autosearch===true){ $("input",td).keypress(function(e){ var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0; if(key == 13){ triggerSearch(); return false; } return this; }); } break; } if(self.p.formtype=='horizontal'){ if(self.p.gridToolbar===true && self.p.gridNames===false) { $(tr).append(td); } else { $(tr).append(tl).append(td); } $(tr).append(td); } else { tr1 = document.createElement("tr"); $(tr1).append(tl).append(td); $(tbl).append(tr1); } }); td = document.createElement("td"); if(self.p.enableSearch === true){ sb = "<input type='button' id='sButton' class='"+self.p.buttonclass+"' value='"+self.p.searchButton+"'/>"; $(td).append(sb); $("input#sButton",td).click(function(){ triggerSearch(); return false; }); } if(self.p.enableClear === true) { cb = "<input type='button' id='cButton' class='"+self.p.buttonclass+"' value='"+self.p.clearButton+"'/>"; $(td).append(cb); $("input#cButton",td).click(function(){ clearSearch(); return false; }); } if(self.p.enableClear === true || self.p.enableSearch === true) { if(self.p.formtype=='horizontal') { $(tr).append(td); } else { tr1 = document.createElement("tr"); $(tr1).append("<td>&#160;</td>").append(td); $(tbl).append(tr1); } } }; var frm = $("<form name='SearchForm' style=display:inline;' class='"+this.p.formclass+"'></form>"); tbl =$("<table class='"+this.p.tableclass+"' cellspacing='0' cellpading='0' border='0'><tbody></tbody></table>"); $(frm).append(tbl); formFill(); $(this).append(frm); this.triggerSearch = triggerSearch; this.clearSearch = clearSearch; }); }, filterToolbar : function(p){ p = $.extend({ autosearch: true, searchOnEnter : true, beforeSearch: null, afterSearch: null, beforeClear: null, afterClear: null, searchurl : '', stringResult: false, groupOp: 'AND', defaultSearch : "bw" },p || {}); return this.each(function(){ var $t = this; var triggerToolbar = function() { var sdata={}, j=0, v, nm, sopt={},so; $.each($t.p.colModel,function(i,n){ nm = this.index || this.name; switch (this.stype) { case 'select' : so = (this.searchoptions && this.searchoptions.sopt) ? this.searchoptions.sopt[0] : 'eq'; v = $("select[name="+nm+"]",$t.grid.hDiv).val(); if(v) { sdata[nm] = v; sopt[nm] = so; j++; } else { try { delete $t.p.postData[nm]; } catch (e) {} } break; case 'text': so = (this.searchoptions && this.searchoptions.sopt) ? this.searchoptions.sopt[0] : p.defaultSearch; v = $("input[name="+nm+"]",$t.grid.hDiv).val(); if(v) { sdata[nm] = v; sopt[nm] = so; j++; } else { try { delete $t.p.postData[nm]; } catch (e) {} } break; } }); var sd = j>0 ? true : false; if(p.stringResult === true || $t.p.datatype == "local") { var ruleGroup = "{\"groupOp\":\"" + p.groupOp + "\",\"rules\":["; var gi=0; $.each(sdata,function(i,n){ if (gi > 0) {ruleGroup += ",";} ruleGroup += "{\"field\":\"" + i + "\","; ruleGroup += "\"op\":\"" + sopt[i] + "\","; ruleGroup += "\"data\":\"" + n + "\"}"; gi++; }); ruleGroup += "]}"; $.extend($t.p.postData,{filters:ruleGroup}); } else { $.extend($t.p.postData,sdata); } var saveurl; if($t.p.searchurl) { saveurl = $t.p.url; $($t).jqGrid("setGridParam",{url:$t.p.searchurl}); } var bsr = false; if($.isFunction(p.beforeSearch)){bsr = p.beforeSearch.call($t);} if(!bsr) { $($t).jqGrid("setGridParam",{search:sd}).trigger("reloadGrid",[{page:1}]); } if(saveurl) {$($t).jqGrid("setGridParam",{url:saveurl});} if($.isFunction(p.afterSearch)){p.afterSearch();} }; var clearToolbar = function(trigger){ var sdata={}, v, j=0, nm; trigger = (typeof trigger != 'boolean') ? true : trigger; $.each($t.p.colModel,function(i,n){ v = (this.searchoptions && this.searchoptions.defaultValue) ? this.searchoptions.defaultValue : ""; nm = this.index || this.name; switch (this.stype) { case 'select' : var v1; $("select[name="+nm+"] option",$t.grid.hDiv).each(function (i){ if(i===0) { this.selected = true; } if ($(this).text() == v) { this.selected = true; v1 = $(this).val(); return false; } }); if (v1) { // post the key and not the text sdata[nm] = v1; j++; } else { try { delete $t.p.postData[nm]; } catch(e) {} } break; case 'text': $("input[name="+nm+"]",$t.grid.hDiv).val(v); if(v) { sdata[nm] = v; j++; } else { try { delete $t.p.postData[nm]; } catch (e){} } break; } }); var sd = j>0 ? true : false; if(p.stringResult === true || $t.p.datatype == "local") { var ruleGroup = "{\"groupOp\":\"" + p.groupOp + "\",\"rules\":["; var gi=0; $.each(sdata,function(i,n){ if (gi > 0) {ruleGroup += ",";} ruleGroup += "{\"field\":\"" + i + "\","; ruleGroup += "\"op\":\"" + "eq" + "\","; ruleGroup += "\"data\":\"" + n + "\"}"; gi++; }); ruleGroup += "]}"; $.extend($t.p.postData,{filters:ruleGroup}); } else { $.extend($t.p.postData,sdata); } var saveurl; if($t.p.searchurl) { saveurl = $t.p.url; $($t).jqGrid("setGridParam",{url:$t.p.searchurl}); } var bcv = false; if($.isFunction(p.beforeClear)){bcv = p.beforeClear.call($t);} if(!bcv) { if(trigger) { $($t).jqGrid("setGridParam",{search:sd}).trigger("reloadGrid",[{page:1}]); } } if(saveurl) {$($t).jqGrid("setGridParam",{url:saveurl});} if($.isFunction(p.afterClear)){p.afterClear();} }; var toggleToolbar = function(){ var trow = $("tr.ui-search-toolbar",$t.grid.hDiv); if(trow.css("display")=='none') { trow.show(); } else { trow.hide(); } }; // create the row function bindEvents(selector, events) { var jElem = $(selector); if (jElem[0]) { jQuery.each(events, function() { if (this.data !== undefined) { jElem.bind(this.type, this.data, this.fn); } else { jElem.bind(this.type, this.fn); } }); } } var tr = $("<tr class='ui-search-toolbar' role='rowheader'></tr>"); var timeoutHnd; $.each($t.p.colModel,function(i,n){ var cm=this, thd , th, soptions,surl,self; th = $("<th role='columnheader' class='ui-state-default ui-th-column ui-th-"+$t.p.direction+"'></th>"); thd = $("<div style='width:100%;position:relative;height:100%;padding-right:0.3em;'></div>"); if(this.hidden===true) { $(th).css("display","none");} this.search = this.search === false ? false : true; if(typeof this.stype == 'undefined' ) {this.stype='text';} soptions = $.extend({},this.searchoptions || {}); if(this.search){ switch (this.stype) { case "select": surl = this.surl || soptions.dataUrl; if(surl) { // data returned should have already constructed html select // primitive jQuery load self = thd; $.ajax($.extend({ url: surl, dataType: "html", complete: function(res,status) { if(soptions.buildSelect !== undefined) { var d = soptions.buildSelect(res); if (d) { $(self).append(d); } } else { $(self).append(res.responseText); } if(soptions.defaultValue) { $("select",self).val(soptions.defaultValue); } $("select",self).attr({name:cm.index || cm.name, id: "gs_"+cm.name}); if(soptions.attr) {$("select",self).attr(soptions.attr);} $("select",self).css({width: "100%"}); // preserve autoserch if(soptions.dataInit !== undefined) { soptions.dataInit($("select",self)[0]); } if(soptions.dataEvents !== undefined) { bindEvents($("select",self)[0],soptions.dataEvents); } if(p.autosearch===true){ $("select",self).change(function(e){ triggerToolbar(); return false; }); } res=null; } }, $.jgrid.ajaxOptions, $t.p.ajaxSelectOptions || {} )); } else { var oSv; if(cm.searchoptions && cm.searchoptions.value) { oSv = cm.searchoptions.value; } else if(cm.editoptions && cm.editoptions.value) { oSv = cm.editoptions.value; } if (oSv) { var elem = document.createElement("select"); elem.style.width = "100%"; $(elem).attr({name:cm.index || cm.name, id: "gs_"+cm.name}); var so, sv, ov; if(typeof oSv === "string") { so = oSv.split(";"); for(var k=0; k<so.length;k++){ sv = so[k].split(":"); ov = document.createElement("option"); ov.value = sv[0]; ov.innerHTML = sv[1]; elem.appendChild(ov); } } else if(typeof oSv === "object" ) { for ( var key in oSv) { if(oSv.hasOwnProperty(key)) { ov = document.createElement("option"); ov.value = key; ov.innerHTML = oSv[key]; elem.appendChild(ov); } } } if(soptions.defaultValue) { $(elem).val(soptions.defaultValue); } if(soptions.attr) {$(elem).attr(soptions.attr);} if(soptions.dataInit !== undefined) { soptions.dataInit(elem); } if(soptions.dataEvents !== undefined) { bindEvents(elem, soptions.dataEvents); } $(thd).append(elem); if(p.autosearch===true){ $(elem).change(function(e){ triggerToolbar(); return false; }); } } } break; case 'text': var df = soptions.defaultValue ? soptions.defaultValue: ""; $(thd).append("<input type='text' style='width:95%;padding:0px;' name='"+(cm.index || cm.name)+"' id='gs_"+cm.name+"' value='"+df+"'/>"); if(soptions.attr) {$("input",thd).attr(soptions.attr);} if(soptions.dataInit !== undefined) { soptions.dataInit($("input",thd)[0]); } if(soptions.dataEvents !== undefined) { bindEvents($("input",thd)[0], soptions.dataEvents); } if(p.autosearch===true){ if(p.searchOnEnter) { $("input",thd).keypress(function(e){ var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0; if(key == 13){ triggerToolbar(); return false; } return this; }); } else { $("input",thd).keydown(function(e){ var key = e.which; switch (key) { case 13: return false; case 9 : case 16: case 37: case 38: case 39: case 40: case 27: break; default : if(timeoutHnd) { clearTimeout(timeoutHnd); } timeoutHnd = setTimeout(function(){triggerToolbar();},500); } }); } } break; } } $(th).append(thd); $(tr).append(th); }); $("table thead",$t.grid.hDiv).append(tr); this.triggerToolbar = triggerToolbar; this.clearToolbar = clearToolbar; this.toggleToolbar = toggleToolbar; }); } }); })(jQuery);
JavaScript
;(function($){ /* ** * jqGrid addons using jQuery UI * Author: Mark Williams * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl-2.0.html * depends on jQuery UI **/ if ($.browser.msie && $.browser.version==8) { $.expr[":"].hidden = function(elem) { return elem.offsetWidth === 0 || elem.offsetHeight === 0 || elem.style.display == "none"; }; } // requiere load multiselect before grid $.jgrid._multiselect = false; if($.ui) { if ($.ui.multiselect ) { if($.ui.multiselect.prototype._setSelected) { var setSelected = $.ui.multiselect.prototype._setSelected; $.ui.multiselect.prototype._setSelected = function(item,selected) { var ret = setSelected.call(this,item,selected); if (selected && this.selectedList) { var elt = this.element; this.selectedList.find('li').each(function() { if ($(this).data('optionLink')) { $(this).data('optionLink').remove().appendTo(elt); } }); } return ret; }; } if($.ui.multiselect.prototype.destroy) { $.ui.multiselect.prototype.destroy = function() { this.element.show(); this.container.remove(); if ($.Widget === undefined) { $.widget.prototype.destroy.apply(this, arguments); } else { $.Widget.prototype.destroy.apply(this, arguments); } }; } $.jgrid._multiselect = true; } } $.jgrid.extend({ sortableColumns : function (tblrow) { return this.each(function (){ var ts = this; function start() {ts.p.disableClick = true;} var sortable_opts = { "tolerance" : "pointer", "axis" : "x", "scrollSensitivity": "1", "items": '>th:not(:has(#jqgh_cb,#jqgh_rn,#jqgh_subgrid),:hidden)', "placeholder": { element: function(item) { var el = $(document.createElement(item[0].nodeName)) .addClass(item[0].className+" ui-sortable-placeholder ui-state-highlight") .removeClass("ui-sortable-helper")[0]; return el; }, update: function(self, p) { p.height(self.currentItem.innerHeight() - parseInt(self.currentItem.css('paddingTop')||0, 10) - parseInt(self.currentItem.css('paddingBottom')||0, 10)); p.width(self.currentItem.innerWidth() - parseInt(self.currentItem.css('paddingLeft')||0, 10) - parseInt(self.currentItem.css('paddingRight')||0, 10)); } }, "update": function(event, ui) { var p = $(ui.item).parent(); var th = $(">th", p); var colModel = ts.p.colModel; var cmMap = {}; $.each(colModel, function(i) { cmMap[this.name]=i; }); var permutation = []; th.each(function(i) { var id = $(">div", this).get(0).id.replace(/^jqgh_/, ""); if (id in cmMap) { permutation.push(cmMap[id]); } }); $(ts).jqGrid("remapColumns",permutation, true, true); if ($.isFunction(ts.p.sortable.update)) { ts.p.sortable.update(permutation); } setTimeout(function(){ts.p.disableClick=false;}, 50); } }; if (ts.p.sortable.options) { $.extend(sortable_opts, ts.p.sortable.options); } else if ($.isFunction(ts.p.sortable)) { ts.p.sortable = { "update" : ts.p.sortable }; } if (sortable_opts.start) { var s = sortable_opts.start; sortable_opts.start = function(e,ui) { start(); s.call(this,e,ui); }; } else { sortable_opts.start = start; } if (ts.p.sortable.exclude) { sortable_opts.items += ":not("+ts.p.sortable.exclude+")"; } tblrow.sortable(sortable_opts).data("sortable").floating = true; }); }, columnChooser : function(opts) { var self = this; if($("#colchooser_"+self[0].p.id).length ) { return; } var selector = $('<div id="colchooser_'+self[0].p.id+'" style="position:relative;overflow:hidden"><div><select multiple="multiple"></select></div></div>'); var select = $('select', selector); function insert(perm,i,v) { if(i>=0){ var a = perm.slice(); var b = a.splice(i,Math.max(perm.length-i,i)); if(i>perm.length) { i = perm.length; } a[i] = v; return a.concat(b); } } opts = $.extend({ "width" : 420, "height" : 240, "classname" : null, "done" : function(perm) { if (perm) { self.jqGrid("remapColumns", perm, true); } }, /* msel is either the name of a ui widget class that extends a multiselect, or a function that supports creating a multiselect object (with no argument, or when passed an object), and destroying it (when passed the string "destroy"). */ "msel" : "multiselect", /* "msel_opts" : {}, */ /* dlog is either the name of a ui widget class that behaves in a dialog-like way, or a function, that supports creating a dialog (when passed dlog_opts) or destroying a dialog (when passed the string "destroy") */ "dlog" : "dialog", /* dlog_opts is either an option object to be passed to "dlog", or (more likely) a function that creates the options object. The default produces a suitable options object for ui.dialog */ "dlog_opts" : function(opts) { var buttons = {}; buttons[opts.bSubmit] = function() { opts.apply_perm(); opts.cleanup(false); }; buttons[opts.bCancel] = function() { opts.cleanup(true); }; return { "buttons": buttons, "close": function() { opts.cleanup(true); }, "modal" : false, "resizable": false, "width": opts.width+20 }; }, /* Function to get the permutation array, and pass it to the "done" function */ "apply_perm" : function() { $('option',select).each(function(i) { if (this.selected) { self.jqGrid("showCol", colModel[this.value].name); } else { self.jqGrid("hideCol", colModel[this.value].name); } }); var perm = []; //fixedCols.slice(0); $('option[selected]',select).each(function() { perm.push(parseInt(this.value,10)); }); $.each(perm, function() { delete colMap[colModel[parseInt(this,10)].name]; }); $.each(colMap, function() { var ti = parseInt(this,10); perm = insert(perm,ti,ti); }); if (opts.done) { opts.done.call(self, perm); } }, /* Function to cleanup the dialog, and select. Also calls the done function with no permutation (to indicate that the columnChooser was aborted */ "cleanup" : function(calldone) { call(opts.dlog, selector, 'destroy'); call(opts.msel, select, 'destroy'); selector.remove(); if (calldone && opts.done) { opts.done.call(self); } }, "msel_opts" : {} }, $.jgrid.col, opts || {}); if($.ui) { if ($.ui.multiselect ) { if(opts.msel == "multiselect") { if(!$.jgrid._multiselect) { // should be in language file alert("Multiselect plugin loaded after jqGrid. Please load the plugin before the jqGrid!"); return; } opts.msel_opts = $.extend($.ui.multiselect.defaults,opts.msel_opts); } } } if (opts.caption) { selector.attr("title", opts.caption); } if (opts.classname) { selector.addClass(opts.classname); select.addClass(opts.classname); } if (opts.width) { $(">div",selector).css({"width": opts.width,"margin":"0 auto"}); select.css("width", opts.width); } if (opts.height) { $(">div",selector).css("height", opts.height); select.css("height", opts.height - 10); } var colModel = self.jqGrid("getGridParam", "colModel"); var colNames = self.jqGrid("getGridParam", "colNames"); var colMap = {}, fixedCols = []; select.empty(); $.each(colModel, function(i) { colMap[this.name] = i; if (this.hidedlg) { if (!this.hidden) { fixedCols.push(i); } return; } select.append("<option value='"+i+"' "+ (this.hidden?"":"selected='selected'")+">"+colNames[i]+"</option>"); }); function call(fn, obj) { if (!fn) { return; } if (typeof fn == 'string') { if ($.fn[fn]) { $.fn[fn].apply(obj, $.makeArray(arguments).slice(2)); } } else if ($.isFunction(fn)) { fn.apply(obj, $.makeArray(arguments).slice(2)); } } var dopts = $.isFunction(opts.dlog_opts) ? opts.dlog_opts.call(self, opts) : opts.dlog_opts; call(opts.dlog, selector, dopts); var mopts = $.isFunction(opts.msel_opts) ? opts.msel_opts.call(self, opts) : opts.msel_opts; call(opts.msel, select, mopts); }, sortableRows : function (opts) { // Can accept all sortable options and events return this.each(function(){ var $t = this; if(!$t.grid) { return; } // Currently we disable a treeGrid sortable if($t.p.treeGrid) { return; } if($.fn.sortable) { opts = $.extend({ "cursor":"move", "axis" : "y", "items": ".jqgrow" }, opts || {}); if(opts.start && $.isFunction(opts.start)) { opts._start_ = opts.start; delete opts.start; } else {opts._start_=false;} if(opts.update && $.isFunction(opts.update)) { opts._update_ = opts.update; delete opts.update; } else {opts._update_ = false;} opts.start = function(ev,ui) { $(ui.item).css("border-width","0px"); $("td",ui.item).each(function(i){ this.style.width = $t.grid.cols[i].style.width; }); if($t.p.subGrid) { var subgid = $(ui.item).attr("id"); try { $($t).jqGrid('collapseSubGridRow',subgid); } catch (e) {} } if(opts._start_) { opts._start_.apply(this,[ev,ui]); } }; opts.update = function (ev,ui) { $(ui.item).css("border-width",""); if($t.p.rownumbers === true) { $("td.jqgrid-rownum",$t.rows).each(function(i){ $(this).html(i+1); }); } if(opts._update_) { opts._update_.apply(this,[ev,ui]); } }; $("tbody:first",$t).sortable(opts); $("tbody:first",$t).disableSelection(); } }); }, gridDnD : function(opts) { return this.each(function(){ var $t = this; if(!$t.grid) { return; } // Currently we disable a treeGrid drag and drop if($t.p.treeGrid) { return; } if(!$.fn.draggable || !$.fn.droppable) { return; } function updateDnD () { var datadnd = $.data($t,"dnd"); $("tr.jqgrow:not(.ui-draggable)",$t).draggable($.isFunction(datadnd.drag) ? datadnd.drag.call($($t),datadnd) : datadnd.drag); } var appender = "<table id='jqgrid_dnd' class='ui-jqgrid-dnd'></table>"; if($("#jqgrid_dnd").html() === null) { $('body').append(appender); } if(typeof opts == 'string' && opts == 'updateDnD' && $t.p.jqgdnd===true) { updateDnD(); return; } opts = $.extend({ "drag" : function (opts) { return $.extend({ start : function (ev, ui) { // if we are in subgrid mode try to collapse the node if($t.p.subGrid) { var subgid = $(ui.helper).attr("id"); try { $($t).jqGrid('collapseSubGridRow',subgid); } catch (e) {} } // hack // drag and drop does not insert tr in table, when the table has no rows // we try to insert new empty row on the target(s) for (var i=0;i<$.data($t,"dnd").connectWith.length;i++){ if($($.data($t,"dnd").connectWith[i]).jqGrid('getGridParam','reccount') == "0" ){ $($.data($t,"dnd").connectWith[i]).jqGrid('addRowData','jqg_empty_row',{}); } } ui.helper.addClass("ui-state-highlight"); $("td",ui.helper).each(function(i) { this.style.width = $t.grid.headers[i].width+"px"; }); if(opts.onstart && $.isFunction(opts.onstart) ) { opts.onstart.call($($t),ev,ui); } }, stop :function(ev,ui) { if(ui.helper.dropped) { var ids = $(ui.helper).attr("id"); $($t).jqGrid('delRowData',ids ); } // if we have a empty row inserted from start event try to delete it for (var i=0;i<$.data($t,"dnd").connectWith.length;i++){ $($.data($t,"dnd").connectWith[i]).jqGrid('delRowData','jqg_empty_row'); } if(opts.onstop && $.isFunction(opts.onstop) ) { opts.onstop.call($($t),ev,ui); } } },opts.drag_opts || {}); }, "drop" : function (opts) { return $.extend({ accept: function(d) { if (!$(d).hasClass('jqgrow')) { return d;} var tid = $(d).closest("table.ui-jqgrid-btable"); if(tid.length > 0 && $.data(tid[0],"dnd") !== undefined) { var cn = $.data(tid[0],"dnd").connectWith; return $.inArray('#'+this.id,cn) != -1 ? true : false; } return d; }, drop: function(ev, ui) { if (!$(ui.draggable).hasClass('jqgrow')) { return; } var accept = $(ui.draggable).attr("id"); var getdata = ui.draggable.parent().parent().jqGrid('getRowData',accept); if(!opts.dropbyname) { var j =0, tmpdata = {}, dropname; var dropmodel = $("#"+this.id).jqGrid('getGridParam','colModel'); try { for (var key in getdata) { if(getdata.hasOwnProperty(key) && dropmodel[j]) { dropname = dropmodel[j].name; tmpdata[dropname] = getdata[key]; } j++; } getdata = tmpdata; } catch (e) {} } ui.helper.dropped = true; if(opts.beforedrop && $.isFunction(opts.beforedrop) ) { //parameters to this callback - event, element, data to be inserted, sender, reciever // should return object which will be inserted into the reciever var datatoinsert = opts.beforedrop.call(this,ev,ui,getdata,$('#'+$t.id),$(this)); if (typeof datatoinsert != "undefined" && datatoinsert !== null && typeof datatoinsert == "object") { getdata = datatoinsert; } } if(ui.helper.dropped) { var grid; if(opts.autoid) { if($.isFunction(opts.autoid)) { grid = opts.autoid.call(this,getdata); } else { grid = Math.ceil(Math.random()*1000); grid = opts.autoidprefix+grid; } } // NULL is interpreted as undefined while null as object $("#"+this.id).jqGrid('addRowData',grid,getdata,opts.droppos); } if(opts.ondrop && $.isFunction(opts.ondrop) ) { opts.ondrop.call(this,ev,ui, getdata); } }}, opts.drop_opts || {}); }, "onstart" : null, "onstop" : null, "beforedrop": null, "ondrop" : null, "drop_opts" : { "activeClass": "ui-state-active", "hoverClass": "ui-state-hover" }, "drag_opts" : { "revert": "invalid", "helper": "clone", "cursor": "move", "appendTo" : "#jqgrid_dnd", "zIndex": 5000 }, "dropbyname" : false, "droppos" : "first", "autoid" : true, "autoidprefix" : "dnd_" }, opts || {}); if(!opts.connectWith) { return; } opts.connectWith = opts.connectWith.split(","); opts.connectWith = $.map(opts.connectWith,function(n){return $.trim(n);}); $.data($t,"dnd",opts); if($t.p.reccount != "0" && !$t.p.jqgdnd) { updateDnD(); } $t.p.jqgdnd = true; for (var i=0;i<opts.connectWith.length;i++){ var cn =opts.connectWith[i]; $(cn).droppable($.isFunction(opts.drop) ? opts.drop.call($($t),opts) : opts.drop); } }); }, gridResize : function(opts) { return this.each(function(){ var $t = this; if(!$t.grid || !$.fn.resizable) { return; } opts = $.extend({}, opts || {}); if(opts.alsoResize ) { opts._alsoResize_ = opts.alsoResize; delete opts.alsoResize; } else { opts._alsoResize_ = false; } if(opts.stop && $.isFunction(opts.stop)) { opts._stop_ = opts.stop; delete opts.stop; } else { opts._stop_ = false; } opts.stop = function (ev, ui) { $($t).jqGrid('setGridParam',{height:$("#gview_"+$t.p.id+" .ui-jqgrid-bdiv").height()}); $($t).jqGrid('setGridWidth',ui.size.width,opts.shrinkToFit); if(opts._stop_) { opts._stop_.call($t,ev,ui); } }; if(opts._alsoResize_) { var optstest = "{\'#gview_"+$t.p.id+" .ui-jqgrid-bdiv\':true,'" +opts._alsoResize_+"':true}"; opts.alsoResize = eval('('+optstest+')'); // the only way that I found to do this } else { opts.alsoResize = $(".ui-jqgrid-bdiv","#gview_"+$t.p.id); } delete opts._alsoResize_; $("#gbox_"+$t.p.id).resizable(opts); }); } }); })(jQuery);
JavaScript
/* * jQuery UI Multiselect * * Authors: * Michael Aufreiter (quasipartikel.at) * Yanick Rochon (yanick.rochon[at]gmail[dot]com) * * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://www.quasipartikel.at/multiselect/ * * * Depends: * ui.core.js * ui.sortable.js * * Optional: * localization (http://plugins.jquery.com/project/localisation) * scrollTo (http://plugins.jquery.com/project/ScrollTo) * * Todo: * Make batch actions faster * Implement dynamic insertion through remote calls */ (function($) { $.widget("ui.multiselect", { _init: function() { this.element.hide(); this.id = this.element.attr("id"); this.container = $('<div class="ui-multiselect ui-helper-clearfix ui-widget"></div>').insertAfter(this.element); this.count = 0; // number of currently selected options this.selectedContainer = $('<div class="selected"></div>').appendTo(this.container); this.availableContainer = $('<div class="available"></div>').appendTo(this.container); this.selectedActions = $('<div class="actions ui-widget-header ui-helper-clearfix"><span class="count">0 '+$.ui.multiselect.locale.itemsCount+'</span><a href="#" class="remove-all">'+$.ui.multiselect.locale.removeAll+'</a></div>').appendTo(this.selectedContainer); this.availableActions = $('<div class="actions ui-widget-header ui-helper-clearfix"><input type="text" class="search empty ui-widget-content ui-corner-all"/><a href="#" class="add-all">'+$.ui.multiselect.locale.addAll+'</a></div>').appendTo(this.availableContainer); this.selectedList = $('<ul class="selected connected-list"><li class="ui-helper-hidden-accessible"></li></ul>').bind('selectstart', function(){return false;}).appendTo(this.selectedContainer); this.availableList = $('<ul class="available connected-list"><li class="ui-helper-hidden-accessible"></li></ul>').bind('selectstart', function(){return false;}).appendTo(this.availableContainer); var that = this; // set dimensions this.container.width(this.element.width()+1); this.selectedContainer.width(Math.floor(this.element.width()*this.options.dividerLocation)); this.availableContainer.width(Math.floor(this.element.width()*(1-this.options.dividerLocation))); // fix list height to match <option> depending on their individual header's heights this.selectedList.height(Math.max(this.element.height()-this.selectedActions.height(),1)); this.availableList.height(Math.max(this.element.height()-this.availableActions.height(),1)); if ( !this.options.animated ) { this.options.show = 'show'; this.options.hide = 'hide'; } // init lists this._populateLists(this.element.find('option')); // make selection sortable if (this.options.sortable) { $("ul.selected").sortable({ placeholder: 'ui-state-highlight', axis: 'y', update: function(event, ui) { // apply the new sort order to the original selectbox that.selectedList.find('li').each(function() { if ($(this).data('optionLink')) $(this).data('optionLink').remove().appendTo(that.element); }); }, receive: function(event, ui) { ui.item.data('optionLink').attr('selected', true); // increment count that.count += 1; that._updateCount(); // workaround, because there's no way to reference // the new element, see http://dev.jqueryui.com/ticket/4303 that.selectedList.children('.ui-draggable').each(function() { $(this).removeClass('ui-draggable'); $(this).data('optionLink', ui.item.data('optionLink')); $(this).data('idx', ui.item.data('idx')); that._applyItemState($(this), true); }); // workaround according to http://dev.jqueryui.com/ticket/4088 setTimeout(function() { ui.item.remove(); }, 1); } }); } // set up livesearch if (this.options.searchable) { this._registerSearchEvents(this.availableContainer.find('input.search')); } else { $('.search').hide(); } // batch actions $(".remove-all").click(function() { that._populateLists(that.element.find('option').removeAttr('selected')); return false; }); $(".add-all").click(function() { that._populateLists(that.element.find('option').attr('selected', 'selected')); return false; }); }, destroy: function() { this.element.show(); this.container.remove(); $.widget.prototype.destroy.apply(this, arguments); }, _populateLists: function(options) { this.selectedList.children('.ui-element').remove(); this.availableList.children('.ui-element').remove(); this.count = 0; var that = this; var items = $(options.map(function(i) { var item = that._getOptionNode(this).appendTo(this.selected ? that.selectedList : that.availableList).show(); if (this.selected) that.count += 1; that._applyItemState(item, this.selected); item.data('idx', i); return item[0]; })); // update count this._updateCount(); }, _updateCount: function() { this.selectedContainer.find('span.count').text(this.count+" "+$.ui.multiselect.locale.itemsCount); }, _getOptionNode: function(option) { option = $(option); var node = $('<li class="ui-state-default ui-element" title="'+option.text()+'"><span class="ui-icon"/>'+option.text()+'<a href="#" class="action"><span class="ui-corner-all ui-icon"/></a></li>').hide(); node.data('optionLink', option); return node; }, // clones an item with associated data // didn't find a smarter away around this _cloneWithData: function(clonee) { var clone = clonee.clone(); clone.data('optionLink', clonee.data('optionLink')); clone.data('idx', clonee.data('idx')); return clone; }, _setSelected: function(item, selected) { item.data('optionLink').attr('selected', selected); if (selected) { var selectedItem = this._cloneWithData(item); item[this.options.hide](this.options.animated, function() { $(this).remove(); }); selectedItem.appendTo(this.selectedList).hide()[this.options.show](this.options.animated); this._applyItemState(selectedItem, true); return selectedItem; } else { // look for successor based on initial option index var items = this.availableList.find('li'), comparator = this.options.nodeComparator; var succ = null, i = item.data('idx'), direction = comparator(item, $(items[i])); // TODO: test needed for dynamic list populating if ( direction ) { while (i>=0 && i<items.length) { direction > 0 ? i++ : i--; if ( direction != comparator(item, $(items[i])) ) { // going up, go back one item down, otherwise leave as is succ = items[direction > 0 ? i : i+1]; break; } } } else { succ = items[i]; } var availableItem = this._cloneWithData(item); succ ? availableItem.insertBefore($(succ)) : availableItem.appendTo(this.availableList); item[this.options.hide](this.options.animated, function() { $(this).remove(); }); availableItem.hide()[this.options.show](this.options.animated); this._applyItemState(availableItem, false); return availableItem; } }, _applyItemState: function(item, selected) { if (selected) { if (this.options.sortable) item.children('span').addClass('ui-icon-arrowthick-2-n-s').removeClass('ui-helper-hidden').addClass('ui-icon'); else item.children('span').removeClass('ui-icon-arrowthick-2-n-s').addClass('ui-helper-hidden').removeClass('ui-icon'); item.find('a.action span').addClass('ui-icon-minus').removeClass('ui-icon-plus'); this._registerRemoveEvents(item.find('a.action')); } else { item.children('span').removeClass('ui-icon-arrowthick-2-n-s').addClass('ui-helper-hidden').removeClass('ui-icon'); item.find('a.action span').addClass('ui-icon-plus').removeClass('ui-icon-minus'); this._registerAddEvents(item.find('a.action')); } this._registerHoverEvents(item); }, // taken from John Resig's liveUpdate script _filter: function(list) { var input = $(this); var rows = list.children('li'), cache = rows.map(function(){ return $(this).text().toLowerCase(); }); var term = $.trim(input.val().toLowerCase()), scores = []; if (!term) { rows.show(); } else { rows.hide(); cache.each(function(i) { if (this.indexOf(term)>-1) { scores.push(i); } }); $.each(scores, function() { $(rows[this]).show(); }); } }, _registerHoverEvents: function(elements) { elements.removeClass('ui-state-hover'); elements.mouseover(function() { $(this).addClass('ui-state-hover'); }); elements.mouseout(function() { $(this).removeClass('ui-state-hover'); }); }, _registerAddEvents: function(elements) { var that = this; elements.click(function() { var item = that._setSelected($(this).parent(), true); that.count += 1; that._updateCount(); return false; }) // make draggable .each(function() { $(this).parent().draggable({ connectToSortable: 'ul.selected', helper: function() { var selectedItem = that._cloneWithData($(this)).width($(this).width() - 50); selectedItem.width($(this).width()); return selectedItem; }, appendTo: '.ui-multiselect', containment: '.ui-multiselect', revert: 'invalid' }); }); }, _registerRemoveEvents: function(elements) { var that = this; elements.click(function() { that._setSelected($(this).parent(), false); that.count -= 1; that._updateCount(); return false; }); }, _registerSearchEvents: function(input) { var that = this; input.focus(function() { $(this).addClass('ui-state-active'); }) .blur(function() { $(this).removeClass('ui-state-active'); }) .keypress(function(e) { if (e.keyCode == 13) return false; }) .keyup(function() { that._filter.apply(this, [that.availableList]); }); } }); $.extend($.ui.multiselect, { defaults: { sortable: true, searchable: true, animated: 'fast', show: 'slideDown', hide: 'slideUp', dividerLocation: 0.6, nodeComparator: function(node1,node2) { var text1 = node1.text(), text2 = node2.text(); return text1 == text2 ? 0 : (text1 < text2 ? -1 : 1); } }, locale: { addAll:'Add all', removeAll:'Remove all', itemsCount:'items selected' } }); })(jQuery);
JavaScript
/* ** * formatter for values but most of the values if for jqGrid * Some of this was inspired and based on how YUI does the table datagrid but in jQuery fashion * we are trying to keep it as light as possible * Joshua Burnett josh@9ci.com * http://www.greenbill.com * * Changes from Tony Tomov tony@trirand.com * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl-2.0.html * **/ ;(function($) { $.fmatter = {}; //opts can be id:row id for the row, rowdata:the data for the row, colmodel:the column model for this column //example {id:1234,} $.extend($.fmatter,{ isBoolean : function(o) { return typeof o === 'boolean'; }, isObject : function(o) { return (o && (typeof o === 'object' || $.isFunction(o))) || false; }, isString : function(o) { return typeof o === 'string'; }, isNumber : function(o) { return typeof o === 'number' && isFinite(o); }, isNull : function(o) { return o === null; }, isUndefined : function(o) { return typeof o === 'undefined'; }, isValue : function (o) { return (this.isObject(o) || this.isString(o) || this.isNumber(o) || this.isBoolean(o)); }, isEmpty : function(o) { if(!this.isString(o) && this.isValue(o)) { return false; }else if (!this.isValue(o)){ return true; } o = $.trim(o).replace(/\&nbsp\;/ig,'').replace(/\&#160\;/ig,''); return o===""; } }); $.fn.fmatter = function(formatType, cellval, opts, rwd, act) { // build main options before element iteration var v=cellval; opts = $.extend({}, $.jgrid.formatter, opts); if ($.fn.fmatter[formatType]){ v = $.fn.fmatter[formatType](cellval, opts, rwd, act); } return v; }; $.fmatter.util = { // Taken from YAHOO utils NumberFormat : function(nData,opts) { if(!$.fmatter.isNumber(nData)) { nData *= 1; } if($.fmatter.isNumber(nData)) { var bNegative = (nData < 0); var sOutput = nData + ""; var sDecimalSeparator = (opts.decimalSeparator) ? opts.decimalSeparator : "."; var nDotIndex; if($.fmatter.isNumber(opts.decimalPlaces)) { // Round to the correct decimal place var nDecimalPlaces = opts.decimalPlaces; var nDecimal = Math.pow(10, nDecimalPlaces); sOutput = Math.round(nData*nDecimal)/nDecimal + ""; nDotIndex = sOutput.lastIndexOf("."); if(nDecimalPlaces > 0) { // Add the decimal separator if(nDotIndex < 0) { sOutput += sDecimalSeparator; nDotIndex = sOutput.length-1; } // Replace the "." else if(sDecimalSeparator !== "."){ sOutput = sOutput.replace(".",sDecimalSeparator); } // Add missing zeros while((sOutput.length - 1 - nDotIndex) < nDecimalPlaces) { sOutput += "0"; } } } if(opts.thousandsSeparator) { var sThousandsSeparator = opts.thousandsSeparator; nDotIndex = sOutput.lastIndexOf(sDecimalSeparator); nDotIndex = (nDotIndex > -1) ? nDotIndex : sOutput.length; var sNewOutput = sOutput.substring(nDotIndex); var nCount = -1; for (var i=nDotIndex; i>0; i--) { nCount++; if ((nCount%3 === 0) && (i !== nDotIndex) && (!bNegative || (i > 1))) { sNewOutput = sThousandsSeparator + sNewOutput; } sNewOutput = sOutput.charAt(i-1) + sNewOutput; } sOutput = sNewOutput; } // Prepend prefix sOutput = (opts.prefix) ? opts.prefix + sOutput : sOutput; // Append suffix sOutput = (opts.suffix) ? sOutput + opts.suffix : sOutput; return sOutput; } else { return nData; } }, // Tony Tomov // PHP implementation. Sorry not all options are supported. // Feel free to add them if you want DateFormat : function (format, date, newformat, opts) { var token = /\\.|[dDjlNSwzWFmMntLoYyaABgGhHisueIOPTZcrU]/g, timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g, timezoneClip = /[^-+\dA-Z]/g, msDateRegExp = new RegExp("^/Date\((([-+])?[0-9]+)(([-+])([0-9]{2})([0-9]{2}))?\)/$"), msMatch = date.match(msDateRegExp), pad = function (value, length) { value = String(value); length = parseInt(length,10) || 2; while (value.length < length) { value = '0' + value; } return value; }, ts = {m : 1, d : 1, y : 1970, h : 0, i : 0, s : 0, u:0}, timestamp=0, dM, k,hl, dateFormat=["i18n"]; // Internationalization strings dateFormat.i18n = { dayNames: opts.dayNames, monthNames: opts.monthNames }; if( format in opts.masks ) { format = opts.masks[format]; } if(date.constructor === Number) { timestamp = new Date(date); } else if(date.constructor === Date) { timestamp = date; // Microsoft date format support } else if( msMatch !== null ) { timestamp = new Date(parseInt(msMatch[1], 10)); if (msMatch[3]) { var offset = Number(msMatch[5]) * 60 + Number(msMatch[6]); offset *= ((msMatch[4] == '-') ? 1 : -1); offset -= timestamp.getTimezoneOffset(); timestamp.setTime(Number(Number(timestamp) + (offset * 60 * 1000))); } } else { date = date.split(/[\\\/:_;.,\t\T\s-]/); format = format.split(/[\\\/:_;.,\t\T\s-]/); // parsing for month names for(k=0,hl=format.length;k<hl;k++){ if(format[k] == 'M') { dM = $.inArray(date[k],dateFormat.i18n.monthNames); if(dM !== -1 && dM < 12){date[k] = dM+1;} } if(format[k] == 'F') { dM = $.inArray(date[k],dateFormat.i18n.monthNames); if(dM !== -1 && dM > 11){date[k] = dM+1-12;} } if(date[k]) { ts[format[k].toLowerCase()] = parseInt(date[k],10); } } if(ts.f) { ts.m = ts.f; } if( ts.m === 0 && ts.y === 0 && ts.d === 0) { return "&#160;" ; } ts.m = parseInt(ts.m,10)-1; var ty = ts.y; if (ty >= 70 && ty <= 99) { ts.y = 1900+ts.y; } else if (ty >=0 && ty <=69) { ts.y= 2000+ts.y; } timestamp = new Date(ts.y, ts.m, ts.d, ts.h, ts.i, ts.s, ts.u); } if( newformat in opts.masks ) { newformat = opts.masks[newformat]; } else if ( !newformat ) { newformat = 'Y-m-d'; } var G = timestamp.getHours(), i = timestamp.getMinutes(), j = timestamp.getDate(), n = timestamp.getMonth() + 1, o = timestamp.getTimezoneOffset(), s = timestamp.getSeconds(), u = timestamp.getMilliseconds(), w = timestamp.getDay(), Y = timestamp.getFullYear(), N = (w + 6) % 7 + 1, z = (new Date(Y, n - 1, j) - new Date(Y, 0, 1)) / 86400000, flags = { // Day d: pad(j), D: dateFormat.i18n.dayNames[w], j: j, l: dateFormat.i18n.dayNames[w + 7], N: N, S: opts.S(j), //j < 11 || j > 13 ? ['st', 'nd', 'rd', 'th'][Math.min((j - 1) % 10, 3)] : 'th', w: w, z: z, // Week W: N < 5 ? Math.floor((z + N - 1) / 7) + 1 : Math.floor((z + N - 1) / 7) || ((new Date(Y - 1, 0, 1).getDay() + 6) % 7 < 4 ? 53 : 52), // Month F: dateFormat.i18n.monthNames[n - 1 + 12], m: pad(n), M: dateFormat.i18n.monthNames[n - 1], n: n, t: '?', // Year L: '?', o: '?', Y: Y, y: String(Y).substring(2), // Time a: G < 12 ? opts.AmPm[0] : opts.AmPm[1], A: G < 12 ? opts.AmPm[2] : opts.AmPm[3], B: '?', g: G % 12 || 12, G: G, h: pad(G % 12 || 12), H: pad(G), i: pad(i), s: pad(s), u: u, // Timezone e: '?', I: '?', O: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4), P: '?', T: (String(timestamp).match(timezone) || [""]).pop().replace(timezoneClip, ""), Z: '?', // Full Date/Time c: '?', r: '?', U: Math.floor(timestamp / 1000) }; return newformat.replace(token, function ($0) { return $0 in flags ? flags[$0] : $0.substring(1); }); } }; $.fn.fmatter.defaultFormat = function(cellval, opts) { return ($.fmatter.isValue(cellval) && cellval!=="" ) ? cellval : opts.defaultValue ? opts.defaultValue : "&#160;"; }; $.fn.fmatter.email = function(cellval, opts) { if(!$.fmatter.isEmpty(cellval)) { return "<a href=\"mailto:" + cellval + "\">" + cellval + "</a>"; }else { return $.fn.fmatter.defaultFormat(cellval,opts ); } }; $.fn.fmatter.checkbox =function(cval, opts) { var op = $.extend({},opts.checkbox), ds; if(!$.fmatter.isUndefined(opts.colModel.formatoptions)) { op = $.extend({},op,opts.colModel.formatoptions); } if(op.disabled===true) {ds = "disabled=\"disabled\"";} else {ds="";} if($.fmatter.isEmpty(cval) || $.fmatter.isUndefined(cval) ) { cval = $.fn.fmatter.defaultFormat(cval,op); } cval=cval+""; cval=cval.toLowerCase(); var bchk = cval.search(/(false|0|no|off)/i)<0 ? " checked='checked' " : ""; return "<input type=\"checkbox\" " + bchk + " value=\""+ cval+"\" offval=\"no\" "+ds+ "/>"; }; $.fn.fmatter.link = function(cellval, opts) { var op = {target:opts.target }; var target = ""; if(!$.fmatter.isUndefined(opts.colModel.formatoptions)) { op = $.extend({},op,opts.colModel.formatoptions); } if(op.target) {target = 'target=' + op.target;} if(!$.fmatter.isEmpty(cellval)) { return "<a "+target+" href=\"" + cellval + "\">" + cellval + "</a>"; }else { return $.fn.fmatter.defaultFormat(cellval,opts); } }; $.fn.fmatter.showlink = function(cellval, opts) { var op = {baseLinkUrl: opts.baseLinkUrl,showAction:opts.showAction, addParam: opts.addParam || "", target: opts.target, idName: opts.idName }, target = "", idUrl; if(!$.fmatter.isUndefined(opts.colModel.formatoptions)) { op = $.extend({},op,opts.colModel.formatoptions); } if(op.target) {target = 'target=' + op.target;} idUrl = op.baseLinkUrl+op.showAction + '?'+ op.idName+'='+opts.rowId+op.addParam; if($.fmatter.isString(cellval) || $.fmatter.isNumber(cellval)) { //add this one even if its blank string return "<a "+target+" href=\"" + idUrl + "\">" + cellval + "</a>"; }else { return $.fn.fmatter.defaultFormat(cellval,opts); } }; $.fn.fmatter.integer = function(cellval, opts) { var op = $.extend({},opts.integer); if(!$.fmatter.isUndefined(opts.colModel.formatoptions)) { op = $.extend({},op,opts.colModel.formatoptions); } if($.fmatter.isEmpty(cellval)) { return op.defaultValue; } return $.fmatter.util.NumberFormat(cellval,op); }; $.fn.fmatter.number = function (cellval, opts) { var op = $.extend({},opts.number); if(!$.fmatter.isUndefined(opts.colModel.formatoptions)) { op = $.extend({},op,opts.colModel.formatoptions); } if($.fmatter.isEmpty(cellval)) { return op.defaultValue; } return $.fmatter.util.NumberFormat(cellval,op); }; $.fn.fmatter.currency = function (cellval, opts) { var op = $.extend({},opts.currency); if(!$.fmatter.isUndefined(opts.colModel.formatoptions)) { op = $.extend({},op,opts.colModel.formatoptions); } if($.fmatter.isEmpty(cellval)) { return op.defaultValue; } return $.fmatter.util.NumberFormat(cellval,op); }; $.fn.fmatter.date = function (cellval, opts, rwd, act) { var op = $.extend({},opts.date); if(!$.fmatter.isUndefined(opts.colModel.formatoptions)) { op = $.extend({},op,opts.colModel.formatoptions); } if(!op.reformatAfterEdit && act=='edit'){ return $.fn.fmatter.defaultFormat(cellval, opts); } else if(!$.fmatter.isEmpty(cellval)) { return $.fmatter.util.DateFormat(op.srcformat,cellval,op.newformat,op); } else { return $.fn.fmatter.defaultFormat(cellval, opts); } }; $.fn.fmatter.select = function (cellval,opts, rwd, act) { // jqGrid specific cellval = cellval + ""; var oSelect = false, ret=[]; if(!$.fmatter.isUndefined(opts.colModel.formatoptions)){ oSelect= opts.colModel.formatoptions.value; } else if(!$.fmatter.isUndefined(opts.colModel.editoptions)){ oSelect= opts.colModel.editoptions.value; } if (oSelect) { var msl = opts.colModel.editoptions.multiple === true ? true : false, scell = [], sv; if(msl) {scell = cellval.split(",");scell = $.map(scell,function(n){return $.trim(n);});} if ($.fmatter.isString(oSelect)) { // mybe here we can use some caching with care ???? var so = oSelect.split(";"), j=0; for(var i=0; i<so.length;i++){ sv = so[i].split(":"); if(sv.length > 2 ) { sv[1] = jQuery.map(sv,function(n,i){if(i>0) { return n; } }).join(":"); } if(msl) { if(jQuery.inArray(sv[0],scell)>-1) { ret[j] = sv[1]; j++; } } else if($.trim(sv[0])==$.trim(cellval)) { ret[0] = sv[1]; break; } } } else if($.fmatter.isObject(oSelect)) { // this is quicker if(msl) { ret = jQuery.map(scell, function(n, i){ return oSelect[n]; }); } else { ret[0] = oSelect[cellval] || ""; } } } cellval = ret.join(", "); return cellval === "" ? $.fn.fmatter.defaultFormat(cellval,opts) : cellval; }; $.fn.fmatter.rowactions = function(rid,gid,act,pos) { var op ={ keys:false, editbutton:true, delbutton:true, onEdit : null, onSuccess: null, afterSave:null, onError: null, afterRestore: null, extraparam: {oper:'edit'}, url: null, delOptions: {} }, cm = $('#'+gid)[0].p.colModel[pos]; if(!$.fmatter.isUndefined(cm.formatoptions)) { op = $.extend(op,cm.formatoptions); } var saverow = function( rowid) { if(op.afterSave) op.afterSave(rowid); $("tr#"+rid+" div.ui-inline-edit, "+"tr#"+rid+" div.ui-inline-del","#"+gid).show(); $("tr#"+rid+" div.ui-inline-save, "+"tr#"+rid+" div.ui-inline-cancel","#"+gid).hide(); }, restorerow = function( rowid) { if(op.afterRestore) op.afterRestore(rowid); $("tr#"+rid+" div.ui-inline-edit, "+"tr#"+rid+" div.ui-inline-del","#"+gid).show(); $("tr#"+rid+" div.ui-inline-save, "+"tr#"+rid+" div.ui-inline-cancel","#"+gid).hide(); }; switch(act) { case 'edit': $('#'+gid).jqGrid('editRow',rid, op.keys, op.onEdit, op.onSuccess, op.url, op.extraparam, saverow, op.onError,restorerow); $("tr#"+rid+" div.ui-inline-edit, "+"tr#"+rid+" div.ui-inline-del","#"+gid).hide(); $("tr#"+rid+" div.ui-inline-save, "+"tr#"+rid+" div.ui-inline-cancel","#"+gid).show(); break; case 'save': $('#'+gid).jqGrid('saveRow',rid, op.onSuccess,op.url, op.extraparam, saverow, op.onError,restorerow); $("tr#"+rid+" div.ui-inline-edit, "+"tr#"+rid+" div.ui-inline-del","#"+gid).show(); $("tr#"+rid+" div.ui-inline-save, "+"tr#"+rid+" div.ui-inline-cancel","#"+gid).hide(); break; case 'cancel' : $('#'+gid).jqGrid('restoreRow',rid, restorerow); $("tr#"+rid+" div.ui-inline-edit, "+"tr#"+rid+" div.ui-inline-del","#"+gid).show(); $("tr#"+rid+" div.ui-inline-save, "+"tr#"+rid+" div.ui-inline-cancel","#"+gid).hide(); break; case 'del': $('#'+gid).jqGrid('delGridRow',rid, op.delOptions); break; } }; $.fn.fmatter.actions = function(cellval,opts, rwd) { var op ={keys:false, editbutton:true, delbutton:true}; if(!$.fmatter.isUndefined(opts.colModel.formatoptions)) { op = $.extend(op,opts.colModel.formatoptions); } var rowid = opts.rowId, str="",ocl; if(typeof(rowid) =='undefined' || $.fmatter.isEmpty(rowid)) { return ""; } if(op.editbutton){ ocl = "onclick=$.fn.fmatter.rowactions('"+rowid+"','"+opts.gid+"','edit',"+opts.pos+");"; str =str+ "<div style='margin-left:8px;'><div title='"+$.jgrid.nav.edittitle+"' style='float:left;cursor:pointer;' class='ui-pg-div ui-inline-edit' "+ocl+"><span class='ui-icon ui-icon-pencil'></span></div>"; } if(op.delbutton) { ocl = "onclick=$.fn.fmatter.rowactions('"+rowid+"','"+opts.gid+"','del',"+opts.pos+");"; str = str+"<div title='"+$.jgrid.nav.deltitle+"' style='float:left;margin-left:5px;' class='ui-pg-div ui-inline-del' "+ocl+"><span class='ui-icon ui-icon-trash'></span></div>"; } ocl = "onclick=$.fn.fmatter.rowactions('"+rowid+"','"+opts.gid+"','save',"+opts.pos+");"; str = str+"<div title='"+$.jgrid.edit.bSubmit+"' style='float:left;display:none' class='ui-pg-div ui-inline-save'><span class='ui-icon ui-icon-disk' "+ocl+"></span></div>"; ocl = "onclick=$.fn.fmatter.rowactions('"+rowid+"','"+opts.gid+"','cancel',"+opts.pos+");"; str = str+"<div title='"+$.jgrid.edit.bCancel+"' style='float:left;display:none;margin-left:5px;' class='ui-pg-div ui-inline-cancel'><span class='ui-icon ui-icon-cancel' "+ocl+"></span></div></div>"; return str; }; $.unformat = function (cellval,options,pos,cnt) { // specific for jqGrid only var ret, formatType = options.colModel.formatter, op =options.colModel.formatoptions || {}, sep, re = /([\.\*\_\'\(\)\{\}\+\?\\])/g, unformatFunc = options.colModel.unformat||($.fn.fmatter[formatType] && $.fn.fmatter[formatType].unformat); if(typeof unformatFunc !== 'undefined' && $.isFunction(unformatFunc) ) { ret = unformatFunc($(cellval).text(), options, cellval); } else if(!$.fmatter.isUndefined(formatType) && $.fmatter.isString(formatType) ) { var opts = $.jgrid.formatter || {}, stripTag; switch(formatType) { case 'integer' : op = $.extend({},opts.integer,op); sep = op.thousandsSeparator.replace(re,"\\$1"); stripTag = new RegExp(sep, "g"); ret = $(cellval).text().replace(stripTag,''); break; case 'number' : op = $.extend({},opts.number,op); sep = op.thousandsSeparator.replace(re,"\\$1"); stripTag = new RegExp(sep, "g"); ret = $(cellval).text().replace(stripTag,"").replace(op.decimalSeparator,'.'); break; case 'currency': op = $.extend({},opts.currency,op); sep = op.thousandsSeparator.replace(re,"\\$1"); stripTag = new RegExp(sep, "g"); ret = $(cellval).text().replace(stripTag,'').replace(op.decimalSeparator,'.').replace(op.prefix,'').replace(op.suffix,''); break; case 'checkbox': var cbv = (options.colModel.editoptions) ? options.colModel.editoptions.value.split(":") : ["Yes","No"]; ret = $('input',cellval).attr("checked") ? cbv[0] : cbv[1]; break; case 'select' : ret = $.unformat.select(cellval,options,pos,cnt); break; case 'actions': return ""; default: ret= $(cellval).text(); } } return ret ? ret : cnt===true ? $(cellval).text() : $.jgrid.htmlDecode($(cellval).html()); }; $.unformat.select = function (cellval,options,pos,cnt) { // Spacial case when we have local data and perform a sort // cnt is set to true only in sortDataArray var ret = []; var cell = $(cellval).text(); if(cnt===true) { return cell; } var op = $.extend({},options.colModel.editoptions); if(op.value){ var oSelect = op.value, msl = op.multiple === true ? true : false, scell = [], sv; if(msl) { scell = cell.split(","); scell = $.map(scell,function(n){return $.trim(n);}); } if ($.fmatter.isString(oSelect)) { var so = oSelect.split(";"), j=0; for(var i=0; i<so.length;i++){ sv = so[i].split(":"); if(sv.length > 2 ) { sv[1] = jQuery.map(sv,function(n,i){if(i>0) { return n; } }).join(":"); } if(msl) { if(jQuery.inArray(sv[1],scell)>-1) { ret[j] = sv[0]; j++; } } else if($.trim(sv[1])==$.trim(cell)) { ret[0] = sv[0]; break; } } } else if($.fmatter.isObject(oSelect) || $.isArray(oSelect) ){ if(!msl) { scell[0] = cell; } ret = jQuery.map(scell, function(n){ var rv; $.each(oSelect, function(i,val){ if (val == n) { rv = i; return false; } }); if( typeof(rv) != 'undefined' ) { return rv; } }); } return ret.join(", "); } else { return cell || ""; } }; $.unformat.date = function (cellval, opts) { var op = $.jgrid.formatter.date || {}; if(!$.fmatter.isUndefined(opts.formatoptions)) { op = $.extend({},op,opts.formatoptions); } if(!$.fmatter.isEmpty(cellval)) { return $.fmatter.util.DateFormat(op.newformat,cellval,op.srcformat,op); } else { return $.fn.fmatter.defaultFormat(cellval, opts); } }; })(jQuery);
JavaScript
/* * jqDnR - Minimalistic Drag'n'Resize for jQuery. * * Copyright (c) 2007 Brice Burgess <bhb@iceburg.net>, http://www.iceburg.net * Licensed under the MIT License: * http://www.opensource.org/licenses/mit-license.php * * $Version: 2007.08.19 +r2 */ (function($){ $.fn.jqDrag=function(h){return i(this,h,'d');}; $.fn.jqResize=function(h,ar){return i(this,h,'r',ar);}; $.jqDnR={ dnr:{}, e:0, drag:function(v){ if(M.k == 'd')E.css({left:M.X+v.pageX-M.pX,top:M.Y+v.pageY-M.pY}); else { E.css({width:Math.max(v.pageX-M.pX+M.W,0),height:Math.max(v.pageY-M.pY+M.H,0)}); if(M1){E1.css({width:Math.max(v.pageX-M1.pX+M1.W,0),height:Math.max(v.pageY-M1.pY+M1.H,0)});} } return false; }, stop:function(){ //E.css('opacity',M.o); $(document).unbind('mousemove',J.drag).unbind('mouseup',J.stop); } }; var J=$.jqDnR,M=J.dnr,E=J.e,E1, i=function(e,h,k,aR){ return e.each(function(){ h=(h)?$(h,e):e; h.bind('mousedown',{e:e,k:k},function(v){ var d=v.data,p={};E=d.e;E1 = aR ? $(aR) : false; // attempt utilization of dimensions plugin to fix IE issues if(E.css('position') != 'relative'){try{E.position(p);}catch(e){}} M={ X:p.left||f('left')||0, Y:p.top||f('top')||0, W:f('width')||E[0].scrollWidth||0, H:f('height')||E[0].scrollHeight||0, pX:v.pageX, pY:v.pageY, k:d.k //o:E.css('opacity') }; // also resize if(E1 && d.k != 'd'){ M1={ X:p.left||f1('left')||0, Y:p.top||f1('top')||0, W:E1[0].offsetWidth||f1('width')||0, H:E1[0].offsetHeight||f1('height')||0, pX:v.pageX, pY:v.pageY, k:d.k }; } else {M1 = false;} //E.css({opacity:0.8}); try {$("input.hasDatepicker",E[0]).datepicker('hide');}catch (dpe){} $(document).mousemove($.jqDnR.drag).mouseup($.jqDnR.stop); return false; }); }); }, f=function(k){return parseInt(E.css(k))||false;}; f1=function(k){ return parseInt(E1.css(k))||false;}; })(jQuery);
JavaScript
;(function($){ /** * jqGrid extension for manipulating Grid Data * Tony Tomov tony@trirand.com * http://trirand.com/blog/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl-2.0.html **/ $.jgrid.extend({ //Editing editRow : function(rowid,keys,oneditfunc,succesfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc) { return this.each(function(){ var $t = this, nm, tmp, editable, cnt=0, focus=null, svr={}, ind,cm; if (!$t.grid ) { return; } ind = $($t).jqGrid("getInd",rowid,true); if( ind === false ) {return;} editable = $(ind).attr("editable") || "0"; if (editable == "0" && !$(ind).hasClass("not-editable-row")) { cm = $t.p.colModel; $('td',ind).each( function(i) { nm = cm[i].name; var treeg = $t.p.treeGrid===true && nm == $t.p.ExpandColumn; if(treeg) { tmp = $("span:first",this).html();} else { try { tmp = $.unformat(this,{rowId:rowid, colModel:cm[i]},i); } catch (_) { tmp = $(this).html(); } } if ( nm != 'cb' && nm != 'subgrid' && nm != 'rn') { if($t.p.autoencode) { tmp = $.jgrid.htmlDecode(tmp); } svr[nm]=tmp; if(cm[i].editable===true) { if(focus===null) { focus = i; } if (treeg) { $("span:first",this).html(""); } else { $(this).html(""); } var opt = $.extend({},cm[i].editoptions || {},{id:rowid+"_"+nm,name:nm}); if(!cm[i].edittype) { cm[i].edittype = "text"; } var elc = $.jgrid.createEl(cm[i].edittype,opt,tmp,true,$.extend({},$.jgrid.ajaxOptions,$t.p.ajaxSelectOptions || {})); $(elc).addClass("editable"); if(treeg) { $("span:first",this).append(elc); } else { $(this).append(elc); } //Again IE if(cm[i].edittype == "select" && cm[i].editoptions.multiple===true && $.browser.msie) { $(elc).width($(elc).width()); } cnt++; } } }); if(cnt > 0) { svr.id = rowid; $t.p.savedRow.push(svr); $(ind).attr("editable","1"); $("td:eq("+focus+") input",ind).focus(); if(keys===true) { $(ind).bind("keydown",function(e) { if (e.keyCode === 27) {$($t).jqGrid("restoreRow",rowid, afterrestorefunc);} if (e.keyCode === 13) { var ta = e.target; if(ta.tagName == 'TEXTAREA') { return true; } $($t).jqGrid("saveRow",rowid,succesfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc ); return false; } e.stopPropagation(); }); } if( $.isFunction(oneditfunc)) { oneditfunc.call($t, rowid); } } } }); }, saveRow : function(rowid, succesfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc) { return this.each(function(){ var $t = this, nm, tmp={}, tmp2={}, editable, fr, cv, ind; if (!$t.grid ) { return; } ind = $($t).jqGrid("getInd",rowid,true); if(ind === false) {return;} editable = $(ind).attr("editable"); url = url ? url : $t.p.editurl; if (editable==="1") { var cm; $("td",ind).each(function(i) { cm = $t.p.colModel[i]; nm = cm.name; if ( nm != 'cb' && nm != 'subgrid' && cm.editable===true && nm != 'rn') { switch (cm.edittype) { case "checkbox": var cbv = ["Yes","No"]; if(cm.editoptions ) { cbv = cm.editoptions.value.split(":"); } tmp[nm]= $("input",this).attr("checked") ? cbv[0] : cbv[1]; break; case 'text': case 'password': case 'textarea': case "button" : tmp[nm]=$("input, textarea",this).val(); break; case 'select': if(!cm.editoptions.multiple) { tmp[nm] = $("select>option:selected",this).val(); tmp2[nm] = $("select>option:selected", this).text(); } else { var sel = $("select",this), selectedText = []; tmp[nm] = $(sel).val(); if(tmp[nm]) { tmp[nm]= tmp[nm].join(","); } else { tmp[nm] =""; } $("select > option:selected",this).each( function(i,selected){ selectedText[i] = $(selected).text(); } ); tmp2[nm] = selectedText.join(","); } if(cm.formatter && cm.formatter == 'select') { tmp2={}; } break; case 'custom' : try { if(cm.editoptions && $.isFunction(cm.editoptions.custom_value)) { tmp[nm] = cm.editoptions.custom_value.call($t, $(".customelement",this),'get'); if (tmp[nm] === undefined) { throw "e2"; } } else { throw "e1"; } } catch (e) { if (e=="e1") { $.jgrid.info_dialog(jQuery.jgrid.errors.errcap,"function 'custom_value' "+$.jgrid.edit.msg.nodefined,jQuery.jgrid.edit.bClose); } if (e=="e2") { $.jgrid.info_dialog(jQuery.jgrid.errors.errcap,"function 'custom_value' "+$.jgrid.edit.msg.novalue,jQuery.jgrid.edit.bClose); } else { $.jgrid.info_dialog(jQuery.jgrid.errors.errcap,e.message,jQuery.jgrid.edit.bClose); } } break; } cv = $.jgrid.checkValues(tmp[nm],i,$t); if(cv[0] === false) { cv[1] = tmp[nm] + " " + cv[1]; return false; } if($t.p.autoencode) { tmp[nm] = $.jgrid.htmlEncode(tmp[nm]); } } }); if (cv[0] === false){ try { var positions = $.jgrid.findPos($("#"+$.jgrid.jqID(rowid), $t.grid.bDiv)[0]); $.jgrid.info_dialog($.jgrid.errors.errcap,cv[1],$.jgrid.edit.bClose,{left:positions[0],top:positions[1]}); } catch (e) { alert(cv[1]); } return; } if(tmp) { var idname, opers, oper; opers = $t.p.prmNames; oper = opers.oper; idname = opers.id; tmp[oper] = opers.editoper; tmp[idname] = rowid; if(typeof($t.p.inlineData) == 'undefined') { $t.p.inlineData ={}; } if(typeof(extraparam) == 'undefined') { extraparam ={}; } tmp = $.extend({},tmp,$t.p.inlineData,extraparam); } if (url == 'clientArray') { tmp = $.extend({},tmp, tmp2); if($t.p.autoencode) { $.each(tmp,function(n,v){ tmp[n] = $.jgrid.htmlDecode(v); }); } var resp = $($t).jqGrid("setRowData",rowid,tmp); $(ind).attr("editable","0"); for( var k=0;k<$t.p.savedRow.length;k++) { if( $t.p.savedRow[k].id == rowid) {fr = k; break;} } if(fr >= 0) { $t.p.savedRow.splice(fr,1); } if( $.isFunction(aftersavefunc) ) { aftersavefunc.call($t, rowid,resp); } } else { $("#lui_"+$t.p.id).show(); $.ajax($.extend({ url:url, data: $.isFunction($t.p.serializeRowData) ? $t.p.serializeRowData.call($t, tmp) : tmp, type: "POST", complete: function(res,stat){ $("#lui_"+$t.p.id).hide(); if (stat === "success"){ var ret; if( $.isFunction(succesfunc)) { ret = succesfunc.call($t, res);} else { ret = true; } if (ret===true) { if($t.p.autoencode) { $.each(tmp,function(n,v){ tmp[n] = $.jgrid.htmlDecode(v); }); } tmp = $.extend({},tmp, tmp2); $($t).jqGrid("setRowData",rowid,tmp); $(ind).attr("editable","0"); for( var k=0;k<$t.p.savedRow.length;k++) { if( $t.p.savedRow[k].id == rowid) {fr = k; break;} } if(fr >= 0) { $t.p.savedRow.splice(fr,1); } if( $.isFunction(aftersavefunc) ) { aftersavefunc.call($t, rowid,res); } } else { if($.isFunction(errorfunc) ) { errorfunc.call($t, rowid, res, stat); } $($t).jqGrid("restoreRow",rowid, afterrestorefunc); } } }, error:function(res,stat){ $("#lui_"+$t.p.id).hide(); if($.isFunction(errorfunc) ) { errorfunc.call($t, rowid, res, stat); } else { alert("Error Row: "+rowid+" Result: " +res.status+":"+res.statusText+" Status: "+stat); } $($t).jqGrid("restoreRow",rowid, afterrestorefunc); } }, $.jgrid.ajaxOptions, $t.p.ajaxRowOptions || {})); } $(ind).unbind("keydown"); } }); }, restoreRow : function(rowid, afterrestorefunc) { return this.each(function(){ var $t= this, fr, ind, ares={}; if (!$t.grid ) { return; } ind = $($t).jqGrid("getInd",rowid,true); if(ind === false) {return;} for( var k=0;k<$t.p.savedRow.length;k++) { if( $t.p.savedRow[k].id == rowid) {fr = k; break;} } if(fr >= 0) { if($.isFunction($.fn.datepicker)) { try { $("input.hasDatepicker","#"+$.jgrid.jqID(ind.id)).datepicker('hide'); } catch (e) {} } $.each($t.p.colModel, function(i,n){ if(this.editable === true && this.name in $t.p.savedRow[fr]) { ares[this.name] = $t.p.savedRow[fr][this.name]; } }); $($t).jqGrid("setRowData",rowid,ares); $(ind).attr("editable","0").unbind("keydown"); $t.p.savedRow.splice(fr,1); } if ($.isFunction(afterrestorefunc)) { afterrestorefunc.call($t, rowid); } }); } //end inline edit }); })(jQuery);
JavaScript
;(function($){ /** * jqGrid extension for form editing Grid Data * Tony Tomov tony@trirand.com * http://trirand.com/blog/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl-2.0.html **/ var rp_ge = null; $.jgrid.extend({ searchGrid : function (p) { p = $.extend({ recreateFilter: false, drag: true, sField:'searchField', sValue:'searchString', sOper: 'searchOper', sFilter: 'filters', loadDefaults: true, // this options activates loading of default filters from grid's postData for Multipe Search only. beforeShowSearch: null, afterShowSearch : null, onInitializeSearch: null, closeAfterSearch : false, closeAfterReset: false, closeOnEscape : false, multipleSearch : false, cloneSearchRowOnAdd: true, // translation // if you want to change or remove the order change it in sopt // ['bw','eq','ne','lt','le','gt','ge','ew','cn'] sopt: null, // Note: stringResult is intentionally declared "undefined by default". // you are velcome to define stringResult expressly in the options you pass to searchGrid() // stringResult is a "safeguard" measure to insure we post sensible data when communicated as form-encoded // see http://github.com/tonytomov/jqGrid/issues/#issue/36 // // If this value is not expressly defined in the incoming options, // lower in the code we will infer the value based on value of multipleSearch stringResult: undefined, onClose : null, // useDataProxy allows ADD, EDIT and DEL code to bypass calling $.ajax // directly when grid's 'dataProxy' property (grid.p.dataProxy) is a function. // Used for "editGridRow" and "delGridRow" below and automatically flipped to TRUE // when ajax setting's 'url' (grid's 'editurl') property is undefined. // When 'useDataProxy' is true, instead of calling $.ajax.call(gridDOMobj, o, i) we call // gridDOMobj.p.dataProxy.call(gridDOMobj, o, i) // // Behavior is extremely similar to when 'datatype' is a function, but arguments are slightly different. // Normally the following is fed to datatype.call(a, b, c): // a = Pointer to grid's table DOM element, b = grid.p.postdata, c = "load_"+grid's ID // In cases of "edit" and "del" the following is fed: // a = Pointer to grid's table DOM element (same), // b = extended Ajax Options including postdata in "data" property. (different object type) // c = "set_"+grid's ID in case of "edit" and "del_"+grid's ID in case of "del" (same type, different content) // The major difference is that complete ajax options object, with attached "complete" and "error" // callback functions is fed instead of only post data. // This allows you to emulate a $.ajax call (including calling "complete"/"error"), // while retrieving the data locally in the browser. useDataProxy: false, overlay : true }, $.jgrid.search, p || {}); return this.each(function() { var $t = this; if(!$t.grid) {return;} var fid = "fbox_"+$t.p.id, showFrm = true; function applyDefaultFilters(gridDOMobj, filterSettings) { /* gridDOMobj = ointer to grid DOM object ( $(#list)[0] ) What we need from gridDOMobj: gridDOMobj.SearchFilter is the pointer to the Search box, once it's created. gridDOMobj.p.postData - dictionary of post settings. These can be overriden at grid creation to contain default filter settings. We will parse these and will populate the search with defaults. filterSettings - same settings object you (would) pass to $().jqGrid('searchGrid', filterSettings); */ // Pulling default filter settings out of postData property of grid's properties.: var defaultFilters = gridDOMobj.p.postData[filterSettings.sFilter]; // example of what we might get: {"groupOp":"and","rules":[{"field":"amount","op":"eq","data":"100"}]} // suppose we have imported this with grid import, the this is a string. if(typeof(defaultFilters) == "string") { defaultFilters = $.jgrid.parse(defaultFilters); } if (defaultFilters) { if (defaultFilters.groupOp) { gridDOMobj.SearchFilter.setGroupOp(defaultFilters.groupOp); } if (defaultFilters.rules) { var f, i = 0, li = defaultFilters.rules.length, success = false; for (; i < li; i++) { f = defaultFilters.rules[i]; // we are not trying to counter all issues with filter declaration here. Just the basics to avoid lookup exceptions. if (f.field !== undefined && f.op !== undefined && f.data !== undefined) { success = gridDOMobj.SearchFilter.setFilter({ 'sfref':gridDOMobj.SearchFilter.$.find(".sf:last"), 'filter':$.extend({},f) }); if (success) { gridDOMobj.SearchFilter.add(); } } } } } } // end of applyDefaultFilters function hideFilter(selector) { if(p.onClose){ var fclm = p.onClose(selector); if(typeof fclm == 'boolean' && !fclm) { return; } } selector.hide(); if(p.overlay === true) { $(".jqgrid-overlay:first","#gbox_"+$t.p.id).hide(); } } function showFilter(){ var fl = $(".ui-searchFilter").length; if(fl > 1) { var zI = $("#"+fid).css("zIndex"); $("#"+fid).css({zIndex:parseInt(zI,10)+fl}); } $("#"+fid).show(); if(p.overlay === true) { $(".jqgrid-overlay:first","#gbox_"+$t.p.id).show(); } try{$(':input:visible',"#"+fid)[0].focus();}catch(_){} } function searchFilters(filters) { var hasFilters = (filters !== undefined), grid = $("#"+$t.p.id), sdata={}; if(p.multipleSearch===false) { sdata[p.sField] = filters.rules[0].field; sdata[p.sValue] = filters.rules[0].data; sdata[p.sOper] = filters.rules[0].op; } else { sdata[p.sFilter] = filters; } grid[0].p.search = hasFilters; $.extend(grid[0].p.postData,sdata); grid.trigger("reloadGrid",[{page:1}]); if(p.closeAfterSearch) { hideFilter($("#"+fid)); } } function resetFilters(op) { var reload = op && op.hasOwnProperty("reload") ? op.reload : true, grid = $("#"+$t.p.id), sdata={}; grid[0].p.search = false; if(p.multipleSearch===false) { sdata[p.sField] = sdata[p.sValue] = sdata[p.sOper] = ""; } else { sdata[p.sFilter] = ""; } $.extend(grid[0].p.postData,sdata); if(reload) { grid.trigger("reloadGrid",[{page:1}]); } if(p.closeAfterReset) { hideFilter($("#"+fid)); } } if($.fn.searchFilter) { if(p.recreateFilter===true) {$("#"+fid).remove();} if( $("#"+fid).html() != null ) { if ( $.isFunction(p.beforeShowSearch) ) { showFrm = p.beforeShowSearch($("#"+fid)); if(typeof(showFrm) == "undefined") { showFrm = true; } } if(showFrm === false) { return; } showFilter(); if( $.isFunction(p.afterShowSearch) ) { p.afterShowSearch($("#"+fid)); } } else { var fields = [], colNames = $("#"+$t.p.id).jqGrid("getGridParam","colNames"), colModel = $("#"+$t.p.id).jqGrid("getGridParam","colModel"), stempl = ['eq','ne','lt','le','gt','ge','bw','bn','in','ni','ew','en','cn','nc'], j,pos,k,oprtr=[]; if (p.sopt !==null) { k=0; for(j=0;j<p.sopt.length;j++) { if( (pos= $.inArray(p.sopt[j],stempl)) != -1 ){ oprtr[k] = {op:p.sopt[j],text: p.odata[pos]}; k++; } } } else { for(j=0;j<stempl.length;j++) { oprtr[j] = {op:stempl[j],text: p.odata[j]}; } } $.each(colModel, function(i, v) { var searchable = (typeof v.search === 'undefined') ? true: v.search , hidden = (v.hidden === true), soptions = $.extend({}, {text: colNames[i], itemval: v.index || v.name}, this.searchoptions), ignoreHiding = (soptions.searchhidden === true); if(typeof soptions.sopt !== 'undefined') { k=0; soptions.ops =[]; if(soptions.sopt.length>0) { for(j=0;j<soptions.sopt.length;j++) { if( (pos= $.inArray(soptions.sopt[j],stempl)) != -1 ){ soptions.ops[k] = {op:soptions.sopt[j],text: p.odata[pos]}; k++; } } } } if(typeof(this.stype) === 'undefined') { this.stype='text'; } if(this.stype == 'select') { if ( soptions.dataUrl !== undefined) {} else { var eov; if(soptions.value) { eov = soptions.value; } else if(this.editoptions) { eov = this.editoptions.value; } if(eov) { soptions.dataValues =[]; if(typeof(eov) === 'string') { var so = eov.split(";"),sv; for(j=0;j<so.length;j++) { sv = so[j].split(":"); soptions.dataValues[j] ={value:sv[0],text:sv[1]}; } } else if (typeof(eov) === 'object') { j=0; for (var key in eov) { if(eov.hasOwnProperty(key)) { soptions.dataValues[j] ={value:key,text:eov[key]}; j++; } } } } } } if ((ignoreHiding && searchable) || (searchable && !hidden)) { fields.push(soptions); } }); if(fields.length>0){ $("<div id='"+fid+"' role='dialog' tabindex='-1'></div>").insertBefore("#gview_"+$t.p.id); // Before we create searchFilter we need to decide if we want to get back a string or a JS object. // see http://github.com/tonytomov/jqGrid/issues/#issue/36 for background on the issue. // If p.stringResult is defined, it was explisitly passed to us by user. Honor the choice, whatever it is. if (p.stringResult===undefined) { // to provide backward compatibility, inferring stringResult value from multipleSearch p.stringResult = p.multipleSearch; } // we preserve the return value here to retain access to .add() and other good methods of search form. $t.SearchFilter = $("#"+fid).searchFilter(fields, { groupOps: p.groupOps, operators: oprtr, onClose:hideFilter, resetText: p.Reset, searchText: p.Find, windowTitle: p.caption, rulesText:p.rulesText, matchText:p.matchText, onSearch: searchFilters, onReset: resetFilters,stringResult:p.stringResult, ajaxSelectOptions: $.extend({},$.jgrid.ajaxOptions,$t.p.ajaxSelectOptions ||{}), clone: p.cloneSearchRowOnAdd }); $(".ui-widget-overlay","#"+fid).remove(); if($t.p.direction=="rtl") { $(".ui-closer","#"+fid).css("float","left"); } if (p.drag===true) { $("#"+fid+" table thead tr:first td:first").css('cursor','move'); if(jQuery.fn.jqDrag) { $("#"+fid).jqDrag($("#"+fid+" table thead tr:first td:first")); } else { try { $("#"+fid).draggable({handle: $("#"+fid+" table thead tr:first td:first")}); } catch (e) {} } } if(p.multipleSearch === false) { $(".ui-del, .ui-add, .ui-del, .ui-add-last, .matchText, .rulesText", "#"+fid).hide(); $("select[name='groupOp']","#"+fid).hide(); } if (p.multipleSearch === true && p.loadDefaults === true) { applyDefaultFilters($t, p); } if ( $.isFunction(p.onInitializeSearch) ) { p.onInitializeSearch( $("#"+fid) ); } if ( $.isFunction(p.beforeShowSearch) ) { showFrm = p.beforeShowSearch($("#"+fid)); if(typeof(showFrm) == "undefined") { showFrm = true; } } if(showFrm === false) { return; } showFilter(); if( $.isFunction(p.afterShowSearch) ) { p.afterShowSearch($("#"+fid)); } if(p.closeOnEscape===true){ $("#"+fid).keydown( function( e ) { if( e.which == 27 ) { hideFilter($("#"+fid)); } if (e.which == 13) { $(".ui-search", this).click(); } }); } } } } }); }, editGridRow : function(rowid, p){ p = $.extend({ top : 0, left: 0, width: 300, height: 'auto', dataheight: 'auto', modal: false, overlay : 10, drag: true, resize: true, url: null, mtype : "POST", clearAfterAdd :true, closeAfterEdit : false, reloadAfterSubmit : true, onInitializeForm: null, beforeInitData: null, beforeShowForm: null, afterShowForm: null, beforeSubmit: null, afterSubmit: null, onclickSubmit: null, afterComplete: null, onclickPgButtons : null, afterclickPgButtons: null, editData : {}, recreateForm : false, jqModal : true, closeOnEscape : false, addedrow : "first", topinfo : '', bottominfo: '', saveicon : [], closeicon : [], savekey: [false,13], navkeys: [false,38,40], checkOnSubmit : false, checkOnUpdate : false, _savedData : {}, processing : false, onClose : null, ajaxEditOptions : {}, serializeEditData : null, viewPagerButtons : true }, $.jgrid.edit, p || {}); rp_ge = p; return this.each(function(){ var $t = this; if (!$t.grid || !rowid) { return; } var gID = $t.p.id, frmgr = "FrmGrid_"+gID,frmtb = "TblGrid_"+gID, IDs = {themodal:'editmod'+gID,modalhead:'edithd'+gID,modalcontent:'editcnt'+gID, scrollelm : frmgr}, onBeforeShow = $.isFunction(rp_ge.beforeShowForm) ? rp_ge.beforeShowForm : false, onAfterShow = $.isFunction(rp_ge.afterShowForm) ? rp_ge.afterShowForm : false, onBeforeInit = $.isFunction(rp_ge.beforeInitData) ? rp_ge.beforeInitData : false, onInitializeForm = $.isFunction(rp_ge.onInitializeForm) ? rp_ge.onInitializeForm : false, copydata = null, showFrm = true, maxCols = 1, maxRows=0, postdata, extpost, newData, diff; if (rowid=="new") { rowid = "_empty"; p.caption=p.addCaption; } else { p.caption=p.editCaption; } if(p.recreateForm===true && $("#"+IDs.themodal).html() != null) { $("#"+IDs.themodal).remove(); } var closeovrl = true; if(p.checkOnUpdate && p.jqModal && !p.modal) { closeovrl = false; } function getFormData(){ $(".FormElement", "#"+frmtb).each(function(i) { var celm = $(".customelement", this); if (celm.length) { var elem = celm[0], nm = $(elem).attr('name'); $.each($t.p.colModel, function(i,n){ if(this.name == nm && this.editoptions && $.isFunction(this.editoptions.custom_value)) { try { postdata[nm] = this.editoptions.custom_value($("#"+nm,"#"+frmtb),'get'); if (postdata[nm] === undefined) { throw "e1"; } } catch (e) { if (e=="e1") { $.jgrid.info_dialog(jQuery.jgrid.errors.errcap,"function 'custom_value' "+$.jgrid.edit.msg.novalue,jQuery.jgrid.edit.bClose);} else { $.jgrid.info_dialog(jQuery.jgrid.errors.errcap,e.message,jQuery.jgrid.edit.bClose); } } return true; } }); } else { switch ($(this).get(0).type) { case "checkbox": if($(this).attr("checked")) { postdata[this.name]= $(this).val(); }else { var ofv = $(this).attr("offval"); postdata[this.name]= ofv; } break; case "select-one": postdata[this.name]= $("option:selected",this).val(); extpost[this.name]= $("option:selected",this).text(); break; case "select-multiple": postdata[this.name]= $(this).val(); if(postdata[this.name]) { postdata[this.name] = postdata[this.name].join(","); } else { postdata[this.name] =""; } var selectedText = []; $("option:selected",this).each( function(i,selected){ selectedText[i] = $(selected).text(); } ); extpost[this.name]= selectedText.join(","); break; case "password": case "text": case "textarea": case "button": postdata[this.name] = $(this).val(); break; } if($t.p.autoencode) { postdata[this.name] = $.jgrid.htmlEncode(postdata[this.name]); } } }); return true; } function createData(rowid,obj,tb,maxcols){ var nm, hc,trdata, cnt=0,tmp, dc,elc, retpos=[], ind=false, tdtmpl = "<td class='CaptionTD'>&#160;</td><td class='DataTD'>&#160;</td>", tmpl=""; //*2 for (var i =1;i<=maxcols;i++) { tmpl += tdtmpl; } if(rowid != '_empty') { ind = $(obj).jqGrid("getInd",rowid); } $(obj.p.colModel).each( function(i) { nm = this.name; // hidden fields are included in the form if(this.editrules && this.editrules.edithidden === true) { hc = false; } else { hc = this.hidden === true ? true : false; } dc = hc ? "style='display:none'" : ""; if ( nm !== 'cb' && nm !== 'subgrid' && this.editable===true && nm !== 'rn') { if(ind === false) { tmp = ""; } else { if(nm == obj.p.ExpandColumn && obj.p.treeGrid === true) { tmp = $("td:eq("+i+")",obj.rows[ind]).text(); } else { try { tmp = $.unformat($("td:eq("+i+")",obj.rows[ind]),{rowId:rowid, colModel:this},i); } catch (_) { tmp = $("td:eq("+i+")",obj.rows[ind]).html(); } } } var opt = $.extend({}, this.editoptions || {} ,{id:nm,name:nm}), frmopt = $.extend({}, {elmprefix:'',elmsuffix:'',rowabove:false,rowcontent:''}, this.formoptions || {}), rp = parseInt(frmopt.rowpos,10) || cnt+1, cp = parseInt((parseInt(frmopt.colpos,10) || 1)*2,10); if(rowid == "_empty" && opt.defaultValue ) { tmp = $.isFunction(opt.defaultValue) ? opt.defaultValue() : opt.defaultValue; } if(!this.edittype) { this.edittype = "text"; } if($t.p.autoencode) { tmp = $.jgrid.htmlDecode(tmp); } elc = $.jgrid.createEl(this.edittype,opt,tmp,false,$.extend({},$.jgrid.ajaxOptions,obj.p.ajaxSelectOptions || {})); if(tmp === "" && this.edittype == "checkbox") {tmp = $(elc).attr("offval");} if(tmp === "" && this.edittype == "select") {tmp = $("option:eq(0)",elc).text();} if(rp_ge.checkOnSubmit || rp_ge.checkOnUpdate) { rp_ge._savedData[nm] = tmp; } $(elc).addClass("FormElement"); if(this.edittype == 'text' || this.edittype == 'textarea') { $(elc).addClass("ui-widget-content ui-corner-all"); } trdata = $(tb).find("tr[rowpos="+rp+"]"); if(frmopt.rowabove) { var newdata = $("<tr><td class='contentinfo' colspan='"+(maxcols*2)+"'>"+frmopt.rowcontent+"</td></tr>"); $(tb).append(newdata); newdata[0].rp = rp; } if ( trdata.length===0 ) { trdata = $("<tr "+dc+" rowpos='"+rp+"'></tr>").addClass("FormData").attr("id","tr_"+nm); $(trdata).append(tmpl); $(tb).append(trdata); trdata[0].rp = rp; } $("td:eq("+(cp-2)+")",trdata[0]).html( typeof frmopt.label === 'undefined' ? obj.p.colNames[i]: frmopt.label); $("td:eq("+(cp-1)+")",trdata[0]).append(frmopt.elmprefix).append(elc).append(frmopt.elmsuffix); retpos[cnt] = i; cnt++; } }); if( cnt > 0) { var idrow = $("<tr class='FormData' style='display:none'><td class='CaptionTD'></td><td colspan='"+ (maxcols*2-1)+"' class='DataTD'><input class='FormElement' id='id_g' type='text' name='"+obj.p.id+"_id' value='"+rowid+"'/></td></tr>"); idrow[0].rp = cnt+999; $(tb).append(idrow); if(rp_ge.checkOnSubmit || rp_ge.checkOnUpdate) { rp_ge._savedData[obj.p.id+"_id"] = rowid; } } return retpos; } function fillData(rowid,obj,fmid){ var nm,cnt=0,tmp, fld,opt,vl,vlc; if(rp_ge.checkOnSubmit || rp_ge.checkOnUpdate) {rp_ge._savedData = {};rp_ge._savedData[obj.p.id+"_id"]=rowid;} var cm = obj.p.colModel; if(rowid == '_empty') { $(cm).each(function(i){ nm = this.name; opt = $.extend({}, this.editoptions || {} ); fld = $("#"+$.jgrid.jqID(nm),"#"+fmid); if(fld[0] != null) { vl = ""; if(opt.defaultValue ) { vl = $.isFunction(opt.defaultValue) ? opt.defaultValue() : opt.defaultValue; if(fld[0].type=='checkbox') { vlc = vl.toLowerCase(); if(vlc.search(/(false|0|no|off|undefined)/i)<0 && vlc!=="") { fld[0].checked = true; fld[0].defaultChecked = true; fld[0].value = vl; } else { fld.attr({checked:"",defaultChecked:""}); } } else {fld.val(vl); } } else { if( fld[0].type=='checkbox' ) { fld[0].checked = false; fld[0].defaultChecked = false; vl = $(fld).attr("offval"); } else if (fld[0].type && fld[0].type.substr(0,6)=='select') { fld[0].selectedIndex = 0; } else { fld.val(vl); } } if(rp_ge.checkOnSubmit===true || rp_ge.checkOnUpdate) { rp_ge._savedData[nm] = vl; } } }); $("#id_g","#"+fmid).val(rowid); return; } var tre = $(obj).jqGrid("getInd",rowid,true); if(!tre) { return; } $('td',tre).each( function(i) { nm = cm[i].name; // hidden fields are included in the form if ( nm !== 'cb' && nm !== 'subgrid' && nm !== 'rn' && cm[i].editable===true) { if(nm == obj.p.ExpandColumn && obj.p.treeGrid === true) { tmp = $(this).text(); } else { try { tmp = $.unformat($(this),{rowId:rowid, colModel:cm[i]},i); } catch (_) { tmp = $(this).html(); } } if($t.p.autoencode) { tmp = $.jgrid.htmlDecode(tmp); } if(rp_ge.checkOnSubmit===true || rp_ge.checkOnUpdate) { rp_ge._savedData[nm] = tmp; } nm = $.jgrid.jqID(nm); switch (cm[i].edittype) { case "password": case "text": case "button" : case "image": $("#"+nm,"#"+fmid).val(tmp); break; case "textarea": if(tmp == "&nbsp;" || tmp == "&#160;" || (tmp.length==1 && tmp.charCodeAt(0)==160) ) {tmp='';} $("#"+nm,"#"+fmid).val(tmp); break; case "select": var opv = tmp.split(","); opv = $.map(opv,function(n){return $.trim(n);}); $("#"+nm+" option","#"+fmid).each(function(j){ if (!cm[i].editoptions.multiple && (opv[0] == $.trim($(this).text()) || opv[0] == $.trim($(this).val())) ){ this.selected= true; } else if (cm[i].editoptions.multiple){ if( $.inArray($.trim($(this).text()), opv ) > -1 || $.inArray($.trim($(this).val()), opv ) > -1 ){ this.selected = true; }else{ this.selected = false; } } else { this.selected = false; } }); break; case "checkbox": tmp = tmp+""; if(cm[i].editoptions && cm[i].editoptions.value) { var cb = cm[i].editoptions.value.split(":"); if(cb[0] == tmp) { $("#"+nm,"#"+fmid).attr("checked",true); $("#"+nm,"#"+fmid).attr("defaultChecked",true); //ie } else { $("#"+nm,"#"+fmid).attr("checked",false); $("#"+nm,"#"+fmid).attr("defaultChecked",""); //ie } } else { tmp = tmp.toLowerCase(); if(tmp.search(/(false|0|no|off|undefined)/i)<0 && tmp!=="") { $("#"+nm,"#"+fmid).attr("checked",true); $("#"+nm,"#"+fmid).attr("defaultChecked",true); //ie } else { $("#"+nm,"#"+fmid).attr("checked",false); $("#"+nm,"#"+fmid).attr("defaultChecked",""); //ie } } break; case 'custom' : try { if(cm[i].editoptions && $.isFunction(cm[i].editoptions.custom_value)) { cm[i].editoptions.custom_value($("#"+nm,"#"+fmid),'set',tmp); } else { throw "e1"; } } catch (e) { if (e=="e1") { $.jgrid.info_dialog(jQuery.jgrid.errors.errcap,"function 'custom_value' "+$.jgrid.edit.msg.nodefined,jQuery.jgrid.edit.bClose);} else { $.jgrid.info_dialog(jQuery.jgrid.errors.errcap,e.message,jQuery.jgrid.edit.bClose); } } break; } cnt++; } }); if(cnt>0) { $("#id_g","#"+frmtb).val(rowid); } } function postIt() { var copydata, ret=[true,"",""], onCS = {}, opers = $t.p.prmNames, idname, oper; if($.isFunction(rp_ge.beforeCheckValues)) { var retvals = rp_ge.beforeCheckValues(postdata,$("#"+frmgr),postdata[$t.p.id+"_id"] == "_empty" ? opers.addoper : opers.editoper); if(retvals && typeof(retvals) === 'object') { postdata = retvals; } } for( var key in postdata ){ if(postdata.hasOwnProperty(key)) { ret = $.jgrid.checkValues(postdata[key],key,$t); if(ret[0] === false) { break; } } } if(ret[0]) { if( $.isFunction( rp_ge.onclickSubmit)) { onCS = rp_ge.onclickSubmit(rp_ge,postdata) || {}; } if( $.isFunction(rp_ge.beforeSubmit)) { ret = rp_ge.beforeSubmit(postdata,$("#"+frmgr)); } } if(ret[0] && !rp_ge.processing) { rp_ge.processing = true; $("#sData", "#"+frmtb+"_2").addClass('ui-state-active'); oper = opers.oper; idname = opers.id; // we add to pos data array the action - the name is oper postdata[oper] = ($.trim(postdata[$t.p.id+"_id"]) == "_empty") ? opers.addoper : opers.editoper; if(postdata[oper] != opers.addoper) { postdata[idname] = postdata[$t.p.id+"_id"]; } else { // check to see if we have allredy this field in the form and if yes lieve it if( postdata[idname] === undefined ) { postdata[idname] = postdata[$t.p.id+"_id"]; } } delete postdata[$t.p.id+"_id"]; postdata = $.extend(postdata,rp_ge.editData,onCS); var ajaxOptions = $.extend({ url: rp_ge.url ? rp_ge.url : $($t).jqGrid('getGridParam','editurl'), type: rp_ge.mtype, data: $.isFunction(rp_ge.serializeEditData) ? rp_ge.serializeEditData(postdata) : postdata, complete:function(data,Status){ if(Status != "success") { ret[0] = false; if ($.isFunction(rp_ge.errorTextFormat)) { ret[1] = rp_ge.errorTextFormat(data); } else { ret[1] = Status + " Status: '" + data.statusText + "'. Error code: " + data.status; } } else { // data is posted successful // execute aftersubmit with the returned data from server if( $.isFunction(rp_ge.afterSubmit) ) { ret = rp_ge.afterSubmit(data,postdata); } } if(ret[0] === false) { $("#FormError>td","#"+frmtb).html(ret[1]); $("#FormError","#"+frmtb).show(); } else { // remove some values if formattaer select or checkbox $.each($t.p.colModel, function(i,n){ if(extpost[this.name] && this.formatter && this.formatter=='select') { try {delete extpost[this.name];} catch (e) {} } }); postdata = $.extend(postdata,extpost); if($t.p.autoencode) { $.each(postdata,function(n,v){ postdata[n] = $.jgrid.htmlDecode(v); }); } rp_ge.reloadAfterSubmit = rp_ge.reloadAfterSubmit && $t.p.datatype != "local"; // the action is add if(postdata[oper] == opers.addoper ) { //id processing // user not set the id ret[2] if(!ret[2]) { ret[2] = (parseInt($t.p.records,10)+1)+""; } postdata[idname] = ret[2]; if(rp_ge.closeAfterAdd) { if(rp_ge.reloadAfterSubmit) { $($t).trigger("reloadGrid"); } else { $($t).jqGrid("addRowData",ret[2],postdata,p.addedrow); $($t).jqGrid("setSelection",ret[2]); } $.jgrid.hideModal("#"+IDs.themodal,{gb:"#gbox_"+gID,jqm:p.jqModal,onClose: rp_ge.onClose}); } else if (rp_ge.clearAfterAdd) { if(rp_ge.reloadAfterSubmit) { $($t).trigger("reloadGrid"); } else { $($t).jqGrid("addRowData",ret[2],postdata,p.addedrow); } fillData("_empty",$t,frmgr); } else { if(rp_ge.reloadAfterSubmit) { $($t).trigger("reloadGrid"); } else { $($t).jqGrid("addRowData",ret[2],postdata,p.addedrow); } } } else { // the action is update if(rp_ge.reloadAfterSubmit) { $($t).trigger("reloadGrid"); if( !rp_ge.closeAfterEdit ) { setTimeout(function(){$($t).jqGrid("setSelection",postdata[idname]);},1000); } } else { if($t.p.treeGrid === true) { $($t).jqGrid("setTreeRow",postdata[idname],postdata); } else { $($t).jqGrid("setRowData",postdata[idname],postdata); } } if(rp_ge.closeAfterEdit) { $.jgrid.hideModal("#"+IDs.themodal,{gb:"#gbox_"+gID,jqm:p.jqModal,onClose: rp_ge.onClose}); } } if($.isFunction(rp_ge.afterComplete)) { copydata = data; setTimeout(function(){rp_ge.afterComplete(copydata,postdata,$("#"+frmgr));copydata=null;},500); } } rp_ge.processing=false; if(rp_ge.checkOnSubmit || rp_ge.checkOnUpdate) { $("#"+frmgr).data("disabled",false); if(rp_ge._savedData[$t.p.id+"_id"] !="_empty"){ for(var key in rp_ge._savedData) { if(postdata[key]) { rp_ge._savedData[key] = postdata[key]; } } } } $("#sData", "#"+frmtb+"_2").removeClass('ui-state-active'); try{$(':input:visible',"#"+frmgr)[0].focus();} catch (e){} }, error:function(xhr,st,err){ $("#FormError>td","#"+frmtb).html(st+ " : "+err); $("#FormError","#"+frmtb).show(); rp_ge.processing=false; $("#"+frmgr).data("disabled",false); $("#sData", "#"+frmtb+"_2").removeClass('ui-state-active'); } }, $.jgrid.ajaxOptions, rp_ge.ajaxEditOptions ); if (!ajaxOptions.url && !rp_ge.useDataProxy) { if ($.isFunction($t.p.dataProxy)) { rp_ge.useDataProxy = true; } else { ret[0]=false; ret[1] += " "+$.jgrid.errors.nourl; } } if (ret[0]) { if (rp_ge.useDataProxy) { $t.p.dataProxy.call($t, ajaxOptions, "set_"+$t.p.id); } else { $.ajax(ajaxOptions); } } } if(ret[0] === false) { $("#FormError>td","#"+frmtb).html(ret[1]); $("#FormError","#"+frmtb).show(); // return; } } function compareData(nObj, oObj ) { var ret = false,key; for (key in nObj) { if(nObj[key] != oObj[key]) { ret = true; break; } } return ret; } function checkUpdates () { var stat = true; $("#FormError","#"+frmtb).hide(); if(rp_ge.checkOnUpdate) { postdata = {}; extpost={}; getFormData(); newData = $.extend({},postdata,extpost); diff = compareData(newData,rp_ge._savedData); if(diff) { $("#"+frmgr).data("disabled",true); $(".confirm","#"+IDs.themodal).show(); stat = false; } } return stat; } function restoreInline() { if (rowid !== "_empty" && typeof($t.p.savedRow) !== "undefined" && $t.p.savedRow.length > 0 && $.isFunction($.fn.jqGrid['restoreRow'])) { for (var i=0;i<$t.p.savedRow.length;i++) { if ($t.p.savedRow[i].id == rowid) { $($t).jqGrid('restoreRow',rowid); break; } } } } if ( $("#"+IDs.themodal).html() != null ) { if(onBeforeInit) { showFrm = onBeforeInit($("#"+frmgr)); if(typeof(showFrm) == "undefined") { showFrm = true; } } if(showFrm === false) { return; } restoreInline(); $(".ui-jqdialog-title","#"+IDs.modalhead).html(p.caption); $("#FormError","#"+frmtb).hide(); if(rp_ge.topinfo) { $(".topinfo","#"+frmtb+"_2").html(rp_ge.topinfo); $(".tinfo","#"+frmtb+"_2").show(); } else { $(".tinfo","#"+frmtb+"_2").hide(); } if(rp_ge.bottominfo) { $(".bottominfo","#"+frmtb+"_2").html(rp_ge.bottominfo); $(".binfo","#"+frmtb+"_2").show(); } else { $(".binfo","#"+frmtb+"_2").hide(); } // filldata fillData(rowid,$t,frmgr); /// if(rowid=="_empty" || !rp_ge.viewPagerButtons) { $("#pData, #nData","#"+frmtb+"_2").hide(); } else { $("#pData, #nData","#"+frmtb+"_2").show(); } if(rp_ge.processing===true) { rp_ge.processing=false; $("#sData", "#"+frmtb+"_2").removeClass('ui-state-active'); } if($("#"+frmgr).data("disabled")===true) { $(".confirm","#"+IDs.themodal).hide(); $("#"+frmgr).data("disabled",false); } if(onBeforeShow) { onBeforeShow($("#"+frmgr)); } $("#"+IDs.themodal).data("onClose",rp_ge.onClose); $.jgrid.viewModal("#"+IDs.themodal,{gbox:"#gbox_"+gID,jqm:p.jqModal, jqM: false, overlay: p.overlay, modal:p.modal}); if(!closeovrl) { $(".jqmOverlay").click(function(){ if(!checkUpdates()) { return false; } $.jgrid.hideModal("#"+IDs.themodal,{gb:"#gbox_"+gID,jqm:p.jqModal, onClose: rp_ge.onClose}); return false; }); } if(onAfterShow) { onAfterShow($("#"+frmgr)); } } else { var dh = isNaN(p.dataheight) ? p.dataheight : p.dataheight+"px", frm = $("<form name='FormPost' id='"+frmgr+"' class='FormGrid' onSubmit='return false;' style='width:100%;overflow:auto;position:relative;height:"+dh+";'></form>").data("disabled",false), tbl = $("<table id='"+frmtb+"' class='EditTable' cellspacing='0' cellpadding='0' border='0'><tbody></tbody></table>"); if(onBeforeInit) { showFrm = onBeforeInit($("#"+frmgr)); if(typeof(showFrm) == "undefined") { showFrm = true; } } if(showFrm === false) { return; } restoreInline(); $($t.p.colModel).each( function(i) { var fmto = this.formoptions; maxCols = Math.max(maxCols, fmto ? fmto.colpos || 0 : 0 ); maxRows = Math.max(maxRows, fmto ? fmto.rowpos || 0 : 0 ); }); $(frm).append(tbl); var flr = $("<tr id='FormError' style='display:none'><td class='ui-state-error' colspan='"+(maxCols*2)+"'></td></tr>"); flr[0].rp = 0; $(tbl).append(flr); //topinfo flr = $("<tr style='display:none' class='tinfo'><td class='topinfo' colspan='"+(maxCols*2)+"'>"+rp_ge.topinfo+"</td></tr>"); flr[0].rp = 0; $(tbl).append(flr); // set the id. // use carefull only to change here colproperties. // create data var rtlb = $t.p.direction == "rtl" ? true :false, bp = rtlb ? "nData" : "pData", bn = rtlb ? "pData" : "nData"; createData(rowid,$t,tbl,maxCols); // buttons at footer var bP = "<a href='javascript:void(0)' id='"+bp+"' class='fm-button ui-state-default ui-corner-left'><span class='ui-icon ui-icon-triangle-1-w'></span></div>", bN = "<a href='javascript:void(0)' id='"+bn+"' class='fm-button ui-state-default ui-corner-right'><span class='ui-icon ui-icon-triangle-1-e'></span></div>", bS ="<a href='javascript:void(0)' id='sData' class='fm-button ui-state-default ui-corner-all'>"+p.bSubmit+"</a>", bC ="<a href='javascript:void(0)' id='cData' class='fm-button ui-state-default ui-corner-all'>"+p.bCancel+"</a>"; var bt = "<table border='0' cellspacing='0' cellpadding='0' class='EditTable' id='"+frmtb+"_2'><tbody><tr><td colspan='2'><hr class='ui-widget-content' style='margin:1px'/></td></tr><tr id='Act_Buttons'><td class='navButton'>"+(rtlb ? bN+bP : bP+bN)+"</td><td class='EditButton'>"+bS+bC+"</td></tr>"; bt += "<tr style='display:none' class='binfo'><td class='bottominfo' colspan='2'>"+rp_ge.bottominfo+"</td></tr>"; bt += "</tbody></table>"; if(maxRows > 0) { var sd=[]; $.each($(tbl)[0].rows,function(i,r){ sd[i] = r; }); sd.sort(function(a,b){ if(a.rp > b.rp) {return 1;} if(a.rp < b.rp) {return -1;} return 0; }); $.each(sd, function(index, row) { $('tbody',tbl).append(row); }); } p.gbox = "#gbox_"+gID; var cle = false; if(p.closeOnEscape===true){ p.closeOnEscape = false; cle = true; } var tms = $("<span></span>").append(frm).append(bt); $.jgrid.createModal(IDs,tms,p,"#gview_"+$t.p.id,$("#gbox_"+$t.p.id)[0]); if(rtlb) { $("#pData, #nData","#"+frmtb+"_2").css("float","right"); $(".EditButton","#"+frmtb+"_2").css("text-align","left"); } if(rp_ge.topinfo) { $(".tinfo","#"+frmtb+"_2").show(); } if(rp_ge.bottominfo) { $(".binfo","#"+frmtb+"_2").show(); } tms = null; bt=null; $("#"+IDs.themodal).keydown( function( e ) { var wkey = e.target; if ($("#"+frmgr).data("disabled")===true ) { return false; }//?? if(rp_ge.savekey[0] === true && e.which == rp_ge.savekey[1]) { // save if(wkey.tagName != "TEXTAREA") { $("#sData", "#"+frmtb+"_2").trigger("click"); return false; } } if(e.which === 27) { if(!checkUpdates()) { return false; } if(cle) { $.jgrid.hideModal(this,{gb:p.gbox,jqm:p.jqModal, onClose: rp_ge.onClose}); } return false; } if(rp_ge.navkeys[0]===true) { if($("#id_g","#"+frmtb).val() == "_empty") { return true; } if(e.which == rp_ge.navkeys[1]){ //up $("#pData", "#"+frmtb+"_2").trigger("click"); return false; } if(e.which == rp_ge.navkeys[2]){ //down $("#nData", "#"+frmtb+"_2").trigger("click"); return false; } } }); if(p.checkOnUpdate) { $("a.ui-jqdialog-titlebar-close span","#"+IDs.themodal).removeClass("jqmClose"); $("a.ui-jqdialog-titlebar-close","#"+IDs.themodal).unbind("click") .click(function(){ if(!checkUpdates()) { return false; } $.jgrid.hideModal("#"+IDs.themodal,{gb:"#gbox_"+gID,jqm:p.jqModal,onClose: rp_ge.onClose}); return false; }); } p.saveicon = $.extend([true,"left","ui-icon-disk"],p.saveicon); p.closeicon = $.extend([true,"left","ui-icon-close"],p.closeicon); // beforeinitdata after creation of the form if(p.saveicon[0]===true) { $("#sData","#"+frmtb+"_2").addClass(p.saveicon[1] == "right" ? 'fm-button-icon-right' : 'fm-button-icon-left') .append("<span class='ui-icon "+p.saveicon[2]+"'></span>"); } if(p.closeicon[0]===true) { $("#cData","#"+frmtb+"_2").addClass(p.closeicon[1] == "right" ? 'fm-button-icon-right' : 'fm-button-icon-left') .append("<span class='ui-icon "+p.closeicon[2]+"'></span>"); } if(rp_ge.checkOnSubmit || rp_ge.checkOnUpdate) { bS ="<a href='javascript:void(0)' id='sNew' class='fm-button ui-state-default ui-corner-all' style='z-index:1002'>"+p.bYes+"</a>"; bN ="<a href='javascript:void(0)' id='nNew' class='fm-button ui-state-default ui-corner-all' style='z-index:1002'>"+p.bNo+"</a>"; bC ="<a href='javascript:void(0)' id='cNew' class='fm-button ui-state-default ui-corner-all' style='z-index:1002'>"+p.bExit+"</a>"; var ii, zI = p.zIndex || 999; zI ++; if ($.browser.msie && $.browser.version ==6) { ii = '<iframe style="display:block;position:absolute;z-index:-1;filter:Alpha(Opacity=\'0\');" src="javascript:false;"></iframe>'; } else { ii="";} $("<div class='ui-widget-overlay jqgrid-overlay confirm' style='z-index:"+zI+";display:none;'>&#160;"+ii+"</div><div class='confirm ui-widget-content ui-jqconfirm' style='z-index:"+(zI+1)+"'>"+p.saveData+"<br/><br/>"+bS+bN+bC+"</div>").insertAfter("#"+frmgr); $("#sNew","#"+IDs.themodal).click(function(){ postIt(); $("#"+frmgr).data("disabled",false); $(".confirm","#"+IDs.themodal).hide(); return false; }); $("#nNew","#"+IDs.themodal).click(function(){ $(".confirm","#"+IDs.themodal).hide(); $("#"+frmgr).data("disabled",false); setTimeout(function(){$(":input","#"+frmgr)[0].focus();},0); return false; }); $("#cNew","#"+IDs.themodal).click(function(){ $(".confirm","#"+IDs.themodal).hide(); $("#"+frmgr).data("disabled",false); $.jgrid.hideModal("#"+IDs.themodal,{gb:"#gbox_"+gID,jqm:p.jqModal,onClose: rp_ge.onClose}); return false; }); } // here initform - only once if(onInitializeForm) { onInitializeForm($("#"+frmgr)); } if(rowid=="_empty" || !rp_ge.viewPagerButtons) { $("#pData,#nData","#"+frmtb+"_2").hide(); } else { $("#pData,#nData","#"+frmtb+"_2").show(); } if(onBeforeShow) { onBeforeShow($("#"+frmgr)); } $("#"+IDs.themodal).data("onClose",rp_ge.onClose); $.jgrid.viewModal("#"+IDs.themodal,{gbox:"#gbox_"+gID,jqm:p.jqModal, overlay: p.overlay,modal:p.modal}); if(!closeovrl) { $(".jqmOverlay").click(function(){ if(!checkUpdates()) { return false; } $.jgrid.hideModal("#"+IDs.themodal,{gb:"#gbox_"+gID,jqm:p.jqModal, onClose: rp_ge.onClose}); return false; }); } if(onAfterShow) { onAfterShow($("#"+frmgr)); } $(".fm-button","#"+IDs.themodal).hover( function(){$(this).addClass('ui-state-hover');}, function(){$(this).removeClass('ui-state-hover');} ); $("#sData", "#"+frmtb+"_2").click(function(e){ postdata = {}; extpost={}; $("#FormError","#"+frmtb).hide(); // all depend on ret array //ret[0] - succes //ret[1] - msg if not succes //ret[2] - the id that will be set if reload after submit false getFormData(); if(postdata[$t.p.id+"_id"] == "_empty") { postIt(); } else if(p.checkOnSubmit===true ) { newData = $.extend({},postdata,extpost); diff = compareData(newData,rp_ge._savedData); if(diff) { $("#"+frmgr).data("disabled",true); $(".confirm","#"+IDs.themodal).show(); } else { postIt(); } } else { postIt(); } return false; }); $("#cData", "#"+frmtb+"_2").click(function(e){ if(!checkUpdates()) { return false; } $.jgrid.hideModal("#"+IDs.themodal,{gb:"#gbox_"+gID,jqm:p.jqModal,onClose: rp_ge.onClose}); return false; }); $("#nData", "#"+frmtb+"_2").click(function(e){ if(!checkUpdates()) { return false; } $("#FormError","#"+frmtb).hide(); var npos = getCurrPos(); npos[0] = parseInt(npos[0],10); if(npos[0] != -1 && npos[1][npos[0]+1]) { if($.isFunction(p.onclickPgButtons)) { p.onclickPgButtons('next',$("#"+frmgr),npos[1][npos[0]]); } fillData(npos[1][npos[0]+1],$t,frmgr); $($t).jqGrid("setSelection",npos[1][npos[0]+1]); if($.isFunction(p.afterclickPgButtons)) { p.afterclickPgButtons('next',$("#"+frmgr),npos[1][npos[0]+1]); } updateNav(npos[0]+1,npos[1].length-1); } return false; }); $("#pData", "#"+frmtb+"_2").click(function(e){ if(!checkUpdates()) { return false; } $("#FormError","#"+frmtb).hide(); var ppos = getCurrPos(); if(ppos[0] != -1 && ppos[1][ppos[0]-1]) { if($.isFunction(p.onclickPgButtons)) { p.onclickPgButtons('prev',$("#"+frmgr),ppos[1][ppos[0]]); } fillData(ppos[1][ppos[0]-1],$t,frmgr); $($t).jqGrid("setSelection",ppos[1][ppos[0]-1]); if($.isFunction(p.afterclickPgButtons)) { p.afterclickPgButtons('prev',$("#"+frmgr),ppos[1][ppos[0]-1]); } updateNav(ppos[0]-1,ppos[1].length-1); } return false; }); } function updateNav(cr,totr,rid){ if (cr===0) { $("#pData","#"+frmtb+"_2").addClass('ui-state-disabled'); } else { $("#pData","#"+frmtb+"_2").removeClass('ui-state-disabled'); } if (cr==totr) { $("#nData","#"+frmtb+"_2").addClass('ui-state-disabled'); } else { $("#nData","#"+frmtb+"_2").removeClass('ui-state-disabled'); } } function getCurrPos() { var rowsInGrid = $($t).jqGrid("getDataIDs"), selrow = $("#id_g","#"+frmtb).val(), pos = $.inArray(selrow,rowsInGrid); return [pos,rowsInGrid]; } var posInit =getCurrPos(); updateNav(posInit[0],posInit[1].length-1); }); }, viewGridRow : function(rowid, p){ p = $.extend({ top : 0, left: 0, width: 0, height: 'auto', dataheight: 'auto', modal: false, overlay: 10, drag: true, resize: true, jqModal: true, closeOnEscape : false, labelswidth: '30%', closeicon: [], navkeys: [false,38,40], onClose: null, beforeShowForm : null, beforeInitData : null, viewPagerButtons : true }, $.jgrid.view, p || {}); return this.each(function(){ var $t = this; if (!$t.grid || !rowid) { return; } if(!p.imgpath) { p.imgpath= $t.p.imgpath; } // I hate to rewrite code, but ... var gID = $t.p.id, frmgr = "ViewGrid_"+gID , frmtb = "ViewTbl_"+gID, IDs = {themodal:'viewmod'+gID,modalhead:'viewhd'+gID,modalcontent:'viewcnt'+gID, scrollelm : frmgr}, onBeforeInit = $.isFunction(p.beforeInitData) ? p.beforeInitData : false, showFrm = true, maxCols = 1, maxRows=0; function focusaref(){ //Sfari 3 issues if(p.closeOnEscape===true || p.navkeys[0]===true) { setTimeout(function(){$(".ui-jqdialog-titlebar-close","#"+IDs.modalhead).focus();},0); } } function createData(rowid,obj,tb,maxcols){ var nm, hc,trdata, cnt=0,tmp, dc, retpos=[], ind=false, tdtmpl = "<td class='CaptionTD form-view-label ui-widget-content' width='"+p.labelswidth+"'>&#160;</td><td class='DataTD form-view-data ui-helper-reset ui-widget-content'>&#160;</td>", tmpl="", tdtmpl2 = "<td class='CaptionTD form-view-label ui-widget-content'>&#160;</td><td class='DataTD form-view-data ui-widget-content'>&#160;</td>", fmtnum = ['integer','number','currency'],max1 =0, max2=0 ,maxw,setme, viewfld; for (var i =1;i<=maxcols;i++) { tmpl += i == 1 ? tdtmpl : tdtmpl2; } // find max number align rigth with property formatter $(obj.p.colModel).each( function(i) { if(this.editrules && this.editrules.edithidden === true) { hc = false; } else { hc = this.hidden === true ? true : false; } if(!hc && this.align==='right') { if(this.formatter && $.inArray(this.formatter,fmtnum) !== -1 ) { max1 = Math.max(max1,parseInt(this.width,10)); } else { max2 = Math.max(max2,parseInt(this.width,10)); } } }); maxw = max1 !==0 ? max1 : max2 !==0 ? max2 : 0; ind = $(obj).jqGrid("getInd",rowid); $(obj.p.colModel).each( function(i) { nm = this.name; setme = false; // hidden fields are included in the form if(this.editrules && this.editrules.edithidden === true) { hc = false; } else { hc = this.hidden === true ? true : false; } dc = hc ? "style='display:none'" : ""; viewfld = (typeof this.viewable != 'boolean') ? true : this.viewable; if ( nm !== 'cb' && nm !== 'subgrid' && nm !== 'rn' && viewfld) { if(ind === false) { tmp = ""; } else { if(nm == obj.p.ExpandColumn && obj.p.treeGrid === true) { tmp = $("td:eq("+i+")",obj.rows[ind]).text(); } else { tmp = $("td:eq("+i+")",obj.rows[ind]).html(); } } setme = this.align === 'right' && maxw !==0 ? true : false; var opt = $.extend({}, this.editoptions || {} ,{id:nm,name:nm}), frmopt = $.extend({},{rowabove:false,rowcontent:''}, this.formoptions || {}), rp = parseInt(frmopt.rowpos,10) || cnt+1, cp = parseInt((parseInt(frmopt.colpos,10) || 1)*2,10); if(frmopt.rowabove) { var newdata = $("<tr><td class='contentinfo' colspan='"+(maxcols*2)+"'>"+frmopt.rowcontent+"</td></tr>"); $(tb).append(newdata); newdata[0].rp = rp; } trdata = $(tb).find("tr[rowpos="+rp+"]"); if ( trdata.length===0 ) { trdata = $("<tr "+dc+" rowpos='"+rp+"'></tr>").addClass("FormData").attr("id","trv_"+nm); $(trdata).append(tmpl); $(tb).append(trdata); trdata[0].rp = rp; } $("td:eq("+(cp-2)+")",trdata[0]).html('<b>'+ (typeof frmopt.label === 'undefined' ? obj.p.colNames[i]: frmopt.label)+'</b>'); $("td:eq("+(cp-1)+")",trdata[0]).append("<span>"+tmp+"</span>").attr("id","v_"+nm); if(setme){ $("td:eq("+(cp-1)+") span",trdata[0]).css({'text-align':'right',width:maxw+"px"}); } retpos[cnt] = i; cnt++; } }); if( cnt > 0) { var idrow = $("<tr class='FormData' style='display:none'><td class='CaptionTD'></td><td colspan='"+ (maxcols*2-1)+"' class='DataTD'><input class='FormElement' id='id_g' type='text' name='id' value='"+rowid+"'/></td></tr>"); idrow[0].rp = cnt+99; $(tb).append(idrow); } return retpos; } function fillData(rowid,obj){ var nm, hc,cnt=0,tmp, opt,trv; trv = $(obj).jqGrid("getInd",rowid,true); if(!trv) { return; } $('td',trv).each( function(i) { nm = obj.p.colModel[i].name; // hidden fields are included in the form if(obj.p.colModel[i].editrules && obj.p.colModel[i].editrules.edithidden === true) { hc = false; } else { hc = obj.p.colModel[i].hidden === true ? true : false; } if ( nm !== 'cb' && nm !== 'subgrid' && nm !== 'rn') { if(nm == obj.p.ExpandColumn && obj.p.treeGrid === true) { tmp = $(this).text(); } else { tmp = $(this).html(); } opt = $.extend({},obj.p.colModel[i].editoptions || {}); nm = $.jgrid.jqID("v_"+nm); $("#"+nm+" span","#"+frmtb).html(tmp); if (hc) { $("#"+nm,"#"+frmtb).parents("tr:first").hide(); } cnt++; } }); if(cnt>0) { $("#id_g","#"+frmtb).val(rowid); } } if ( $("#"+IDs.themodal).html() != null ) { if(onBeforeInit) { showFrm = onBeforeInit($("#"+frmgr)); if(typeof(showFrm) == "undefined") { showFrm = true; } } if(showFrm === false) { return; } $(".ui-jqdialog-title","#"+IDs.modalhead).html(p.caption); $("#FormError","#"+frmtb).hide(); fillData(rowid,$t); if($.isFunction(p.beforeShowForm)) { p.beforeShowForm($("#"+frmgr)); } $.jgrid.viewModal("#"+IDs.themodal,{gbox:"#gbox_"+gID,jqm:p.jqModal, jqM: false, overlay: p.overlay, modal:p.modal}); focusaref(); } else { var dh = isNaN(p.dataheight) ? p.dataheight : p.dataheight+"px"; var frm = $("<form name='FormPost' id='"+frmgr+"' class='FormGrid' style='width:100%;overflow:auto;position:relative;height:"+dh+";'></form>"), tbl =$("<table id='"+frmtb+"' class='EditTable' cellspacing='1' cellpadding='2' border='0' style='table-layout:fixed'><tbody></tbody></table>"); if(onBeforeInit) { showFrm = onBeforeInit($("#"+frmgr)); if(typeof(showFrm) == "undefined") { showFrm = true; } } if(showFrm === false) { return; } $($t.p.colModel).each( function(i) { var fmto = this.formoptions; maxCols = Math.max(maxCols, fmto ? fmto.colpos || 0 : 0 ); maxRows = Math.max(maxRows, fmto ? fmto.rowpos || 0 : 0 ); }); // set the id. $(frm).append(tbl); createData(rowid, $t, tbl, maxCols); var rtlb = $t.p.direction == "rtl" ? true :false, bp = rtlb ? "nData" : "pData", bn = rtlb ? "pData" : "nData", // buttons at footer bP = "<a href='javascript:void(0)' id='"+bp+"' class='fm-button ui-state-default ui-corner-left'><span class='ui-icon ui-icon-triangle-1-w'></span></a>", bN = "<a href='javascript:void(0)' id='"+bn+"' class='fm-button ui-state-default ui-corner-right'><span class='ui-icon ui-icon-triangle-1-e'></span></a>", bC ="<a href='javascript:void(0)' id='cData' class='fm-button ui-state-default ui-corner-all'>"+p.bClose+"</a>"; if(maxRows > 0) { var sd=[]; $.each($(tbl)[0].rows,function(i,r){ sd[i] = r; }); sd.sort(function(a,b){ if(a.rp > b.rp) {return 1;} if(a.rp < b.rp) {return -1;} return 0; }); $.each(sd, function(index, row) { $('tbody',tbl).append(row); }); } p.gbox = "#gbox_"+gID; var cle = false; if(p.closeOnEscape===true){ p.closeOnEscape = false; cle = true; } var bt = $("<span></span>").append(frm).append("<table border='0' class='EditTable' id='"+frmtb+"_2'><tbody><tr id='Act_Buttons'><td class='navButton' width='"+p.labelswidth+"'>"+(rtlb ? bN+bP : bP+bN)+"</td><td class='EditButton'>"+bC+"</td></tr></tbody></table>"); $.jgrid.createModal(IDs,bt,p,"#gview_"+$t.p.id,$("#gview_"+$t.p.id)[0]); if(rtlb) { $("#pData, #nData","#"+frmtb+"_2").css("float","right"); $(".EditButton","#"+frmtb+"_2").css("text-align","left"); } if(!p.viewPagerButtons) { $("#pData, #nData","#"+frmtb+"_2").hide(); } bt = null; $("#"+IDs.themodal).keydown( function( e ) { if(e.which === 27) { if(cle) { $.jgrid.hideModal(this,{gb:p.gbox,jqm:p.jqModal, onClose: p.onClose}); } return false; } if(p.navkeys[0]===true) { if(e.which === p.navkeys[1]){ //up $("#pData", "#"+frmtb+"_2").trigger("click"); return false; } if(e.which === p.navkeys[2]){ //down $("#nData", "#"+frmtb+"_2").trigger("click"); return false; } } }); p.closeicon = $.extend([true,"left","ui-icon-close"],p.closeicon); if(p.closeicon[0]===true) { $("#cData","#"+frmtb+"_2").addClass(p.closeicon[1] == "right" ? 'fm-button-icon-right' : 'fm-button-icon-left') .append("<span class='ui-icon "+p.closeicon[2]+"'></span>"); } if($.isFunction(p.beforeShowForm)) { p.beforeShowForm($("#"+frmgr)); } $.jgrid.viewModal("#"+IDs.themodal,{gbox:"#gbox_"+gID,jqm:p.jqModal, modal:p.modal}); $(".fm-button:not(.ui-state-disabled)","#"+frmtb+"_2").hover( function(){$(this).addClass('ui-state-hover');}, function(){$(this).removeClass('ui-state-hover');} ); focusaref(); $("#cData", "#"+frmtb+"_2").click(function(e){ $.jgrid.hideModal("#"+IDs.themodal,{gb:"#gbox_"+gID,jqm:p.jqModal, onClose: p.onClose}); return false; }); $("#nData", "#"+frmtb+"_2").click(function(e){ $("#FormError","#"+frmtb).hide(); var npos = getCurrPos(); npos[0] = parseInt(npos[0],10); if(npos[0] != -1 && npos[1][npos[0]+1]) { if($.isFunction(p.onclickPgButtons)) { p.onclickPgButtons('next',$("#"+frmgr),npos[1][npos[0]]); } fillData(npos[1][npos[0]+1],$t); $($t).jqGrid("setSelection",npos[1][npos[0]+1]); if($.isFunction(p.afterclickPgButtons)) { p.afterclickPgButtons('next',$("#"+frmgr),npos[1][npos[0]+1]); } updateNav(npos[0]+1,npos[1].length-1); } focusaref(); return false; }); $("#pData", "#"+frmtb+"_2").click(function(e){ $("#FormError","#"+frmtb).hide(); var ppos = getCurrPos(); if(ppos[0] != -1 && ppos[1][ppos[0]-1]) { if($.isFunction(p.onclickPgButtons)) { p.onclickPgButtons('prev',$("#"+frmgr),ppos[1][ppos[0]]); } fillData(ppos[1][ppos[0]-1],$t); $($t).jqGrid("setSelection",ppos[1][ppos[0]-1]); if($.isFunction(p.afterclickPgButtons)) { p.afterclickPgButtons('prev',$("#"+frmgr),ppos[1][ppos[0]-1]); } updateNav(ppos[0]-1,ppos[1].length-1); } focusaref(); return false; }); } function updateNav(cr,totr,rid){ if (cr===0) { $("#pData","#"+frmtb+"_2").addClass('ui-state-disabled'); } else { $("#pData","#"+frmtb+"_2").removeClass('ui-state-disabled'); } if (cr==totr) { $("#nData","#"+frmtb+"_2").addClass('ui-state-disabled'); } else { $("#nData","#"+frmtb+"_2").removeClass('ui-state-disabled'); } } function getCurrPos() { var rowsInGrid = $($t).jqGrid("getDataIDs"), selrow = $("#id_g","#"+frmtb).val(), pos = $.inArray(selrow,rowsInGrid); return [pos,rowsInGrid]; } var posInit =getCurrPos(); updateNav(posInit[0],posInit[1].length-1); }); }, delGridRow : function(rowids,p) { p = $.extend({ top : 0, left: 0, width: 240, height: 'auto', dataheight : 'auto', modal: false, overlay: 10, drag: true, resize: true, url : '', mtype : "POST", reloadAfterSubmit: true, beforeShowForm: null, beforeInitData : null, afterShowForm: null, beforeSubmit: null, onclickSubmit: null, afterSubmit: null, jqModal : true, closeOnEscape : false, delData: {}, delicon : [], cancelicon : [], onClose : null, ajaxDelOptions : {}, processing : false, serializeDelData : null, useDataProxy : false }, $.jgrid.del, p ||{}); rp_ge = p; return this.each(function(){ var $t = this; if (!$t.grid ) { return; } if(!rowids) { return; } var onBeforeShow = typeof p.beforeShowForm === 'function' ? true: false, onAfterShow = typeof p.afterShowForm === 'function' ? true: false, onBeforeInit = $.isFunction(p.beforeInitData) ? p.beforeInitData : false, gID = $t.p.id, onCS = {}, showFrm = true, dtbl = "DelTbl_"+gID,postd, idname, opers, oper, IDs = {themodal:'delmod'+gID,modalhead:'delhd'+gID,modalcontent:'delcnt'+gID, scrollelm: dtbl}; if (jQuery.isArray(rowids)) { rowids = rowids.join(); } if ( $("#"+IDs.themodal).html() != null ) { if(onBeforeInit) { showFrm = onBeforeInit(); if(typeof(showFrm) == "undefined") { showFrm = true; } } if(showFrm === false) { return; } $("#DelData>td","#"+dtbl).text(rowids); $("#DelError","#"+dtbl).hide(); if( rp_ge.processing === true) { rp_ge.processing=false; $("#dData", "#"+dtbl).removeClass('ui-state-active'); } if(onBeforeShow) { p.beforeShowForm($("#"+dtbl)); } $.jgrid.viewModal("#"+IDs.themodal,{gbox:"#gbox_"+gID,jqm:p.jqModal,jqM: false, overlay: p.overlay, modal:p.modal}); if(onAfterShow) { p.afterShowForm($("#"+dtbl)); } } else { if(onBeforeInit) { showFrm = onBeforeInit(); if(typeof(showFrm) == "undefined") { showFrm = true; } } if(showFrm === false) { return; } var dh = isNaN(p.dataheight) ? p.dataheight : p.dataheight+"px"; var tbl = "<div id='"+dtbl+"' class='formdata' style='width:100%;overflow:auto;position:relative;height:"+dh+";'>"; tbl += "<table class='DelTable'><tbody>"; // error data tbl += "<tr id='DelError' style='display:none'><td class='ui-state-error'></td></tr>"; tbl += "<tr id='DelData' style='display:none'><td >"+rowids+"</td></tr>"; tbl += "<tr><td class=\"delmsg\" style=\"white-space:pre;\">"+p.msg+"</td></tr><tr><td >&#160;</td></tr>"; // buttons at footer tbl += "</tbody></table></div>"; var bS = "<a href='javascript:void(0)' id='dData' class='fm-button ui-state-default ui-corner-all'>"+p.bSubmit+"</a>", bC = "<a href='javascript:void(0)' id='eData' class='fm-button ui-state-default ui-corner-all'>"+p.bCancel+"</a>"; tbl += "<table cellspacing='0' cellpadding='0' border='0' class='EditTable' id='"+dtbl+"_2'><tbody><tr><td><hr class='ui-widget-content' style='margin:1px'/></td></tr></tr><tr><td class='DelButton EditButton'>"+bS+"&#160;"+bC+"</td></tr></tbody></table>"; p.gbox = "#gbox_"+gID; $.jgrid.createModal(IDs,tbl,p,"#gview_"+$t.p.id,$("#gview_"+$t.p.id)[0]); $(".fm-button","#"+dtbl+"_2").hover( function(){$(this).addClass('ui-state-hover');}, function(){$(this).removeClass('ui-state-hover');} ); p.delicon = $.extend([true,"left","ui-icon-scissors"],p.delicon); p.cancelicon = $.extend([true,"left","ui-icon-cancel"],p.cancelicon); if(p.delicon[0]===true) { $("#dData","#"+dtbl+"_2").addClass(p.delicon[1] == "right" ? 'fm-button-icon-right' : 'fm-button-icon-left') .append("<span class='ui-icon "+p.delicon[2]+"'></span>"); } if(p.cancelicon[0]===true) { $("#eData","#"+dtbl+"_2").addClass(p.cancelicon[1] == "right" ? 'fm-button-icon-right' : 'fm-button-icon-left') .append("<span class='ui-icon "+p.cancelicon[2]+"'></span>"); } $("#dData","#"+dtbl+"_2").click(function(e){ var ret=[true,""]; onCS = {}; var postdata = $("#DelData>td","#"+dtbl).text(); //the pair is name=val1,val2,... if( typeof p.onclickSubmit === 'function' ) { onCS = p.onclickSubmit(rp_ge, postdata) || {}; } if( typeof p.beforeSubmit === 'function' ) { ret = p.beforeSubmit(postdata); } if(ret[0] && !rp_ge.processing) { rp_ge.processing = true; $(this).addClass('ui-state-active'); opers = $t.p.prmNames; postd = $.extend({},rp_ge.delData, onCS); oper = opers.oper; postd[oper] = opers.deloper; idname = opers.id; postd[idname] = postdata; var ajaxOptions = $.extend({ url: rp_ge.url ? rp_ge.url : $($t).jqGrid('getGridParam','editurl'), type: p.mtype, data: $.isFunction(p.serializeDelData) ? p.serializeDelData(postd) : postd, complete:function(data,Status){ if(Status != "success") { ret[0] = false; if ($.isFunction(rp_ge.errorTextFormat)) { ret[1] = rp_ge.errorTextFormat(data); } else { ret[1] = Status + " Status: '" + data.statusText + "'. Error code: " + data.status; } } else { // data is posted successful // execute aftersubmit with the returned data from server if( typeof rp_ge.afterSubmit === 'function' ) { ret = rp_ge.afterSubmit(data,postd); } } if(ret[0] === false) { $("#DelError>td","#"+dtbl).html(ret[1]); $("#DelError","#"+dtbl).show(); } else { if(rp_ge.reloadAfterSubmit && $t.p.datatype != "local") { $($t).trigger("reloadGrid"); } else { var toarr = []; toarr = postdata.split(","); if($t.p.treeGrid===true){ try {$($t).jqGrid("delTreeNode",toarr[0]);} catch(e){} } else { for(var i=0;i<toarr.length;i++) { $($t).jqGrid("delRowData",toarr[i]); } } $t.p.selrow = null; $t.p.selarrrow = []; } if($.isFunction(rp_ge.afterComplete)) { setTimeout(function(){rp_ge.afterComplete(data,postdata);},500); } } rp_ge.processing=false; $("#dData", "#"+dtbl+"_2").removeClass('ui-state-active'); if(ret[0]) { $.jgrid.hideModal("#"+IDs.themodal,{gb:"#gbox_"+gID,jqm:p.jqModal, onClose: rp_ge.onClose}); } }, error:function(xhr,st,err){ $("#DelError>td","#"+dtbl).html(st+ " : "+err); $("#DelError","#"+dtbl).show(); rp_ge.processing=false; $("#dData", "#"+dtbl+"_2").removeClass('ui-state-active'); } }, $.jgrid.ajaxOptions, p.ajaxDelOptions); if (!ajaxOptions.url && !rp_ge.useDataProxy) { if ($.isFunction($t.p.dataProxy)) { rp_ge.useDataProxy = true; } else { ret[0]=false; ret[1] += " "+$.jgrid.errors.nourl; } } if (ret[0]) { if (rp_ge.useDataProxy) { $t.p.dataProxy.call($t, ajaxOptions, "del_"+$t.p.id); } else { $.ajax(ajaxOptions); } } } if(ret[0] === false) { $("#DelError>td","#"+dtbl).html(ret[1]); $("#DelError","#"+dtbl).show(); } return false; }); $("#eData", "#"+dtbl+"_2").click(function(e){ $.jgrid.hideModal("#"+IDs.themodal,{gb:"#gbox_"+gID,jqm:p.jqModal, onClose: rp_ge.onClose}); return false; }); if(onBeforeShow) { p.beforeShowForm($("#"+dtbl)); } $.jgrid.viewModal("#"+IDs.themodal,{gbox:"#gbox_"+gID,jqm:p.jqModal, overlay: p.overlay, modal:p.modal}); if(onAfterShow) { p.afterShowForm($("#"+dtbl)); } } if(p.closeOnEscape===true) { setTimeout(function(){$(".ui-jqdialog-titlebar-close","#"+IDs.modalhead).focus();},0); } }); }, navGrid : function (elem, o, pEdit,pAdd,pDel,pSearch, pView) { o = $.extend({ edit: true, editicon: "ui-icon-pencil", add: true, addicon:"ui-icon-plus", del: true, delicon:"ui-icon-trash", search: true, searchicon:"ui-icon-search", refresh: true, refreshicon:"ui-icon-refresh", refreshstate: 'firstpage', view: false, viewicon : "ui-icon-document", position : "left", closeOnEscape : true, beforeRefresh : null, afterRefresh : null, cloneToTop : false }, $.jgrid.nav, o ||{}); return this.each(function() { var alertIDs = {themodal:'alertmod',modalhead:'alerthd',modalcontent:'alertcnt'}, $t = this, vwidth, vheight, twd, tdw; if(!$t.grid || typeof elem != 'string') { return; } if ($("#"+alertIDs.themodal).html() === null) { if (typeof window.innerWidth != 'undefined') { vwidth = window.innerWidth; vheight = window.innerHeight; } else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth !== 0) { vwidth = document.documentElement.clientWidth; vheight = document.documentElement.clientHeight; } else { vwidth=1024; vheight=768; } $.jgrid.createModal(alertIDs,"<div>"+o.alerttext+"</div><span tabindex='0'><span tabindex='-1' id='jqg_alrt'></span></span>",{gbox:"#gbox_"+$t.p.id,jqModal:true,drag:true,resize:true,caption:o.alertcap,top:vheight/2-25,left:vwidth/2-100,width:200,height:'auto',closeOnEscape:o.closeOnEscape},"","",true); } var clone = 1; if(o.cloneToTop && $t.p.toppager) { clone = 2; } for(var i = 0; i<clone; i++) { var tbd, navtbl = $("<table cellspacing='0' cellpadding='0' border='0' class='ui-pg-table navtable' style='float:left;table-layout:auto;'><tbody><tr></tr></tbody></table>"), sep = "<td class='ui-pg-button ui-state-disabled' style='width:4px;'><span class='ui-separator'></span></td>", pgid, elemids; if(i===0) { pgid = elem; elemids = $t.p.id; if(pgid == $t.p.toppager) { elemids += "_top"; clone = 1; } } else { pgid = $t.p.toppager; elemids = $t.p.id+"_top"; } if($t.p.direction == "rtl") { $(navtbl).attr("dir","rtl").css("float","right"); } if (o.add) { pAdd = pAdd || {}; tbd = $("<td class='ui-pg-button ui-corner-all'></td>"); $(tbd).append("<div class='ui-pg-div'><span class='ui-icon "+o.addicon+"'></span>"+o.addtext+"</div>"); $("tr",navtbl).append(tbd); $(tbd,navtbl) .attr({"title":o.addtitle || "",id : pAdd.id || "add_"+elemids}) .click(function(){ if (!$(this).hasClass('ui-state-disabled')) { if (typeof o.addfunc == 'function') { o.addfunc(); } else { $($t).jqGrid("editGridRow","new",pAdd); } } return false; }).hover( function () { if (!$(this).hasClass('ui-state-disabled')) { $(this).addClass("ui-state-hover"); } }, function () {$(this).removeClass("ui-state-hover");} ); tbd = null; } if (o.edit) { tbd = $("<td class='ui-pg-button ui-corner-all'></td>"); pEdit = pEdit || {}; $(tbd).append("<div class='ui-pg-div'><span class='ui-icon "+o.editicon+"'></span>"+o.edittext+"</div>"); $("tr",navtbl).append(tbd); $(tbd,navtbl) .attr({"title":o.edittitle || "",id: pEdit.id || "edit_"+elemids}) .click(function(){ if (!$(this).hasClass('ui-state-disabled')) { var sr = $t.p.selrow; if (sr) { if(typeof o.editfunc == 'function') { o.editfunc(sr); } else { $($t).jqGrid("editGridRow",sr,pEdit); } } else { $.jgrid.viewModal("#"+alertIDs.themodal,{gbox:"#gbox_"+$t.p.id,jqm:true}); $("#jqg_alrt").focus(); } } return false; }).hover( function () { if (!$(this).hasClass('ui-state-disabled')) { $(this).addClass("ui-state-hover"); } }, function () {$(this).removeClass("ui-state-hover");} ); tbd = null; } if (o.view) { tbd = $("<td class='ui-pg-button ui-corner-all'></td>"); pView = pView || {}; $(tbd).append("<div class='ui-pg-div'><span class='ui-icon "+o.viewicon+"'></span>"+o.viewtext+"</div>"); $("tr",navtbl).append(tbd); $(tbd,navtbl) .attr({"title":o.viewtitle || "",id: pView.id || "view_"+elemids}) .click(function(){ if (!$(this).hasClass('ui-state-disabled')) { var sr = $t.p.selrow; if (sr) { $($t).jqGrid("viewGridRow",sr,pView); } else { $.jgrid.viewModal("#"+alertIDs.themodal,{gbox:"#gbox_"+$t.p.id,jqm:true}); $("#jqg_alrt").focus(); } } return false; }).hover( function () { if (!$(this).hasClass('ui-state-disabled')) { $(this).addClass("ui-state-hover"); } }, function () {$(this).removeClass("ui-state-hover");} ); tbd = null; } if (o.del) { tbd = $("<td class='ui-pg-button ui-corner-all'></td>"); pDel = pDel || {}; $(tbd).append("<div class='ui-pg-div'><span class='ui-icon "+o.delicon+"'></span>"+o.deltext+"</div>"); $("tr",navtbl).append(tbd); $(tbd,navtbl) .attr({"title":o.deltitle || "",id: pDel.id || "del_"+elemids}) .click(function(){ if (!$(this).hasClass('ui-state-disabled')) { var dr; if($t.p.multiselect) { dr = $t.p.selarrrow; if(dr.length===0) { dr = null; } } else { dr = $t.p.selrow; } if(dr){ if("function" == typeof o.delfunc){ o.delfunc(dr); }else{ $($t).jqGrid("delGridRow",dr,pDel); } } else { $.jgrid.viewModal("#"+alertIDs.themodal,{gbox:"#gbox_"+$t.p.id,jqm:true}); $("#jqg_alrt").focus(); } } return false; }).hover( function () { if (!$(this).hasClass('ui-state-disabled')) { $(this).addClass("ui-state-hover"); } }, function () {$(this).removeClass("ui-state-hover");} ); tbd = null; } if(o.add || o.edit || o.del || o.view) { $("tr",navtbl).append(sep); } if (o.search) { tbd = $("<td class='ui-pg-button ui-corner-all'></td>"); pSearch = pSearch || {}; $(tbd).append("<div class='ui-pg-div'><span class='ui-icon "+o.searchicon+"'></span>"+o.searchtext+"</div>"); $("tr",navtbl).append(tbd); $(tbd,navtbl) .attr({"title":o.searchtitle || "",id:pSearch.id || "search_"+elemids}) .click(function(){ if (!$(this).hasClass('ui-state-disabled')) { $($t).jqGrid("searchGrid",pSearch); } return false; }).hover( function () { if (!$(this).hasClass('ui-state-disabled')) { $(this).addClass("ui-state-hover"); } }, function () {$(this).removeClass("ui-state-hover");} ); tbd = null; } if (o.refresh) { tbd = $("<td class='ui-pg-button ui-corner-all'></td>"); $(tbd).append("<div class='ui-pg-div'><span class='ui-icon "+o.refreshicon+"'></span>"+o.refreshtext+"</div>"); $("tr",navtbl).append(tbd); $(tbd,navtbl) .attr({"title":o.refreshtitle || "",id: "refresh_"+elemids}) .click(function(){ if (!$(this).hasClass('ui-state-disabled')) { if($.isFunction(o.beforeRefresh)) { o.beforeRefresh(); } $t.p.search = false; try { var gID = $t.p.id; $("#fbox_"+gID).searchFilter().reset({"reload":false}); if($.isFunction($t.clearToolbar)) { $t.clearToolbar(false); } } catch (e) {} switch (o.refreshstate) { case 'firstpage': $($t).trigger("reloadGrid", [{page:1}]); break; case 'current': $($t).trigger("reloadGrid", [{current:true}]); break; } if($.isFunction(o.afterRefresh)) { o.afterRefresh(); } } return false; }).hover( function () { if (!$(this).hasClass('ui-state-disabled')) { $(this).addClass("ui-state-hover"); } }, function () {$(this).removeClass("ui-state-hover");} ); tbd = null; } tdw = $(".ui-jqgrid").css("font-size") || "11px"; $('body').append("<div id='testpg2' class='ui-jqgrid ui-widget ui-widget-content' style='font-size:"+tdw+";visibility:hidden;' ></div>"); twd = $(navtbl).clone().appendTo("#testpg2").width(); $("#testpg2").remove(); $(pgid+"_"+o.position,pgid).append(navtbl); if($t.p._nvtd) { if(twd > $t.p._nvtd[0] ) { $(pgid+"_"+o.position,pgid).width(twd); $t.p._nvtd[0] = twd; } $t.p._nvtd[1] = twd; } tdw =null; twd=null; navtbl =null; } }); }, navButtonAdd : function (elem, p) { p = $.extend({ caption : "newButton", title: '', buttonicon : 'ui-icon-newwin', onClickButton: null, position : "last", cursor : 'pointer' }, p ||{}); return this.each(function() { if( !this.grid) { return; } if( elem.indexOf("#") !== 0) { elem = "#"+elem; } var findnav = $(".navtable",elem)[0], $t = this; if (findnav) { var tbd = $("<td></td>"); if(p.buttonicon.toString().toUpperCase() == "NONE") { $(tbd).addClass('ui-pg-button ui-corner-all').append("<div class='ui-pg-div'>"+p.caption+"</div>"); } else { $(tbd).addClass('ui-pg-button ui-corner-all').append("<div class='ui-pg-div'><span class='ui-icon "+p.buttonicon+"'></span>"+p.caption+"</div>"); } if(p.id) {$(tbd).attr("id",p.id);} if(p.position=='first'){ if(findnav.rows[0].cells.length ===0 ) { $("tr",findnav).append(tbd); } else { $("tr td:eq(0)",findnav).before(tbd); } } else { $("tr",findnav).append(tbd); } $(tbd,findnav) .attr("title",p.title || "") .click(function(e){ if (!$(this).hasClass('ui-state-disabled')) { if ($.isFunction(p.onClickButton) ) { p.onClickButton.call($t,e); } } return false; }) .hover( function () { if (!$(this).hasClass('ui-state-disabled')) { $(this).addClass('ui-state-hover'); } }, function () {$(this).removeClass("ui-state-hover");} ); } }); }, navSeparatorAdd:function (elem,p) { p = $.extend({ sepclass : "ui-separator", sepcontent: '' }, p ||{}); return this.each(function() { if( !this.grid) { return; } if( elem.indexOf("#") !== 0) { elem = "#"+elem; } var findnav = $(".navtable",elem)[0]; if(findnav) { var sep = "<td class='ui-pg-button ui-state-disabled' style='width:4px;'><span class='"+p.sepclass+"'></span>"+p.sepcontent+"</td>"; $("tr",findnav).append(sep); } }); }, GridToForm : function( rowid, formid ) { return this.each(function(){ var $t = this; if (!$t.grid) { return; } var rowdata = $($t).jqGrid("getRowData",rowid); if (rowdata) { for(var i in rowdata) { if ( $("[name="+i+"]",formid).is("input:radio") || $("[name="+i+"]",formid).is("input:checkbox")) { $("[name="+i+"]",formid).each( function() { if( $(this).val() == rowdata[i] ) { $(this).attr("checked","checked"); } else { $(this).attr("checked",""); } }); } else { // this is very slow on big table and form. $("[name="+i+"]",formid).val(rowdata[i]); } } } }); }, FormToGrid : function(rowid, formid, mode, position){ return this.each(function() { var $t = this; if(!$t.grid) { return; } if(!mode) { mode = 'set'; } if(!position) { position = 'first'; } var fields = $(formid).serializeArray(); var griddata = {}; $.each(fields, function(i, field){ griddata[field.name] = field.value; }); if(mode=='add') { $($t).jqGrid("addRowData",rowid,griddata, position); } else if(mode=='set') { $($t).jqGrid("setRowData",rowid,griddata); } }); } }); })(jQuery);
JavaScript
;(function($){ /** * jqGrid extension for manipulating columns properties * Piotr Roznicki roznicki@o2.pl * http://www.roznicki.prv.pl * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl-2.0.html **/ $.jgrid.extend({ setColumns : function(p) { p = $.extend({ top : 0, left: 0, width: 200, height: 'auto', dataheight: 'auto', modal: false, drag: true, beforeShowForm: null, afterShowForm: null, afterSubmitForm: null, closeOnEscape : true, ShrinkToFit : false, jqModal : false, saveicon: [true,"left","ui-icon-disk"], closeicon: [true,"left","ui-icon-close"], onClose : null, colnameview : true, closeAfterSubmit : true, updateAfterCheck : false, recreateForm : false }, $.jgrid.col, p ||{}); return this.each(function(){ var $t = this; if (!$t.grid ) { return; } var onBeforeShow = typeof p.beforeShowForm === 'function' ? true: false; var onAfterShow = typeof p.afterShowForm === 'function' ? true: false; var onAfterSubmit = typeof p.afterSubmitForm === 'function' ? true: false; var gID = $t.p.id, dtbl = "ColTbl_"+gID, IDs = {themodal:'colmod'+gID,modalhead:'colhd'+gID,modalcontent:'colcnt'+gID, scrollelm: dtbl}; if(p.recreateForm===true && $("#"+IDs.themodal).html() != null) { $("#"+IDs.themodal).remove(); } if ( $("#"+IDs.themodal).html() != null ) { if(onBeforeShow) { p.beforeShowForm($("#"+dtbl)); } $.jgrid.viewModal("#"+IDs.themodal,{gbox:"#gbox_"+gID,jqm:p.jqModal, jqM:false, modal:p.modal}); if(onAfterShow) { p.afterShowForm($("#"+dtbl)); } } else { var dh = isNaN(p.dataheight) ? p.dataheight : p.dataheight+"px"; var formdata = "<div id='"+dtbl+"' class='formdata' style='width:100%;overflow:auto;position:relative;height:"+dh+";'>"; formdata += "<table class='ColTable' cellspacing='1' cellpading='2' border='0'><tbody>"; for(i=0;i<this.p.colNames.length;i++){ if(!$t.p.colModel[i].hidedlg) { // added from T. Tomov formdata += "<tr><td style='white-space: pre;'><input type='checkbox' style='margin-right:5px;' id='col_" + this.p.colModel[i].name + "' class='cbox' value='T' " + ((this.p.colModel[i].hidden===false)?"checked":"") + "/>" + "<label for='col_" + this.p.colModel[i].name + "'>" + this.p.colNames[i] + ((p.colnameview) ? " (" + this.p.colModel[i].name + ")" : "" )+ "</label></td></tr>"; } } formdata += "</tbody></table></div>" var bS = !p.updateAfterCheck ? "<a href='javascript:void(0)' id='dData' class='fm-button ui-state-default ui-corner-all'>"+p.bSubmit+"</a>" : "", bC ="<a href='javascript:void(0)' id='eData' class='fm-button ui-state-default ui-corner-all'>"+p.bCancel+"</a>"; formdata += "<table border='0' class='EditTable' id='"+dtbl+"_2'><tbody><tr style='display:block;height:3px;'><td></td></tr><tr><td class='DataTD ui-widget-content'></td></tr><tr><td class='ColButton EditButton'>"+bS+"&#160;"+bC+"</td></tr></tbody></table>"; p.gbox = "#gbox_"+gID; $.jgrid.createModal(IDs,formdata,p,"#gview_"+$t.p.id,$("#gview_"+$t.p.id)[0]); if(p.saveicon[0]==true) { $("#dData","#"+dtbl+"_2").addClass(p.saveicon[1] == "right" ? 'fm-button-icon-right' : 'fm-button-icon-left') .append("<span class='ui-icon "+p.saveicon[2]+"'></span>"); } if(p.closeicon[0]==true) { $("#eData","#"+dtbl+"_2").addClass(p.closeicon[1] == "right" ? 'fm-button-icon-right' : 'fm-button-icon-left') .append("<span class='ui-icon "+p.closeicon[2]+"'></span>"); } if(!p.updateAfterCheck) { $("#dData","#"+dtbl+"_2").click(function(e){ for(i=0;i<$t.p.colModel.length;i++){ if(!$t.p.colModel[i].hidedlg) { // added from T. Tomov var nm = $t.p.colModel[i].name.replace(/\./g, "\\."); if($("#col_" + nm,"#"+dtbl).attr("checked")) { $($t).jqGrid("showCol",$t.p.colModel[i].name); $("#col_" + nm,"#"+dtbl).attr("defaultChecked",true); // Added from T. Tomov IE BUG } else { $($t).jqGrid("hideCol",$t.p.colModel[i].name); $("#col_" + nm,"#"+dtbl).attr("defaultChecked",""); // Added from T. Tomov IE BUG } } } if(p.ShrinkToFit===true) { $($t).jqGrid("setGridWidth",$t.grid.width-0.001,true); } if(p.closeAfterSubmit) $.jgrid.hideModal("#"+IDs.themodal,{gb:"#gbox_"+gID,jqm:p.jqModal, onClose: p.onClose}); if (onAfterSubmit) { p.afterSubmitForm($("#"+dtbl)); } return false; }); } else { $(":input","#"+dtbl).click(function(e){ var cn = this.id.substr(4); if(cn){ if(this.checked) { $($t).jqGrid("showCol",cn); } else { $($t).jqGrid("hideCol",cn); } if(p.ShrinkToFit===true) { $($t).jqGrid("setGridWidth",$t.grid.width-0.001,true); } } return this; }); } $("#eData", "#"+dtbl+"_2").click(function(e){ $.jgrid.hideModal("#"+IDs.themodal,{gb:"#gbox_"+gID,jqm:p.jqModal, onClose: p.onClose}); return false; }); $("#dData, #eData","#"+dtbl+"_2").hover( function(){$(this).addClass('ui-state-hover');}, function(){$(this).removeClass('ui-state-hover');} ); if(onBeforeShow) { p.beforeShowForm($("#"+dtbl)); } $.jgrid.viewModal("#"+IDs.themodal,{gbox:"#gbox_"+gID,jqm:p.jqModal, jqM: true, modal:p.modal}); if(onAfterShow) { p.afterShowForm($("#"+dtbl)); } } }); } }); })(jQuery);
JavaScript
;(function($){ /** * jqGrid extension * Paul Tiseo ptiseo@wasteconsultants.com * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl-2.0.html **/ $.jgrid.extend({ getPostData : function(){ var $t = this[0]; if(!$t.grid) { return; } return $t.p.postData; }, setPostData : function( newdata ) { var $t = this[0]; if(!$t.grid) { return; } // check if newdata is correct type if ( typeof(newdata) === 'object' ) { $t.p.postData = newdata; } else { alert("Error: cannot add a non-object postData value. postData unchanged."); } }, appendPostData : function( newdata ) { var $t = this[0]; if(!$t.grid) { return; } // check if newdata is correct type if ( typeof(newdata) === 'object' ) { $.extend($t.p.postData, newdata); } else { alert("Error: cannot append a non-object postData value. postData unchanged."); } }, setPostDataItem : function( key, val ) { var $t = this[0]; if(!$t.grid) { return; } $t.p.postData[key] = val; }, getPostDataItem : function( key ) { var $t = this[0]; if(!$t.grid) { return; } return $t.p.postData[key]; }, removePostDataItem : function( key ) { var $t = this[0]; if(!$t.grid) { return; } delete $t.p.postData[key]; }, getUserData : function(){ var $t = this[0]; if(!$t.grid) { return; } return $t.p.userData; }, getUserDataItem : function( key ) { var $t = this[0]; if(!$t.grid) { return; } return $t.p.userData[key]; } }); })(jQuery);
JavaScript
;(function($){ /* * jqGrid common function * Tony Tomov tony@trirand.com * http://trirand.com/blog/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl-2.0.html */ $.extend($.jgrid,{ // Modal functions showModal : function(h) { h.w.show(); }, closeModal : function(h) { h.w.hide().attr("aria-hidden","true"); if(h.o) { h.o.remove(); } }, hideModal : function (selector,o) { o = $.extend({jqm : true, gb :''}, o || {}); if(o.onClose) { var oncret = o.onClose(selector); if (typeof oncret == 'boolean' && !oncret ) { return; } } if ($.fn.jqm && o.jqm === true) { $(selector).attr("aria-hidden","true").jqmHide(); } else { if(o.gb !== '') { try {$(".jqgrid-overlay:first",o.gb).hide();} catch (e){} } $(selector).hide().attr("aria-hidden","true"); } }, //Helper functions findPos : function(obj) { var curleft = 0, curtop = 0; if (obj.offsetParent) { do { curleft += obj.offsetLeft; curtop += obj.offsetTop; } while (obj = obj.offsetParent); //do not change obj == obj.offsetParent } return [curleft,curtop]; }, createModal : function(aIDs, content, p, insertSelector, posSelector, appendsel) { var mw = document.createElement('div'), rtlsup, self = this; rtlsup = $(p.gbox).attr("dir") == "rtl" ? true : false; mw.className= "ui-widget ui-widget-content ui-corner-all ui-jqdialog"; mw.id = aIDs.themodal; var mh = document.createElement('div'); mh.className = "ui-jqdialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix"; mh.id = aIDs.modalhead; $(mh).append("<span class='ui-jqdialog-title'>"+p.caption+"</span>"); var ahr= $("<a href='javascript:void(0)' class='ui-jqdialog-titlebar-close ui-corner-all'></a>") .hover(function(){ahr.addClass('ui-state-hover');}, function(){ahr.removeClass('ui-state-hover');}) .append("<span class='ui-icon ui-icon-closethick'></span>"); $(mh).append(ahr); if(rtlsup) { mw.dir = "rtl"; $(".ui-jqdialog-title",mh).css("float","right"); $(".ui-jqdialog-titlebar-close",mh).css("left",0.3+"em"); } else { mw.dir = "ltr"; $(".ui-jqdialog-title",mh).css("float","left"); $(".ui-jqdialog-titlebar-close",mh).css("right",0.3+"em"); } var mc = document.createElement('div'); $(mc).addClass("ui-jqdialog-content ui-widget-content").attr("id",aIDs.modalcontent); $(mc).append(content); mw.appendChild(mc); $(mw).prepend(mh); if(appendsel===true) { $('body').append(mw); } //append as first child in body -for alert dialog else {$(mw).insertBefore(insertSelector);} if(typeof p.jqModal === 'undefined') {p.jqModal = true;} // internal use var coord = {}; if ( $.fn.jqm && p.jqModal === true) { if(p.left ===0 && p.top===0) { var pos = []; pos = this.findPos(posSelector); p.left = pos[0] + 4; p.top = pos[1] + 4; } coord.top = p.top+"px"; coord.left = p.left; } else if(p.left !==0 || p.top!==0) { coord.left = p.left; coord.top = p.top+"px"; } $("a.ui-jqdialog-titlebar-close",mh).click(function(e){ var oncm = $("#"+aIDs.themodal).data("onClose") || p.onClose; var gboxclose = $("#"+aIDs.themodal).data("gbox") || p.gbox; self.hideModal("#"+aIDs.themodal,{gb:gboxclose,jqm:p.jqModal,onClose:oncm}); return false; }); if (p.width === 0 || !p.width) {p.width = 300;} if(p.height === 0 || !p.height) {p.height =200;} if(!p.zIndex) { var parentZ = $(insertSelector).parents("*[role=dialog]").first().css("z-index") if(parentZ) p.zIndex = parseInt(parentZ)+1 else p.zIndex = 950; } var rtlt = 0; if( rtlsup && coord.left && !appendsel) { rtlt = $(p.gbox).width()- (!isNaN(p.width) ? parseInt(p.width,10) :0) - 8; // to do // just in case coord.left = parseInt(coord.left,10) + parseInt(rtlt,10); } if(coord.left) { coord.left += "px"; } $(mw).css($.extend({ width: isNaN(p.width) ? "auto": p.width+"px", height:isNaN(p.height) ? "auto" : p.height + "px", zIndex:p.zIndex, overflow: 'hidden' },coord)) .attr({tabIndex: "-1","role":"dialog","aria-labelledby":aIDs.modalhead,"aria-hidden":"true"}); if(typeof p.drag == 'undefined') { p.drag=true;} if(typeof p.resize == 'undefined') {p.resize=true;} if (p.drag) { $(mh).css('cursor','move'); if($.fn.jqDrag) { $(mw).jqDrag(mh); } else { try { $(mw).draggable({handle: $("#"+mh.id)}); } catch (e) {} } } if(p.resize) { if($.fn.jqResize) { $(mw).append("<div class='jqResize ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se ui-icon-grip-diagonal-se'></div>"); $("#"+aIDs.themodal).jqResize(".jqResize",aIDs.scrollelm ? "#"+aIDs.scrollelm : false); } else { try { $(mw).resizable({handles: 'se, sw',alsoResize: aIDs.scrollelm ? "#"+aIDs.scrollelm : false}); } catch (e) {} } } if(p.closeOnEscape === true){ $(mw).keydown( function( e ) { if( e.which == 27 ) { var cone = $("#"+aIDs.themodal).data("onClose") || p.onClose; self.hideModal(this,{gb:p.gbox,jqm:p.jqModal,onClose: cone}); } }); } }, viewModal : function (selector,o){ o = $.extend({ toTop: true, overlay: 10, modal: false, onShow: this.showModal, onHide: this.closeModal, gbox: '', jqm : true, jqM : true }, o || {}); if ($.fn.jqm && o.jqm === true) { if(o.jqM) { $(selector).attr("aria-hidden","false").jqm(o).jqmShow(); } else {$(selector).attr("aria-hidden","false").jqmShow();} } else { if(o.gbox !== '') { $(".jqgrid-overlay:first",o.gbox).show(); $(selector).data("gbox",o.gbox); } $(selector).show().attr("aria-hidden","false"); try{$(':input:visible',selector)[0].focus();}catch(_){} } }, info_dialog : function(caption, content,c_b, modalopt) { var mopt = { width:290, height:'auto', dataheight: 'auto', drag: true, resize: false, caption:"<b>"+caption+"</b>", left:250, top:170, zIndex : 1000, jqModal : true, modal : false, closeOnEscape : true, align: 'center', buttonalign : 'center', buttons : [] // {text:'textbutt', id:"buttid", onClick : function(){...}} // if the id is not provided we set it like info_button_+ the index in the array - i.e info_button_0,info_button_1... }; $.extend(mopt,modalopt || {}); var jm = mopt.jqModal, self = this; if($.fn.jqm && !jm) { jm = false; } // in case there is no jqModal var buttstr =""; if(mopt.buttons.length > 0) { for(var i=0;i<mopt.buttons.length;i++) { if(typeof mopt.buttons[i].id == "undefined") { mopt.buttons[i].id = "info_button_"+i; } buttstr += "<a href='javascript:void(0)' id='"+mopt.buttons[i].id+"' class='fm-button ui-state-default ui-corner-all'>"+mopt.buttons[i].text+"</a>"; } } var dh = isNaN(mopt.dataheight) ? mopt.dataheight : mopt.dataheight+"px", cn = "text-align:"+mopt.align+";"; var cnt = "<div id='info_id'>"; cnt += "<div id='infocnt' style='margin:0px;padding-bottom:1em;width:100%;overflow:auto;position:relative;height:"+dh+";"+cn+"'>"+content+"</div>"; cnt += c_b ? "<div class='ui-widget-content ui-helper-clearfix' style='text-align:"+mopt.buttonalign+";padding-bottom:0.8em;padding-top:0.5em;background-image: none;border-width: 1px 0 0 0;'><a href='javascript:void(0)' id='closedialog' class='fm-button ui-state-default ui-corner-all'>"+c_b+"</a>"+buttstr+"</div>" : buttstr !== "" ? "<div class='ui-widget-content ui-helper-clearfix' style='text-align:"+mopt.buttonalign+";padding-bottom:0.8em;padding-top:0.5em;background-image: none;border-width: 1px 0 0 0;'>"+buttstr+"</div>" : ""; cnt += "</div>"; try { if($("#info_dialog").attr("aria-hidden") == "false") { this.hideModal("#info_dialog",{jqm:jm}); } $("#info_dialog").remove(); } catch (e){} this.createModal({ themodal:'info_dialog', modalhead:'info_head', modalcontent:'info_content', scrollelm: 'infocnt'}, cnt, mopt, '','',true ); // attach onclick after inserting into the dom if(buttstr) { $.each(mopt.buttons,function(i){ $("#"+this.id,"#info_id").bind('click',function(){mopt.buttons[i].onClick.call($("#info_dialog")); return false;}); }); } $("#closedialog", "#info_id").click(function(e){ self.hideModal("#info_dialog",{jqm:jm}); return false; }); $(".fm-button","#info_dialog").hover( function(){$(this).addClass('ui-state-hover');}, function(){$(this).removeClass('ui-state-hover');} ); if($.isFunction(mopt.beforeOpen) ) { mopt.beforeOpen(); } this.viewModal("#info_dialog",{ onHide: function(h) { h.w.hide().remove(); if(h.o) { h.o.remove(); } }, modal :mopt.modal, jqm:jm }); if($.isFunction(mopt.afterOpen) ) { mopt.afterOpen(); } try{ $("#info_dialog").focus();} catch (e){} }, // Form Functions createEl : function(eltype,options,vl,autowidth, ajaxso) { var elem = ""; if(options.defaultValue) { delete options.defaultValue; } function bindEv (el, opt) { if($.isFunction(opt.dataInit)) { // datepicker fix el.id = opt.id; opt.dataInit(el); delete opt.id; delete opt.dataInit; } if(opt.dataEvents) { $.each(opt.dataEvents, function() { if (this.data !== undefined) { $(el).bind(this.type, this.data, this.fn); } else { $(el).bind(this.type, this.fn); } }); delete opt.dataEvents; } return opt; } switch (eltype) { case "textarea" : elem = document.createElement("textarea"); if(autowidth) { if(!options.cols) { $(elem).css({width:"98%"});} } else if (!options.cols) { options.cols = 20; } if(!options.rows) { options.rows = 2; } if(vl=='&nbsp;' || vl=='&#160;' || (vl.length==1 && vl.charCodeAt(0)==160)) {vl="";} elem.value = vl; options = bindEv(elem,options); $(elem).attr(options).attr({"role":"textbox","multiline":"true"}); break; case "checkbox" : //what code for simple checkbox elem = document.createElement("input"); elem.type = "checkbox"; if( !options.value ) { var vl1 = vl.toLowerCase(); if(vl1.search(/(false|0|no|off|undefined)/i)<0 && vl1!=="") { elem.checked=true; elem.defaultChecked=true; elem.value = vl; } else { elem.value = "on"; } $(elem).attr("offval","off"); } else { var cbval = options.value.split(":"); if(vl === cbval[0]) { elem.checked=true; elem.defaultChecked=true; } elem.value = cbval[0]; $(elem).attr("offval",cbval[1]); try {delete options.value;} catch (e){} } options = bindEv(elem,options); $(elem).attr(options).attr("role","checkbox"); break; case "select" : elem = document.createElement("select"); elem.setAttribute("role","select"); var msl, ovm = []; if(options.multiple===true) { msl = true; elem.multiple="multiple"; $(elem).attr("aria-multiselectable","true"); } else { msl = false; } if(typeof(options.dataUrl) != "undefined") { $.ajax($.extend({ url: options.dataUrl, type : "GET", dataType: "html", success: function(data,status){ try {delete options.dataUrl; delete options.value;} catch (e){} var a; if(typeof(options.buildSelect) != "undefined") { var b = options.buildSelect(data); a = $(b).html(); delete options.buildSelect; } else { a = $(data).html(); } if(a) { $(elem).append(a); options = bindEv(elem,options); if(typeof options.size === 'undefined') { options.size = msl ? 3 : 1;} if(msl) { ovm = vl.split(","); ovm = $.map(ovm,function(n){return $.trim(n);}); } else { ovm[0] = $.trim(vl); } $(elem).attr(options); setTimeout(function(){ $("option",elem).each(function(i){ if(i===0) { this.selected = ""; } $(this).attr("role","option"); if($.inArray($.trim($(this).text()),ovm) > -1 || $.inArray($.trim($(this).val()),ovm) > -1 ) { this.selected= "selected"; if(!msl) { return false; } } }); },0); } } },ajaxso || {})); } else if(options.value) { var i; if(msl) { ovm = vl.split(","); ovm = $.map(ovm,function(n){return $.trim(n);}); if(typeof options.size === 'undefined') {options.size = 3;} } else { options.size = 1; } if(typeof options.value === 'function') { options.value = options.value(); } var so,sv, ov; if(typeof options.value === 'string') { so = options.value.split(";"); for(i=0; i<so.length;i++){ sv = so[i].split(":"); if(sv.length > 2 ) { sv[1] = $.map(sv,function(n,i){if(i>0) { return n;} }).join(":"); } ov = document.createElement("option"); ov.setAttribute("role","option"); ov.value = sv[0]; ov.innerHTML = sv[1]; if (!msl && ($.trim(sv[0]) == $.trim(vl) || $.trim(sv[1]) == $.trim(vl))) { ov.selected ="selected"; } if (msl && ($.inArray($.trim(sv[1]), ovm)>-1 || $.inArray($.trim(sv[0]), ovm)>-1)) {ov.selected ="selected";} elem.appendChild(ov); } } else if (typeof options.value === 'object') { var oSv = options.value; for ( var key in oSv) { if (oSv.hasOwnProperty(key ) ){ ov = document.createElement("option"); ov.setAttribute("role","option"); ov.value = key; ov.innerHTML = oSv[key]; if (!msl && ( $.trim(key) == $.trim(vl) || $.trim(oSv[key]) == $.trim(vl)) ) { ov.selected ="selected"; } if (msl && ($.inArray($.trim(oSv[key]),ovm)>-1 || $.inArray($.trim(key),ovm)>-1)) { ov.selected ="selected"; } elem.appendChild(ov); } } } options = bindEv(elem,options); try {delete options.value;} catch (e){} $(elem).attr(options); } break; case "text" : case "password" : case "button" : var role; if(eltype=="button") { role = "button"; } else { role = "textbox"; } elem = document.createElement("input"); elem.type = eltype; elem.value = vl; options = bindEv(elem,options); if(eltype != "button"){ if(autowidth) { if(!options.size) { $(elem).css({width:"98%"}); } } else if (!options.size) { options.size = 20; } } $(elem).attr(options).attr("role",role); break; case "image" : case "file" : elem = document.createElement("input"); elem.type = eltype; options = bindEv(elem,options); $(elem).attr(options); break; case "custom" : elem = document.createElement("span"); try { if($.isFunction(options.custom_element)) { var celm = options.custom_element.call(this,vl,options); if(celm) { celm = $(celm).addClass("customelement").attr({id:options.id,name:options.name}); $(elem).empty().append(celm); } else { throw "e2"; } } else { throw "e1"; } } catch (e) { if (e=="e1") { this.info_dialog($.jgrid.errors.errcap,"function 'custom_element' "+$.jgrid.edit.msg.nodefined, $.jgrid.edit.bClose);} if (e=="e2") { this.info_dialog($.jgrid.errors.errcap,"function 'custom_element' "+$.jgrid.edit.msg.novalue,$.jgrid.edit.bClose);} else { this.info_dialog($.jgrid.errors.errcap,typeof(e)==="string"?e:e.message,$.jgrid.edit.bClose); } } break; } return elem; }, // Date Validation Javascript checkDate : function (format, date) { var daysInFebruary = function(year){ // February has 29 days in any year evenly divisible by four, // EXCEPT for centurial years which are not also divisible by 400. return (((year % 4 === 0) && ( year % 100 !== 0 || (year % 400 === 0))) ? 29 : 28 ); }, DaysArray = function(n) { for (var i = 1; i <= n; i++) { this[i] = 31; if (i==4 || i==6 || i==9 || i==11) {this[i] = 30;} if (i==2) {this[i] = 29;} } return this; }; var tsp = {}, sep; format = format.toLowerCase(); //we search for /,-,. for the date separator if(format.indexOf("/") != -1) { sep = "/"; } else if(format.indexOf("-") != -1) { sep = "-"; } else if(format.indexOf(".") != -1) { sep = "."; } else { sep = "/"; } format = format.split(sep); date = date.split(sep); if (date.length != 3) { return false; } var j=-1,yln, dln=-1, mln=-1; for(var i=0;i<format.length;i++){ var dv = isNaN(date[i]) ? 0 : parseInt(date[i],10); tsp[format[i]] = dv; yln = format[i]; if(yln.indexOf("y") != -1) { j=i; } if(yln.indexOf("m") != -1) { mln=i; } if(yln.indexOf("d") != -1) { dln=i; } } if (format[j] == "y" || format[j] == "yyyy") { yln=4; } else if(format[j] =="yy"){ yln = 2; } else { yln = -1; } var daysInMonth = DaysArray(12), strDate; if (j === -1) { return false; } else { strDate = tsp[format[j]].toString(); if(yln == 2 && strDate.length == 1) {yln = 1;} if (strDate.length != yln || (tsp[format[j]]===0 && date[j]!="00")){ return false; } } if(mln === -1) { return false; } else { strDate = tsp[format[mln]].toString(); if (strDate.length<1 || tsp[format[mln]]<1 || tsp[format[mln]]>12){ return false; } } if(dln === -1) { return false; } else { strDate = tsp[format[dln]].toString(); if (strDate.length<1 || tsp[format[dln]]<1 || tsp[format[dln]]>31 || (tsp[format[mln]]==2 && tsp[format[dln]]>daysInFebruary(tsp[format[j]])) || tsp[format[dln]] > daysInMonth[tsp[format[mln]]]){ return false; } } return true; }, isEmpty : function(val) { if (val.match(/^\s+$/) || val === "") { return true; } else { return false; } }, checkTime : function(time){ // checks only hh:ss (and optional am/pm) var re = /^(\d{1,2}):(\d{2})([ap]m)?$/,regs; if(!this.isEmpty(time)) { regs = time.match(re); if(regs) { if(regs[3]) { if(regs[1] < 1 || regs[1] > 12) { return false; } } else { if(regs[1] > 23) { return false; } } if(regs[2] > 59) { return false; } } else { return false; } } return true; }, checkValues : function(val, valref,g) { var edtrul,i, nm, dft, len; if(typeof(valref)=='string'){ for( i =0, len=g.p.colModel.length;i<len; i++){ if(g.p.colModel[i].name==valref) { edtrul = g.p.colModel[i].editrules; valref = i; try { nm = g.p.colModel[i].formoptions.label; } catch (e) {} break; } } } else if(valref >=0) { edtrul = g.p.colModel[valref].editrules; } if(edtrul) { if(!nm) { nm = g.p.colNames[valref]; } if(edtrul.required === true) { if( this.isEmpty(val) ) { return [false,nm+": "+$.jgrid.edit.msg.required,""]; } } // force required var rqfield = edtrul.required === false ? false : true; if(edtrul.number === true) { if( !(rqfield === false && this.isEmpty(val)) ) { if(isNaN(val)) { return [false,nm+": "+$.jgrid.edit.msg.number,""]; } } } if(typeof edtrul.minValue != 'undefined' && !isNaN(edtrul.minValue)) { if (parseFloat(val) < parseFloat(edtrul.minValue) ) { return [false,nm+": "+$.jgrid.edit.msg.minValue+" "+edtrul.minValue,""];} } if(typeof edtrul.maxValue != 'undefined' && !isNaN(edtrul.maxValue)) { if (parseFloat(val) > parseFloat(edtrul.maxValue) ) { return [false,nm+": "+$.jgrid.edit.msg.maxValue+" "+edtrul.maxValue,""];} } var filter; if(edtrul.email === true) { if( !(rqfield === false && this.isEmpty(val)) ) { // taken from $ Validate plugin filter = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i; if(!filter.test(val)) {return [false,nm+": "+$.jgrid.edit.msg.email,""];} } } if(edtrul.integer === true) { if( !(rqfield === false && this.isEmpty(val)) ) { if(isNaN(val)) { return [false,nm+": "+$.jgrid.edit.msg.integer,""]; } if ((val % 1 !== 0) || (val.indexOf('.') != -1)) { return [false,nm+": "+$.jgrid.edit.msg.integer,""];} } } if(edtrul.date === true) { if( !(rqfield === false && this.isEmpty(val)) ) { if(g.p.colModel[valref].formatoptions && g.p.colModel[valref].formatoptions.newformat) { dft = g.p.colModel[valref].formatoptions.newformat; } else { dft = g.p.colModel[valref].datefmt || "Y-m-d"; } if(!this.checkDate (dft, val)) { return [false,nm+": "+$.jgrid.edit.msg.date+" - "+dft,""]; } } } if(edtrul.time === true) { if( !(rqfield === false && this.isEmpty(val)) ) { if(!this.checkTime (val)) { return [false,nm+": "+$.jgrid.edit.msg.date+" - hh:mm (am/pm)",""]; } } } if(edtrul.url === true) { if( !(rqfield === false && this.isEmpty(val)) ) { filter = /^(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i; if(!filter.test(val)) {return [false,nm+": "+$.jgrid.edit.msg.url,""];} } } if(edtrul.custom === true) { if( !(rqfield === false && this.isEmpty(val)) ) { if($.isFunction(edtrul.custom_func)) { var ret = edtrul.custom_func.call(g,val,nm); if($.isArray(ret)) { return ret; } else { return [false,$.jgrid.edit.msg.customarray,""]; } } else { return [false,$.jgrid.edit.msg.customfcheck,""]; } } } } return [true,"",""]; } }); })(jQuery);
JavaScript
;(function($){ /* * jqGrid extension for constructing Grid Data from external file * Tony Tomov tony@trirand.com * http://trirand.com/blog/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl-2.0.html **/ $.jgrid.extend({ jqGridImport : function(o) { o = $.extend({ imptype : "xml", // xml, json, xmlstring, jsonstring impstring: "", impurl: "", mtype: "GET", impData : {}, xmlGrid :{ config : "roots>grid", data: "roots>rows" }, jsonGrid :{ config : "grid", data: "data" }, ajaxOptions :{} }, o || {}); return this.each(function(){ var $t = this; var XmlConvert = function (xml,o) { var cnfg = $(o.xmlGrid.config,xml)[0]; var xmldata = $(o.xmlGrid.data,xml)[0], jstr, jstr1; if(xmlJsonClass.xml2json && $.jgrid.parse) { jstr = xmlJsonClass.xml2json(cnfg," "); jstr = $.jgrid.parse(jstr); for(var key in jstr) { if(jstr.hasOwnProperty(key)) { jstr1=jstr[key]; } } if(xmldata) { // save the datatype var svdatatype = jstr.grid.datatype; jstr.grid.datatype = 'xmlstring'; jstr.grid.datastr = xml; $($t).jqGrid( jstr1 ).jqGrid("setGridParam",{datatype:svdatatype}); } else { $($t).jqGrid( jstr1 ); } jstr = null;jstr1=null; } else { alert("xml2json or parse are not present"); } }; var JsonConvert = function (jsonstr,o){ if (jsonstr && typeof jsonstr == 'string') { var json = $.jgrid.parse(jsonstr); var gprm = json[o.jsonGrid.config]; var jdata = json[o.jsonGrid.data]; if(jdata) { var svdatatype = gprm.datatype; gprm.datatype = 'jsonstring'; gprm.datastr = jdata; $($t).jqGrid( gprm ).jqGrid("setGridParam",{datatype:svdatatype}); } else { $($t).jqGrid( gprm ); } } }; switch (o.imptype){ case 'xml': $.ajax($.extend({ url:o.impurl, type:o.mtype, data: o.impData, dataType:"xml", complete: function(xml,stat) { if(stat == 'success') { XmlConvert(xml.responseXML,o); if($.isFunction(o.importComplete)) { o.importComplete(xml); } } xml=null; } }, o.ajaxOptions)); break; case 'xmlstring' : // we need to make just the conversion and use the same code as xml if(o.impstring && typeof o.impstring == 'string') { var xmld = $.jgrid.stringToDoc(o.impstring); if(xmld) { XmlConvert(xmld,o); if($.isFunction(o.importComplete)) { o.importComplete(xmld); } o.impstring = null; } xmld = null; } break; case 'json': $.ajax($.extend({ url:o.impurl, type:o.mtype, data: o.impData, dataType:"json", complete: function(json,stat) { if(stat == 'success') { JsonConvert(json.responseText,o ); if($.isFunction(o.importComplete)) { o.importComplete(json); } } json=null; } }, o.ajaxOptions )); break; case 'jsonstring' : if(o.impstring && typeof o.impstring == 'string') { JsonConvert(o.impstring,o ); if($.isFunction(o.importComplete)) { o.importComplete(o.impstring); } o.impstring = null; } break; } }); }, jqGridExport : function(o) { o = $.extend({ exptype : "xmlstring", root: "grid", ident: "\t" }, o || {}); var ret = null; this.each(function () { if(!this.grid) { return;} var gprm = $.extend({},$(this).jqGrid("getGridParam")); // we need to check for: // 1.multiselect, 2.subgrid 3. treegrid and remove the unneded columns from colNames if(gprm.rownumbers) { gprm.colNames.splice(0,1); gprm.colModel.splice(0,1); } if(gprm.multiselect) { gprm.colNames.splice(0,1); gprm.colModel.splice(0,1); } if(gprm.subGrid) { gprm.colNames.splice(0,1); gprm.colModel.splice(0,1); } gprm.knv = null; if(gprm.treeGrid) { for (var key in gprm.treeReader) { if(gprm.treeReader.hasOwnProperty(key)) { gprm.colNames.splice(gprm.colNames.length-1); gprm.colModel.splice(gprm.colModel.length-1); } } } switch (o.exptype) { case 'xmlstring' : ret = "<"+o.root+">"+xmlJsonClass.json2xml(gprm,o.ident)+"</"+o.root+">"; break; case 'jsonstring' : ret = "{"+ xmlJsonClass.toJson(gprm,o.root,o.ident)+"}"; if(gprm.postData.filters !== undefined) { ret=ret.replace(/filters":"/,'filters":'); ret=ret.replace(/}]}"/,'}]}'); } break; } }); return ret; }, excelExport : function(o) { o = $.extend({ exptype : "remote", url : null, oper: "oper", tag: "excel", exportOptions : {} }, o || {}); return this.each(function(){ if(!this.grid) { return;} var url; if(o.exptype == "remote") { var pdata = $.extend({},this.p.postData); pdata[o.oper] = o.tag; var params = jQuery.param(pdata); if(o.url.indexOf("?") != -1) { url = o.url+"&"+params; } else { url = o.url+"?"+params; } window.location = url; } }); } }); })(jQuery);
JavaScript
;(function($){ /** * jqGrid Ukrainian Translation v1.0 02.07.2009 * Sergey Dyagovchenko * http://d.sumy.ua * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html **/ $.jgrid = { defaults : { recordtext: "Перегляд {0} - {1} з {2}", emptyrecords: "Немає записів для перегляду", loadtext: "Завантаження...", pgtext : "Стор. {0} з {1}" }, search : { caption: "Пошук...", Find: "Знайти", Reset: "Скидання", odata : ['рівно', 'не рівно', 'менше', 'менше або рівне','більше','більше або рівне', 'починається з','не починається з','знаходиться в','не знаходиться в','закінчується на','не закінчується на','містить','не містить'], groupOps: [ { op: "AND", text: "все" }, { op: "OR", text: "будь-який" } ], matchText: " збігається", rulesText: " правила" }, edit : { addCaption: "Додати запис", editCaption: "Змінити запис", bSubmit: "Зберегти", bCancel: "Відміна", bClose: "Закрити", saveData: "До данних були внесені зміни! Зберегти зміни?", bYes : "Так", bNo : "Ні", bExit : "Відміна", msg: { required:"Поле є обов'язковим", number:"Будь ласка, введіть правильне число", minValue:"значення повинне бути більше або дорівнює", maxValue:"значення повинно бути менше або дорівнює", email: "некоректна адреса електронної пошти", integer: "Будь ласка, введення дійсне ціле значення", date: "Будь ласка, введення дійсне значення дати", url: "не дійсний URL. Необхідна приставка ('http://' or 'https://')", nodefined : " is not defined!", novalue : " return value is required!", customarray : "Custom function should return array!", customfcheck : "Custom function should be present in case of custom checking!" } }, view : { caption: "Переглянути запис", bClose: "Закрити" }, del : { caption: "Видалити", msg: "Видалити обраний запис(и)?", bSubmit: "Видалити", bCancel: "Відміна" }, nav : { edittext: " ", edittitle: "Змінити вибраний запис", addtext:" ", addtitle: "Додати новий запис", deltext: " ", deltitle: "Видалити вибраний запис", searchtext: " ", searchtitle: "Знайти записи", refreshtext: "", refreshtitle: "Оновити таблицю", alertcap: "Попередження", alerttext: "Будь ласка, виберіть запис", viewtext: "", viewtitle: "Переглянути обраний запис" }, col : { caption: "Показати/Приховати стовпці", bSubmit: "Зберегти", bCancel: "Відміна" }, errors : { errcap : "Помилка", nourl : "URL не задан", norecords: "Немає записів для обробки", model : "Число полів не відповідає числу стовпців таблиці!" }, formatter : { integer : {thousandsSeparator: " ", defaultValue: '0'}, number : {decimalSeparator:",", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: '0,00'}, currency : {decimalSeparator:",", thousandsSeparator: " ", decimalPlaces: 2, prefix: "", suffix:"", defaultValue: '0,00'}, date : { dayNames: [ "Нд", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Неділя", "Понеділок", "Вівторок", "Середа", "Четвер", "П'ятниця", "Субота" ], monthNames: [ "Січ", "Лют", "Бер", "Кві", "Тра", "Чер", "Лип", "Сер", "Вер", "Жов", "Лис", "Гру", "Січень", "Лютий", "Березень", "Квітень", "Травень", "Червень", "Липень", "Серпень", "Вересень", "Жовтень", "Листопад", "Грудень" ], AmPm : ["am","pm","AM","PM"], S: function (j) {return j < 11 || j > 13 ? ['st', 'nd', 'rd', 'th'][Math.min((j - 1) % 10, 3)] : 'th'}, srcformat: 'Y-m-d', newformat: 'd.m.Y', masks : { ISO8601Long:"Y-m-d H:i:s", ISO8601Short:"Y-m-d", ShortDate: "n.j.Y", LongDate: "l, F d, Y", FullDateTime: "l, F d, Y G:i:s", MonthDay: "F d", ShortTime: "G:i", LongTime: "G:i:s", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "F, Y" }, reformatAfterEdit : false }, baseLinkUrl: '', showAction: '', target: '', checkbox : {disabled:true}, idName : 'id' } }; })(jQuery);
JavaScript
;(function($){ /** * jqGrid Catalan Translation * Traducció jqGrid en Catatà per Faserline, S.L. * http://www.faserline.com * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html **/ $.jgrid = { defaults : { recordtext: "Mostrant {0} - {1} de {2}", emptyrecords: "Sense registres que mostrar", loadtext: "Carregant...", pgtext : "Pàgina {0} de {1}" }, search : { caption: "Cerca...", Find: "Cercar", Reset: "Buidar", odata : ['equal', 'not equal', 'less', 'less or equal','greater','greater or equal', 'begins with','does not begin with','is in','is not in','ends with','does not end with','contains','does not contain'], groupOps: [ { op: "AND", text: "tot" }, { op: "OR", text: "qualsevol" } ], matchText: " match", rulesText: " rules" }, edit : { addCaption: "Afegir registre", editCaption: "Modificar registre", bSubmit: "Guardar", bCancel: "Cancelar", bClose: "Tancar", saveData: "Les dades han canviat. Guardar canvis?", bYes : "Yes", bNo : "No", bExit : "Cancel", msg: { required:"Camp obligatori", number:"Introdueixi un nombre", minValue:"El valor ha de ser major o igual que ", maxValue:"El valor ha de ser menor o igual a ", email: "no és una direcció de correu vàlida", integer: "Introdueixi un valor enter", date: "Introdueixi una data correcta ", url: "no és una URL vàlida. Prefix requerit ('http://' or 'https://')", nodefined : " is not defined!", novalue : " return value is required!", customarray : "Custom function should return array!", customfcheck : "Custom function should be present in case of custom checking!" } }, view : { caption: "Veure registre", bClose: "Tancar" }, del : { caption: "Eliminar", msg: "¿Desitja eliminar els registres seleccionats?", bSubmit: "Eliminar", bCancel: "Cancelar" }, nav : { edittext: " ", edittitle: "Modificar fila seleccionada", addtext:" ", addtitle: "Agregar nova fila", deltext: " ", deltitle: "Eliminar fila seleccionada", searchtext: " ", searchtitle: "Cercar informació", refreshtext: "", refreshtitle: "Refrescar taula", alertcap: "Avís", alerttext: "Seleccioni una fila", viewtext: " ", viewtitle: "Veure fila seleccionada" }, // setcolumns module col : { caption: "Mostrar/ocultar columnes", bSubmit: "Enviar", bCancel: "Cancelar" }, errors : { errcap : "Error", nourl : "No s'ha especificat una URL", norecords: "No hi ha dades per processar", model : "Les columnes de noms són diferents de les columnes del model" }, formatter : { integer : {thousandsSeparator: ".", defaultValue: '0'}, number : {decimalSeparator:",", thousandsSeparator: ".", decimalPlaces: 2, defaultValue: '0,00'}, currency : {decimalSeparator:",", thousandsSeparator: ".", decimalPlaces: 2, prefix: "", suffix:"", defaultValue: '0,00'}, date : { dayNames: [ "Dg", "Dl", "Dt", "Dc", "Dj", "Dv", "Ds", "Diumenge", "Dilluns", "Dimarts", "Dimecres", "Dijous", "Divendres", "Dissabte" ], monthNames: [ "Gen", "Febr", "Març", "Abr", "Maig", "Juny", "Jul", "Ag", "Set", "Oct", "Nov", "Des", "Gener", "Febrer", "Març", "Abril", "Maig", "Juny", "Juliol", "Agost", "Setembre", "Octubre", "Novembre", "Desembre" ], AmPm : ["am","pm","AM","PM"], S: function (j) {return j < 11 || j > 13 ? ['st', 'nd', 'rd', 'th'][Math.min((j - 1) % 10, 3)] : 'th'}, srcformat: 'Y-m-d', newformat: 'd-m-Y', masks : { ISO8601Long:"Y-m-d H:i:s", ISO8601Short:"Y-m-d", ShortDate: "n/j/Y", LongDate: "l, F d, Y", FullDateTime: "l, F d, Y g:i:s A", MonthDay: "F d", ShortTime: "g:i A", LongTime: "g:i:s A", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "F, Y" }, reformatAfterEdit : false }, baseLinkUrl: '', showAction: 'show', target: '', checkbox : {disabled:true}, idName : 'id' } }; })(jQuery);
JavaScript
;(function($){ /** * jqGrid Hebrew Translation * Shuki Shukrun shukrun.shuki@gmail.com * http://trirand.com/blog/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html **/ $.jgrid = { defaults : { recordtext: "מציג {0} - {1} מתוך {2}", emptyrecords: "אין רשומות להציג", loadtext: "טוען...", pgtext : "דף {0} מתוך {1}" }, search : { caption: "מחפש...", Find: "חפש", Reset: "התחל", odata : ['שווה', 'לא שווה', 'קטן', 'קטן או שווה','גדול','גדול או שווה', 'מתחיל ב','לא מתחיל ב','נמצא ב','לא נמצא ב','מסתיים ב','לא מסתיים ב','מכיל','לא מכיל'], groupOps: [ { op: "AND", text: "הכל" }, { op: "OR", text: "אחד מ" } ], matchText: " תואם", rulesText: " חוקים" }, edit : { addCaption: "הוסף רשומה", editCaption: "ערוך רשומה", bSubmit: "שלח", bCancel: "בטל", bClose: "סגור", saveData: "נתונים השתנו! לשמור?", bYes : "כן", bNo : "לא", bExit : "בטל", msg: { required:"שדה חובה", number:"אנא, הכנס מספר תקין", minValue:"ערך צריך להיות גדול או שווה ל ", maxValue:"ערך צריך להיות קטן או שווה ל ", email: "היא לא כתובת איימל תקינה", integer: "אנא, הכנס מספר שלם", date: "אנא, הכנס תאריך תקין", url: "הכתובת אינה תקינה. דרושה תחילית ('http://' או 'https://')", nodefined : " is not defined!", novalue : " return value is required!", customarray : "Custom function should return array!", customfcheck : "Custom function should be present in case of custom checking!" } }, view : { caption: "הצג רשומה", bClose: "סגור" }, del : { caption: "מחק", msg: "האם למחוק את הרשומה/ות המסומנות?", bSubmit: "מחק", bCancel: "בטל" }, nav : { edittext: "", edittitle: "ערוך שורה מסומנת", addtext:"", addtitle: "הוסף שורה חדשה", deltext: "", deltitle: "מחק שורה מסומנת", searchtext: "", searchtitle: "חפש רשומות", refreshtext: "", refreshtitle: "טען גריד מחדש", alertcap: "אזהרה", alerttext: "אנא, בחר שורה", viewtext: "", viewtitle: "הצג שורה מסומנת" }, col : { caption: "הצג/הסתר עמודות", bSubmit: "שלח", bCancel: "בטל" }, errors : { errcap : "שגיאה", nourl : "לא הוגדרה כתובת url", norecords: "אין רשומות לעבד", model : "אורך של colNames <> colModel!" }, formatter : { integer : {thousandsSeparator: " ", defaultValue: '0'}, number : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: '0.00'}, currency : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, prefix: "", suffix:"", defaultValue: '0.00'}, date : { dayNames: [ "א", "ב", "ג", "ד", "ה", "ו", "ש", "ראשון", "שני", "שלישי", "רביעי", "חמישי", "שישי", "שבת" ], monthNames: [ "ינו", "פבר", "מרץ", "אפר", "מאי", "יונ", "יול", "אוג", "ספט", "אוק", "נוב", "דצמ", "ינואר", "פברואר", "מרץ", "אפריל", "מאי", "יוני", "יולי", "אוגוסט", "ספטמבר", "אוקטובר", "נובמבר", "דצמבר" ], AmPm : ["לפני הצהרים","אחר הצהרים","לפני הצהרים","אחר הצהרים"], S: function (j) {return j < 11 || j > 13 ? ['', '', '', ''][Math.min((j - 1) % 10, 3)] : ''}, srcformat: 'Y-m-d', newformat: 'd/m/Y', masks : { ISO8601Long:"Y-m-d H:i:s", ISO8601Short:"Y-m-d", ShortDate: "n/j/Y", LongDate: "l, F d, Y", FullDateTime: "l, F d, Y g:i:s A", MonthDay: "F d", ShortTime: "g:i A", LongTime: "g:i:s A", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "F, Y" }, reformatAfterEdit : false }, baseLinkUrl: '', showAction: '', target: '', checkbox : {disabled:true}, idName : 'id' } }; })(jQuery);
JavaScript
;(function($){ /** * jqGrid Spanish Translation * Traduccion jqGrid en Español por Yamil Bracho * Traduccion corregida y ampliada por Faserline, S.L. * http://www.faserline.com * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html **/ $.jgrid = { defaults : { recordtext: "Mostrando {0} - {1} de {2}", emptyrecords: "Sin registros que mostrar", loadtext: "Cargando...", pgtext : "Página {0} de {1}" }, search : { caption: "Búsqueda...", Find: "Buscar", Reset: "Limpiar", odata : ['igual ', 'no igual a', 'menor que', 'menor o igual que','mayor que','mayor o igual a', 'empiece por','no empiece por','está en','no está en','termina por','no termina por','contiene','no contiene'], groupOps: [ { op: "AND", text: "todo" }, { op: "OR", text: "cualquier" } ], matchText: " match", rulesText: " reglas" }, edit : { addCaption: "Agregar registro", editCaption: "Modificar registro", bSubmit: "Guardar", bCancel: "Cancelar", bClose: "Cerrar", saveData: "Se han modificado los datos, ¿guardar cambios?", bYes : "Si", bNo : "No", bExit : "Cancelar", msg: { required:"Campo obligatorio", number:"Introduzca un número", minValue:"El valor debe ser mayor o igual a ", maxValue:"El valor debe ser menor o igual a ", email: "no es una dirección de correo válida", integer: "Introduzca un valor entero", date: "Introduza una fecha correcta ", url: "no es una URL válida. Prefijo requerido ('http://' or 'https://')", nodefined : " no está definido.", novalue : " valor de retorno es requerido.", customarray : "La función personalizada debe devolver un array.", customfcheck : "La función personalizada debe estar presente en el caso de validación personalizada." } }, view : { caption: "Consultar registro", bClose: "Cerrar" }, del : { caption: "Eliminar", msg: "¿Desea eliminar los registros seleccionados?", bSubmit: "Eliminar", bCancel: "Cancelar" }, nav : { edittext: " ", edittitle: "Modificar fila seleccionada", addtext:" ", addtitle: "Agregar nueva fila", deltext: " ", deltitle: "Eliminar fila seleccionada", searchtext: " ", searchtitle: "Buscar información", refreshtext: "", refreshtitle: "Recargar datos", alertcap: "Aviso", alerttext: "Seleccione una fila", viewtext: "", viewtitle: "Ver fila seleccionada" }, col : { caption: "Mostrar/ocultar columnas", bSubmit: "Enviar", bCancel: "Cancelar" }, errors : { errcap : "Error", nourl : "No se ha especificado una URL", norecords: "No hay datos para procesar", model : "Las columnas de nombres son diferentes de las columnas de modelo" }, formatter : { integer : {thousandsSeparator: ".", defaultValue: '0'}, number : {decimalSeparator:",", thousandsSeparator: ".", decimalPlaces: 2, defaultValue: '0,00'}, currency : {decimalSeparator:",", thousandsSeparator: ".", decimalPlaces: 2, prefix: "", suffix:"", defaultValue: '0,00'}, date : { dayNames: [ "Do", "Lu", "Ma", "Mi", "Ju", "Vi", "Sa", "Domingo", "Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sabado" ], monthNames: [ "Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic", "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre" ], AmPm : ["am","pm","AM","PM"], S: function (j) {return j < 11 || j > 13 ? ['st', 'nd', 'rd', 'th'][Math.min((j - 1) % 10, 3)] : 'th'}, srcformat: 'Y-m-d', newformat: 'd-m-Y', masks : { ISO8601Long:"Y-m-d H:i:s", ISO8601Short:"Y-m-d", ShortDate: "n/j/Y", LongDate: "l, F d, Y", FullDateTime: "l, F d, Y g:i:s A", MonthDay: "F d", ShortTime: "g:i A", LongTime: "g:i:s A", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "F, Y" }, reformatAfterEdit : false }, baseLinkUrl: '', showAction: '', target: '', checkbox : {disabled:true}, idName : 'id' } }; })(jQuery);
JavaScript
;(function($){ /** * jqGrid Polish Translation * Łukasz Schab * http://FreeTree.pl * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html **/ $.jgrid = { defaults : { recordtext: "Pokaż {0} - {1} z {2}", emptyrecords: "Brak rekordów do pokazania", loadtext: "\u0142adowanie...", pgtext : "Strona {0} z {1}" }, search : { caption: "Wyszukiwanie...", Find: "Szukaj", Reset: "Czyść", odata : ['dok\u0142adnie', 'różne od', 'mniejsze od', 'mniejsze lub równe','większe od','większe lub równe', 'zaczyna się od','nie zaczyna się od','zawiera','nie zawiera','kończy się na','nie kończy się na','zawiera','nie zawiera'], groupOps: [ { op: "ORAZ", text: "wszystkie" }, { op: "LUB", text: "każdy" } ], matchText: " pasuje", rulesText: " regu\u0142y" }, edit : { addCaption: "Dodaj rekord", editCaption: "Edytuj rekord", bSubmit: "Zapisz", bCancel: "Anuluj", bClose: "Zamknij", saveData: "Dane zosta\u0142y zmienione! Zapisać zmiany?", bYes : "Tak", bNo : "Nie", bExit : "Anuluj", msg: { required:"Pole jest wymagane", number:"Proszę wpisać poprawną liczbę", minValue:"wartość musi być większa lub równa", maxValue:"wartość musi być mniejsza od", email: "nie jest adresem e-mail", integer: "Proszę wpisać poprawną liczbę", date: "Proszę podaj poprawną datę", url: "jest niew\u0142aściwym adresem URL. Pamiętaj o prefiksie ('http://' lub 'https://')", nodefined : " is not defined!", novalue : " return value is required!", customarray : "Custom function should return array!", customfcheck : "Custom function should be present in case of custom checking!" } }, view : { caption: "Pokaż rekord", bClose: "Zamknij" }, del : { caption: "Usuwanie", msg: "Czy usunąć wybrany rekord(y)?", bSubmit: "Usuń", bCancel: "Anuluj" }, nav : { edittext: " ", edittitle: "Edytuj wybrany wiersz", addtext:" ", addtitle: "Dodaj nowy wiersz", deltext: " ", deltitle: "Usuń wybrany wiersz", searchtext: " ", searchtitle: "Wyszukaj rekord", refreshtext: "", refreshtitle: "Prze\u0142aduj", alertcap: "Uwaga", alerttext: "Proszę wybrać wiersz", viewtext: "", viewtitle: "View selected row" }, col : { caption: "Pokaż/Ukryj kolumny", bSubmit: "Zatwierdź", bCancel: "Anuluj" }, errors : { errcap : "B\u0142ąd", nourl : "Brak adresu url", norecords: "Brak danych", model : "D\u0142ugość colNames <> colModel!" }, formatter : { integer : {thousandsSeparator: " ", defaultValue: '0'}, number : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: '0.00'}, currency : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, prefix: "", suffix:"", defaultValue: '0.00'}, date : { dayNames: [ "Nie", "Pon", "Wt", "Śr", "Cz", "Pi", "So", "Niedziela", "Poniedzia\u0142ek", "Wtorek", "Środa", "Czwartek", "Piątek", "Sobota" ], monthNames: [ "Sty", "Lu", "Mar", "Kwie", "Maj", "Cze", "Lip", "Sie", "Wrz", "Paź", "Lis", "Gru", "Styczeń", "Luty", "Marzec", "Kwiecień", "Maj", "Czerwiec", "Lipiec", "Sierpień", "Wrzesień", "Październik", "Listopad", "Grudzień" ], AmPm : ["am","pm","AM","PM"], S: function (j) {return j < 11 || j > 13 ? ['', '', '', ''][Math.min((j - 1) % 10, 3)] : ''}, srcformat: 'Y-m-d', newformat: 'd/m/Y', masks : { ISO8601Long:"Y-m-d H:i:s", ISO8601Short:"Y-m-d", ShortDate: "n/j/Y", LongDate: "l, F d, Y", FullDateTime: "l, F d, Y g:i:s A", MonthDay: "F d", ShortTime: "g:i A", LongTime: "g:i:s A", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "F, Y" }, reformatAfterEdit : false }, baseLinkUrl: '', showAction: '', target: '', checkbox : {disabled:true}, idName : 'id' } }; })(jQuery);
JavaScript
;(function($){ /** * jqGrid German Translation * Version 1.0.0 (developed for jQuery Grid 3.3.1) * Olaf Klöppel opensource@blue-hit.de * http://blue-hit.de/ * * Updated for jqGrid 3.8 * Andreas Flack * http://www.contentcontrol-berlin.de * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html **/ $.jgrid = { defaults : { recordtext: "Zeige {0} - {1} von {2}", emptyrecords: "Keine Datensätze vorhanden", loadtext: "Lädt...", pgtext : "Seite {0} von {1}" }, search : { caption: "Suche...", Find: "Suchen", Reset: "Zurücksetzen", odata : ['gleich', 'ungleich', 'kleiner', 'kleiner gleich','größer','größer gleich', 'beginnt mit','beginnt nicht mit','ist in','ist nicht in','endet mit','endet nicht mit','enthält','enthält nicht'], groupOps: [ { op: "AND", text: "alle" }, { op: "OR", text: "mindestens eine" } ], matchText: " erfülle", rulesText: " Bedingung(en)" }, edit : { addCaption: "Datensatz hinzufügen", editCaption: "Datensatz bearbeiten", bSubmit: "Speichern", bCancel: "Abbrechen", bClose: "Schließen", saveData: "Daten wurden geändert! Änderungen speichern?", bYes : "ja", bNo : "nein", bExit : "abbrechen", msg: { required:"Feld ist erforderlich", number: "Bitte geben Sie eine Zahl ein", minValue:"Wert muss größer oder gleich sein, als ", maxValue:"Wert muss kleiner oder gleich sein, als ", email: "ist keine gültige E-Mail-Adresse", integer: "Bitte geben Sie eine Ganzzahl ein", date: "Bitte geben Sie ein gültiges Datum ein", url: "ist keine gültige URL. Präfix muss eingegeben werden ('http://' oder 'https://')", nodefined : " ist nicht definiert!", novalue : " Rückgabewert ist erforderlich!", customarray : "Benutzerdefinierte Funktion sollte ein Array zurückgeben!", customfcheck : "Benutzerdefinierte Funktion sollte im Falle der benutzerdefinierten Überprüfung vorhanden sein!" } }, view : { caption: "Datensatz anzeigen", bClose: "Schließen" }, del : { caption: "Löschen", msg: "Ausgewählte Datensätze löschen?", bSubmit: "Löschen", bCancel: "Abbrechen" }, nav : { edittext: " ", edittitle: "Ausgewählte Zeile editieren", addtext:" ", addtitle: "Neue Zeile einfügen", deltext: " ", deltitle: "Ausgewählte Zeile löschen", searchtext: " ", searchtitle: "Datensatz suchen", refreshtext: "", refreshtitle: "Tabelle neu laden", alertcap: "Warnung", alerttext: "Bitte Zeile auswählen", viewtext: "", viewtitle: "Ausgewählte Zeile anzeigen" }, col : { caption: "Spalten auswählen", bSubmit: "Speichern", bCancel: "Abbrechen" }, errors : { errcap : "Fehler", nourl : "Keine URL angegeben", norecords: "Keine Datensätze zu bearbeiten", model : "colNames und colModel sind unterschiedlich lang!" }, formatter : { integer : {thousandsSeparator: ".", defaultValue: '0'}, number : {decimalSeparator:",", thousandsSeparator: ".", decimalPlaces: 2, defaultValue: '0,00'}, currency : {decimalSeparator:",", thousandsSeparator: ".", decimalPlaces: 2, prefix: "", suffix:" €", defaultValue: '0,00'}, date : { dayNames: [ "So", "Mo", "Di", "Mi", "Do", "Fr", "Sa", "Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag" ], monthNames: [ "Jan", "Feb", "Mar", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez", "Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember" ], AmPm : ["am","pm","AM","PM"], S: function (j) {return 'ter'}, srcformat: 'Y-m-d', newformat: 'd.m.Y', masks : { ISO8601Long: "Y-m-d H:i:s", ISO8601Short: "Y-m-d", ShortDate: "j.n.Y", LongDate: "l, j. F Y", FullDateTime: "l, d. F Y G:i:s", MonthDay: "d. F", ShortTime: "G:i", LongTime: "G:i:s", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "F Y" }, reformatAfterEdit : false }, baseLinkUrl: '', showAction: '', target: '', checkbox : {disabled:true}, idName : 'id' } }; })(jQuery);
JavaScript
;(function($){ /** * jqGrid Russian Translation v1.0 02.07.2009 (based on translation by Alexey Kanaev v1.1 21.01.2009, http://softcore.com.ru) * Sergey Dyagovchenko * http://d.sumy.ua * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html **/ $.jgrid = { defaults : { recordtext: "Просмотр {0} - {1} из {2}", emptyrecords: "Нет записей для просмотра", loadtext: "Загрузка...", pgtext : "Стр. {0} из {1}" }, search : { caption: "Поиск...", Find: "Найти", Reset: "Сброс", odata : ['равно', 'не равно', 'меньше', 'меньше или равно','больше','больше или равно', 'начинается с','не начинается с','находится в','не находится в','заканчивается на','не заканчивается на','содержит','не содержит'], groupOps: [ { op: "AND", text: "все" }, { op: "OR", text: "любой" } ], matchText: " совпадает", rulesText: " правила" }, edit : { addCaption: "Добавить запись", editCaption: "Редактировать запись", bSubmit: "Сохранить", bCancel: "Отмена", bClose: "Закрыть", saveData: "Данные были измененны! Сохранить изменения?", bYes : "Да", bNo : "Нет", bExit : "Отмена", msg: { required:"Поле является обязательным", number:"Пожалуйста, введите правильное число", minValue:"значение должно быть больше либо равно", maxValue:"значение должно быть меньше либо равно", email: "некорректное значение e-mail", integer: "Пожалуйста, введите целое число", date: "Пожалуйста, введите правильную дату", url: "неверная ссылка. Необходимо ввести префикс ('http://' or 'https://')", nodefined : " is not defined!", novalue : " return value is required!", customarray : "Custom function should return array!", customfcheck : "Custom function should be present in case of custom checking!" } }, view : { caption: "Просмотр записи", bClose: "Закрыть" }, del : { caption: "Удалить", msg: "Удалить выбранную запись(и)?", bSubmit: "Удалить", bCancel: "Отмена" }, nav : { edittext: " ", edittitle: "Редактировать выбранную запись", addtext:" ", addtitle: "Добавить новую запись", deltext: " ", deltitle: "Удалить выбранную запись", searchtext: " ", searchtitle: "Найти записи", refreshtext: "", refreshtitle: "Обновить таблицу", alertcap: "Внимание", alerttext: "Пожалуйста, выберите запись", viewtext: "", viewtitle: "Просмотреть выбранную запись" }, col : { caption: "Показать/скрыть столбцы", bSubmit: "Сохранить", bCancel: "Отмена" }, errors : { errcap : "Ошибка", nourl : "URL не установлен", norecords: "Нет записей для обработки", model : "Число полей не соответствует числу столбцов таблицы!" }, formatter : { integer : {thousandsSeparator: " ", defaultValue: '0'}, number : {decimalSeparator:",", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: '0,00'}, currency : {decimalSeparator:",", thousandsSeparator: " ", decimalPlaces: 2, prefix: "", suffix:"", defaultValue: '0,00'}, date : { dayNames: [ "Вс", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Воскресение", "Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота" ], monthNames: [ "Янв", "Фев", "Мар", "Апр", "Май", "Июн", "Июл", "Авг", "Сен", "Окт", "Ноя", "Дек", "Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь" ], AmPm : ["am","pm","AM","PM"], S: function (j) {return j < 11 || j > 13 ? ['st', 'nd', 'rd', 'th'][Math.min((j - 1) % 10, 3)] : 'th'}, srcformat: 'Y-m-d', newformat: 'd.m.Y', masks : { ISO8601Long:"Y-m-d H:i:s", ISO8601Short:"Y-m-d", ShortDate: "n.j.Y", LongDate: "l, F d, Y", FullDateTime: "l, F d, Y G:i:s", MonthDay: "F d", ShortTime: "G:i", LongTime: "G:i:s", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "F, Y" }, reformatAfterEdit : false }, baseLinkUrl: '', showAction: '', target: '', checkbox : {disabled:true}, idName : 'id' } }; })(jQuery);
JavaScript
;(function($){ /** * jqGrid Swedish Translation * Harald Normann harald.normann@wts.se, harald.normann@gmail.com * http://www.worldteamsoftware.com * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html **/ $.jgrid = { defaults : { recordtext: "Visar {0} - {1} av {2}", emptyrecords: "Det finns inga poster att visa", loadtext: "Laddar...", pgtext : "Sida {0} av {1}" }, search : { caption: "Sök Poster - Ange sökvillkor", Find: "Sök", Reset: "Nollställ Villkor", odata : ['lika', 'ej lika', 'mindre', 'mindre eller lika','större','större eller lika', 'börjar med','börjar inte med','tillhör','tillhör inte','slutar med','slutar inte med','innehåller','innehåller inte'], groupOps: [ { op: "AND", text: "alla" }, { op: "OR", text: "eller" } ], matchText: " träff", rulesText: " regler" }, edit : { addCaption: "Ny Post", editCaption: "Redigera Post", bSubmit: "Spara", bCancel: "Avbryt", bClose: "Stäng", saveData: "Data har ändrats! Spara förändringar?", bYes : "Ja", bNo : "Nej", bExit : "Avbryt", msg: { required:"Fältet är obligatoriskt", number:"Välj korrekt nummer", minValue:"värdet måste vara större än eller lika med", maxValue:"värdet måste vara mindre än eller lika med", email: "är inte korrekt e-post adress", integer: "Var god ange korrekt heltal", date: "Var god ange korrekt datum", url: "är inte en korrekt URL. Prefix måste anges ('http://' or 'https://')", nodefined : " är inte definierad!", novalue : " returvärde måste anges!", customarray : "Custom funktion måste returnera en vektor!", customfcheck : "Custom funktion måste finnas om Custom kontroll sker!" } }, view : { caption: "Visa Post", bClose: "Stäng" }, del : { caption: "Radera", msg: "Radera markerad(e) post(er)?", bSubmit: "Radera", bCancel: "Avbryt" }, nav : { edittext: "", edittitle: "Redigera markerad rad", addtext:"", addtitle: "Skapa ny post", deltext: "", deltitle: "Radera markerad rad", searchtext: "", searchtitle: "Sök poster", refreshtext: "", refreshtitle: "Uppdatera data", alertcap: "Varning", alerttext: "Ingen rad är markerad", viewtext: "", viewtitle: "Visa markerad rad" }, col : { caption: "Välj Kolumner", bSubmit: "OK", bCancel: "Avbryt" }, errors : { errcap : "Fel", nourl : "URL saknas", norecords: "Det finns inga poster att bearbeta", model : "Antal colNames <> colModel!" }, formatter : { integer : {thousandsSeparator: " ", defaultValue: '0'}, number : {decimalSeparator:",", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: '0,00'}, currency : {decimalSeparator:",", thousandsSeparator: " ", decimalPlaces: 2, prefix: "", suffix:"Kr", defaultValue: '0,00'}, date : { dayNames: [ "Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör", "Söndag", "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag" ], monthNames: [ "Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec", "Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December" ], AmPm : ["fm","em","FM","EM"], S: function (j) {return j < 11 || j > 13 ? ['st', 'nd', 'rd', 'th'][Math.min((j - 1) % 10, 3)] : 'th'}, srcformat: 'Y-m-d', newformat: 'Y-m-d', masks : { ISO8601Long:"Y-m-d H:i:s", ISO8601Short:"Y-m-d", ShortDate: "n/j/Y", LongDate: "l, F d, Y", FullDateTime: "l, F d, Y g:i:s A", MonthDay: "F d", ShortTime: "g:i A", LongTime: "g:i:s A", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "F, Y" }, reformatAfterEdit : false }, baseLinkUrl: '', showAction: '', target: '', checkbox : {disabled:true}, idName : 'id' } }; })(jQuery);
JavaScript
(function(a) { a.jgrid = { defaults: { recordtext: "regels {0} - {1} van {2}", emptyrecords: "Geen data gevonden.", loadtext: "laden...", pgtext: "pagina {0} van {1}" }, search: { caption: "Zoeken...", Find: "Zoek", Reset: "Herstellen", odata: ["gelijk aan", "niet gelijk aan", "kleiner dan", "kleiner dan of gelijk aan", "groter dan", "groter dan of gelijk aan", "begint met", "begint niet met", "is in", "is niet in", "eindigd met", "eindigd niet met", "bevat", "bevat niet"], groupOps: [{ op: "AND", text: "alle" }, { op: "OR", text: "een van de"}], matchText: " match", rulesText: " regels" }, edit: { addCaption: "Nieuw", editCaption: "Bewerken", bSubmit: "Opslaan", bCancel: "Annuleren", bClose: "Sluiten", saveData: "Er is data aangepast! Wijzigingen opslaan?", bYes: "Ja", bNo: "Nee", bExit: "Sluiten", msg: { required: "Veld is verplicht", number: "Voer a.u.b. geldig nummer in", minValue: "Waarde moet groter of gelijk zijn aan ", maxValue: "Waarde moet kleiner of gelijks zijn aan", email: "is geen geldig e-mailadres", integer: "Voer a.u.b. een geldig getal in", date: "Voer a.u.b. een geldige waarde in", url: "is geen geldige URL. Prefix is verplicht ('http://' or 'https://')", nodefined : " is not defined!", novalue : " return value is required!", customarray : "Custom function should return array!", customfcheck : "Custom function should be present in case of custom checking!" } }, view: { caption: "Tonen", bClose: "Sluiten" }, del: { caption: "Verwijderen", msg: "Verwijder geselecteerde regel(s)?", bSubmit: "Verwijderen", bCancel: "Annuleren" }, nav: { edittext: "", edittitle: "Bewerken", addtext: "", addtitle: "Nieuw", deltext: "", deltitle: "Verwijderen", searchtext: "", searchtitle: "Zoeken", refreshtext: "", refreshtitle: "Vernieuwen", alertcap: "Waarschuwing", alerttext: "Selecteer a.u.b. een regel", viewtext: "", viewtitle: "Openen" }, col: { caption: "Tonen/verbergen kolommen", bSubmit: "OK", bCancel: "Annuleren" }, errors: { errcap: "Fout", nourl: "Er is geen URL gedefinieerd", norecords: "Geen data om te verwerken", model: "Lengte van 'colNames' is niet gelijk aan 'colModel'!" }, formatter: { integer: { thousandsSeparator: ".", defaultValue: "0" }, number: { decimalSeparator: ",", thousandsSeparator: ".", decimalPlaces: 2, defaultValue: "0.00" }, currency: { decimalSeparator: ",", thousandsSeparator: ".", decimalPlaces: 2, prefix: "EUR ", suffix: "", defaultValue: "0.00" }, date: { dayNames: ["Zo", "Ma", "Di", "Wo", "Do", "Vr", "Za", "Zondag", "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrijdag", "Zaterdag"], monthNames: ["Jan", "Feb", "Maa", "Apr", "Mei", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "Januari", "Februari", "Maart", "April", "Mei", "Juni", "Juli", "Augustus", "September", "October", "November", "December"], AmPm: ["am", "pm", "AM", "PM"], S: function(b) { return b < 11 || b > 13 ? ["st", "nd", "rd", "th"][Math.min((b - 1) % 10, 3)] : "th" }, srcformat: "Y-m-d", newformat: "d/m/Y", masks: { ISO8601Long: "Y-m-d H:i:s", ISO8601Short: "Y-m-d", ShortDate: "n/j/Y", LongDate: "l, F d, Y", FullDateTime: "l d F Y G:i:s", MonthDay: "d F", ShortTime: "G:i", LongTime: "G:i:s", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "F, Y" }, reformatAfterEdit: false }, baseLinkUrl: "", showAction: "", target: "", checkbox: { disabled: true }, idName: "id" } } })(jQuery);
JavaScript
;(function($){ /** * jqGrid Danish Translation * Kaare Rasmussen kjs@jasonic.dk * http://jasonic.dk/blog * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html **/ $.jgrid = { defaults : { recordtext: "View {0} - {1} of {2}", emptyrecords: "No records to view", loadtext: "Loading...", pgtext : "Page {0} of {1}" }, search : { caption: "Søg...", Find: "Find", Reset: "Nulstil", odata : ['equal', 'not equal', 'less', 'less or equal','greater','greater or equal', 'begins with','does not begin with','is in','is not in','ends with','does not end with','contains','does not contain'], groupOps: [ { op: "AND", text: "all" }, { op: "OR", text: "any" } ], matchText: " match", rulesText: " rules" }, edit : { addCaption: "Tilføj", editCaption: "Ret", bSubmit: "Send", bCancel: "Annuller", bClose: "Luk", saveData: "Data has been changed! Save changes?", bYes : "Yes", bNo : "No", bExit : "Cancel", msg: { required:"Felt er nødvendigt", number:"Indtast venligst et validt tal", minValue:"værdi skal være større end eller lig med", maxValue:"værdi skal være mindre end eller lig med", email: "er ikke en valid email", integer: "Indtast venligst et validt heltalt", date: "Indtast venligst en valid datoværdi", url: "is not a valid URL. Prefix required ('http://' or 'https://')", nodefined : " is not defined!", novalue : " return value is required!", customarray : "Custom function should return array!", customfcheck : "Custom function should be present in case of custom checking!" } }, view : { caption: "View Record", bClose: "Close" }, del : { caption: "Slet", msg: "Slet valgte række(r)?", bSubmit: "Slet", bCancel: "Annuller" }, nav : { edittext: " ", edittitle: "Rediger valgte række", addtext:" ", addtitle: "Tilføj ny række", deltext: " ", deltitle: "Slet valgte række", searchtext: " ", searchtitle: "Find poster", refreshtext: "", refreshtitle: "Indlæs igen", alertcap: "Advarsel", alerttext: "Vælg venligst række", viewtext: "", viewtitle: "View selected row" }, col : { caption: "Vis/skjul kolonner", bSubmit: "Send", bCancel: "Annuller" }, errors : { errcap : "Fejl", nourl : "Ingel url valgt", norecords: "Ingen poster at behandle", model : "colNames og colModel har ikke samme længde!" }, formatter : { integer : {thousandsSeparator: " ", defaultValue: '0'}, number : {decimalSeparator:",", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: '0,00'}, currency : {decimalSeparator:",", thousandsSeparator: " ", decimalPlaces: 2, prefix: "", suffix:"", defaultValue: '0,00'}, date : { dayNames: [ "Søn", "Man", "Tirs", "Ons", "Tors", "Fre", "Lør", "Søndag", "Mandag", "Tirsdag", "Onsdag", "Torsdag", "Fredag", "Lørdag" ], monthNames: [ "Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec", "Januar", "Februar", "Marts", "April", "Maj", "Juni", "Juli", "August", "September", "Oktober", "November", "December" ], AmPm : ["","","",""], S: function (j) {return '.'}, srcformat: 'Y-m-d', newformat: 'd/m/Y', masks : { ISO8601Long:"Y-m-d H:i:s", ISO8601Short:"Y-m-d", ShortDate: "j/n/Y", LongDate: "l d. F Y", FullDateTime: "l d F Y G:i:s", MonthDay: "d. F", ShortTime: "G:i", LongTime: "G:i:s", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "F Y" }, reformatAfterEdit : false }, baseLinkUrl: '', showAction: '', target: '', checkbox : {disabled:true}, idName : 'id' } }; // DK })(jQuery);
JavaScript
;(function ($) { /** * jqGrid Persian Translation * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html **/ $.jgrid = { defaults: { recordtext: "نمابش {0} - {1} از {2}", emptyrecords: "رکوردی یافت نشد", loadtext: "بارگزاري...", pgtext: "صفحه {0} از {1}" }, search: { caption: "جستجو...", Find: "يافته ها", Reset: "از نو", odata: ['برابر', 'نا برابر', 'به', 'کوچکتر', 'از', 'بزرگتر', 'شروع با', 'شروع نشود با', 'نباشد', 'عضو این نباشد', 'اتمام با', 'تمام نشود با', 'حاوی', 'نباشد حاوی'], groupOps: [{ op: "AND", text: "کل" }, { op: "OR", text: "مجموع" }], matchText: " حاوی", rulesText: " اطلاعات" }, edit: { addCaption: "اضافه کردن رکورد", editCaption: "ويرايش رکورد", bSubmit: "ثبت", bCancel: "انصراف", bClose: "بستن", saveData: "دیتا تعییر کرد! ذخیره شود؟", bYes: "بله", bNo: "خیر", bExit: "انصراف", msg: { required: "فيلدها بايد ختما پر شوند", number: "لطفا عدد وعتبر وارد کنيد", minValue: "مقدار وارد شده بايد بزرگتر يا مساوي با", maxValue: "مقدار وارد شده بايد کوچکتر يا مساوي", email: "پست الکترونيک وارد شده معتبر نيست", integer: "لطفا يک عدد صحيح وارد کنيد", date: "لطفا يک تاريخ معتبر وارد کنيد", url: "این آدرس صحیح نمی باشد. پیشوند نیاز است ('http://' یا 'https://')", nodefined: " تعریف نشده!", novalue: " مقدار برگشتی اجباری است!", customarray: "تابع شما باید مقدار آرایه داشته باشد!", customfcheck: "برای داشتن متد دلخواه شما باید سطون با چکینگ دلخواه داشته باشید!" } }, view: { caption: "نمایش رکورد", bClose: "بستن" }, del: { caption: "حذف", msg: "از حذف گزينه هاي انتخاب شده مطمئن هستيد؟", bSubmit: "حذف", bCancel: "ابطال" }, nav: { edittext: " ", edittitle: "ويرايش رديف هاي انتخاب شده", addtext: " ", addtitle: "افزودن رديف جديد", deltext: " ", deltitle: "حذف ردبف هاي انتخاب شده", searchtext: " ", searchtitle: "جستجوي رديف", refreshtext: "", refreshtitle: "بازيابي مجدد صفحه", alertcap: "اخطار", alerttext: "لطفا يک رديف انتخاب کنيد", viewtext: "", viewtitle: "نمایش رکورد های انتخاب شده" }, col: { caption: "نمايش/عدم نمايش ستون", bSubmit: "ثبت", bCancel: "انصراف" }, errors: { errcap: "خطا", nourl: "هيچ آدرسي تنظيم نشده است", norecords: "هيچ رکوردي براي پردازش موجود نيست", model: "طول نام ستون ها محالف ستون هاي مدل مي باشد!" }, formatter: { integer: { thousandsSeparator: " ", defaultValue: "0" }, number: { decimalSeparator: ".", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: "0.00" }, currency: { decimalSeparator: ".", thousandsSeparator: " ", decimalPlaces: 2, prefix: "", suffix: "", defaultValue: "0" }, date: { dayNames: ["يک", "دو", "سه", "چهار", "پنج", "جمع", "شنب", "يکشنبه", "دوشنبه", "سه شنبه", "چهارشنبه", "پنجشنبه", "جمعه", "شنبه"], monthNames: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "ژانويه", "فوريه", "مارس", "آوريل", "مه", "ژوئن", "ژوئيه", "اوت", "سپتامبر", "اکتبر", "نوامبر", "December"], AmPm: ["ب.ظ", "ب.ظ", "ق.ظ", "ق.ظ"], S: function (b) { return b < 11 || b > 13 ? ["st", "nd", "rd", "th"][Math.min((b - 1) % 10, 3)] : "th" }, srcformat: "Y-m-d", newformat: "d/m/Y", masks: { ISO8601Long: "Y-m-d H:i:s", ISO8601Short: "Y-m-d", ShortDate: "n/j/Y", LongDate: "l, F d, Y", FullDateTime: "l, F d, Y g:i:s A", MonthDay: "F d", ShortTime: "g:i A", LongTime: "g:i:s A", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "F, Y" }, reformatAfterEdit: false }, baseLinkUrl: "", showAction: "نمايش", target: "", checkbox: { disabled: true }, idName: "id" } } })(jQuery);
JavaScript
;(function($){ /** * jqGrid Brazilian-Portuguese Translation * Sergio Righi sergio.righi@gmail.com * http://curve.com.br * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html **/ $.jgrid = { defaults : { recordtext: "Ver {0} - {1} of {2}", emptyrecords: "Nenhum registro para visualizar", loadtext: "Carregando...", pgtext : "Página {0} de {1}" }, search : { caption: "Procurar...", Find: "Procurar", Reset: "Resetar", odata : ['equal', 'not equal', 'less', 'less or equal','greater','greater or equal', 'begins with','does not begin with','is in','is not in','ends with','does not end with','contains','does not contain'], groupOps: [ { op: "AND", text: "all" }, { op: "OR", text: "any" } ], matchText: " iguala", rulesText: " regras" }, edit : { addCaption: "Incluir", editCaption: "Alterar", bSubmit: "Enviar", bCancel: "Cancelar", bClose: "Fechar", saveData: "Os dados foram alterados! Salvar alterações?", bYes : "Sim", bNo : "Não", bExit : "Cancelar", msg: { required:"Campo obrigatório", number:"Por favor, informe um número válido", minValue:"valor deve ser igual ou maior que ", maxValue:"valor deve ser menor ou igual a", email: "este e-mail não é válido", integer: "Por favor, informe um valor inteiro", date: "Por favor, informe uma data válida", url: "não é uma URL válida. Prefixo obrigatório ('http://' or 'https://')", nodefined : " não está definido!", novalue : " um valor de retorno é obrigatório!", customarray : "Função customizada deve retornar um array!", customfcheck : "Função customizada deve estar presente em caso de validação customizada!" } }, view : { caption: "Ver Registro", bClose: "Fechar" }, del : { caption: "Apagar", msg: "Apagar registros selecionado(s)?", bSubmit: "Apagar", bCancel: "Cancelar" }, nav : { edittext: " ", edittitle: "Alterar registro selecionado", addtext:" ", addtitle: "Incluir novo registro", deltext: " ", deltitle: "Apagar registro selecionado", searchtext: " ", searchtitle: "Procurar registros", refreshtext: "", refreshtitle: "Recarrgando Tabela", alertcap: "Aviso", alerttext: "Por favor, selecione um registro", viewtext: "", viewtitle: "Ver linha selecionada" }, col : { caption: "Mostrar/Esconder Colunas", bSubmit: "Enviar", bCancel: "Cancelar" }, errors : { errcap : "Erro", nourl : "Nenhuma URL defenida", norecords: "Sem registros para exibir", model : "Comprimento de colNames <> colModel!" }, formatter : { integer : {thousandsSeparator: " ", defaultValue: '0'}, number : {decimalSeparator:",", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: '0,00'}, currency : {decimalSeparator:",", thousandsSeparator: ".", decimalPlaces: 2, prefix: "R$ ", suffix:"", defaultValue: '0,00'}, date : { dayNames: [ "Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb", "Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado" ], monthNames: [ "Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez", "Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro" ], AmPm : ["am","pm","AM","PM"], S: function (j) {return j < 11 || j > 13 ? ['º', 'º', 'º', 'º'][Math.min((j - 1) % 10, 3)] : 'º'}, srcformat: 'Y-m-d', newformat: 'd/m/Y', masks : { ISO8601Long:"Y-m-d H:i:s", ISO8601Short:"Y-m-d", ShortDate: "n/j/Y", LongDate: "l, F d, Y", FullDateTime: "l, F d, Y g:i:s A", MonthDay: "F d", ShortTime: "g:i A", LongTime: "g:i:s A", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "F, Y" }, reformatAfterEdit : false }, baseLinkUrl: '', showAction: '', target: '', checkbox : {disabled:true}, idName : 'id' } }; })(jQuery);
JavaScript
;(function($){ /** * jqGrid Turkish Translation * Erhan Gündoğan (erhan@trposta.net) * http://blog.zakkum.com * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html **/ $.jgrid = { defaults : { recordtext: "{0}-{1} listeleniyor. Toplam:{2}", emptyrecords: "Kayıt bulunamadı", loadtext: "Yükleniyor...", pgtext : "{0}/{1}. Sayfa" }, search : { caption: "Arama...", Find: "Bul", Reset: "Temizle", odata : ['eşit', 'eşit değil', 'daha az', 'daha az veya eşit', 'daha fazla', 'daha fazla veya eşit', 'ile başlayan', 'ile başlamayan', 'içinde', 'içinde değil', 'ile biten', 'ile bitmeyen', 'içeren', 'içermeyen'], groupOps: [ { op: "VE", text: "tüm" }, { op: "VEYA", text: "herhangi" } ], matchText: " uyan", rulesText: " kurallar" }, edit : { addCaption: "Kayıt Ekle", editCaption: "Kayıt Düzenle", bSubmit: "Gönder", bCancel: "İptal", bClose: "Kapat", saveData: "Veriler değişti! Kayıt edilsin mi?", bYes : "Evet", bNo : "Hayıt", bExit : "İptal", msg: { required:"Alan gerekli", number:"Lütfen bir numara giriniz", minValue:"girilen değer daha büyük ya da buna eşit olmalıdır", maxValue:"girilen değer daha küçük ya da buna eşit olmalıdır", email: "geçerli bir e-posta adresi değildir", integer: "Lütfen bir tamsayı giriniz", url: "Geçerli bir URL değil. ('http://' or 'https://') ön eki gerekli.", nodefined : " is not defined!", novalue : " return value is required!", customarray : "Custom function should return array!", customfcheck : "Custom function should be present in case of custom checking!" } }, view : { caption: "Kayıt Görüntüle", bClose: "Kapat" }, del : { caption: "Sil", msg: "Seçilen kayıtlar silinsin mi?", bSubmit: "Sil", bCancel: "İptal" }, nav : { edittext: " ", edittitle: "Seçili satırı düzenle", addtext:" ", addtitle: "Yeni satır ekle", deltext: " ", deltitle: "Seçili satırı sil", searchtext: " ", searchtitle: "Kayıtları bul", refreshtext: "", refreshtitle: "Tabloyu yenile", alertcap: "Uyarı", alerttext: "Lütfen bir satır seçiniz", viewtext: "", viewtitle: "Seçilen satırı görüntüle" }, col : { caption: "Sütunları göster/gizle", bSubmit: "Gönder", bCancel: "İptal" }, errors : { errcap : "Hata", nourl : "Bir url yapılandırılmamış", norecords: "İşlem yapılacak bir kayıt yok", model : "colNames uzunluğu <> colModel!" }, formatter : { integer : {thousandsSeparator: " ", defaultValue: '0'}, number : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: '0.00'}, currency : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, prefix: "", suffix:"", defaultValue: '0.00'}, date : { dayNames: [ "Paz", "Pts", "Sal", "Çar", "Per", "Cum", "Cts", "Pazar", "Pazartesi", "Salı", "Çarşamba", "Perşembe", "Cuma", "Cumartesi" ], monthNames: [ "Oca", "Şub", "Mar", "Nis", "May", "Haz", "Tem", "Ağu", "Eyl", "Eki", "Kas", "Ara", "Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık" ], AmPm : ["am","pm","AM","PM"], S: function (j) {return j < 11 || j > 13 ? ['st', 'nd', 'rd', 'th'][Math.min((j - 1) % 10, 3)] : 'th'}, srcformat: 'Y-m-d', newformat: 'd/m/Y', masks : { ISO8601Long:"Y-m-d H:i:s", ISO8601Short:"Y-m-d", ShortDate: "n/j/Y", LongDate: "l, F d, Y", FullDateTime: "l, F d, Y g:i:s A", MonthDay: "F d", ShortTime: "g:i A", LongTime: "g:i:s A", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "F, Y" }, reformatAfterEdit : false }, baseLinkUrl: '', showAction: '', target: '', checkbox : {disabled:true}, idName : 'id' } }; })(jQuery);
JavaScript
;(function($){ /** * jqGrid Danish Translation * Aesiras A/S * http://www.aesiras.dk * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html **/ $.jgrid = { defaults : { recordtext: "Vis {0} - {1} of {2}", emptyrecords: "Ingen linjer fundet", loadtext: "Henter...", pgtext : "Side {0} af {1}" }, search : { caption: "Søg...", Find: "Find", Reset: "Nulstil", odata : ['lig', 'forskellige fra', 'mindre', 'mindre eller lig','større','større eller lig', 'begynder med','begynder ikke med','findes i','findes ikke i','ender med','ender ikke med','indeholder','indeholder ikke'], groupOps: [ { op: "AND", text: "all" }, { op: "OR", text: "any" } ], matchText: " lig", rulesText: " regler" }, edit : { addCaption: "Tilføj", editCaption: "Ret", bSubmit: "Send", bCancel: "Annuller", bClose: "Luk", saveData: "Data er ændret. Gem data?", bYes : "Ja", bNo : "Nej", bExit : "Fortryd", msg: { required:"Felt er nødvendigt", number:"Indtast venligst et validt tal", minValue:"værdi skal være større end eller lig med", maxValue:"værdi skal være mindre end eller lig med", email: "er ikke en gyldig email", integer: "Indtast venligst et gyldigt heltal", date: "Indtast venligst en gyldig datoværdi", url: "er ugyldig URL. Prefix mangler ('http://' or 'https://')", nodefined : " er ikke defineret!", novalue : " returværdi kræves!", customarray : "Custom function should return array!", customfcheck : "Custom function should be present in case of custom checking!" } }, view : { caption: "Vis linje", bClose: "Luk" }, del : { caption: "Slet", msg: "Slet valgte linje(r)?", bSubmit: "Slet", bCancel: "Fortryd" }, nav : { edittext: " ", edittitle: "Rediger valgte linje", addtext:" ", addtitle: "Tilføj ny linje", deltext: " ", deltitle: "Slet valgte linje", searchtext: " ", searchtitle: "Find linjer", refreshtext: "", refreshtitle: "Indlæs igen", alertcap: "Advarsel", alerttext: "Vælg venligst linje", viewtext: "", viewtitle: "Vis valgte linje" }, col : { caption: "Vis/skjul kolonner", bSubmit: "Opdatere", bCancel: "Fortryd" }, errors : { errcap : "Fejl", nourl : "Ingen url valgt", norecords: "Ingen linjer at behandle", model : "colNames og colModel har ikke samme længde!" }, formatter : { integer : {thousandsSeparator: " ", defaultValue: '0'}, number : {decimalSeparator:",", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: '0,00'}, currency : {decimalSeparator:",", thousandsSeparator: " ", decimalPlaces: 2, prefix: "", suffix:"", defaultValue: '0,00'}, date : { dayNames: [ "Søn", "Man", "Tir", "Ons", "Tor", "Fre", "Lør", "Søndag", "Mandag", "Tirsdag", "Onsdag", "Torsdag", "Fredag", "Lørdag" ], monthNames: [ "Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec", "Januar", "Februar", "Marts", "April", "Maj", "Juni", "Juli", "August", "September", "Oktober", "November", "December" ], AmPm : ["","","",""], S: function (j) {return '.'}, srcformat: 'Y-m-d', newformat: 'd/m/Y', masks : { ISO8601Long:"Y-m-d H:i:s", ISO8601Short:"Y-m-d", ShortDate: "j/n/Y", LongDate: "l d. F Y", FullDateTime: "l d F Y G:i:s", MonthDay: "d. F", ShortTime: "G:i", LongTime: "G:i:s", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "F Y" }, reformatAfterEdit : false }, baseLinkUrl: '', showAction: '', target: '', checkbox : {disabled:true}, idName : 'id' } }; // DA })(jQuery);
JavaScript
;(function($){ /** * jqGrid Romanian Translation * Alexandru Emil Lupu contact@alecslupu.ro * http://www.alecslupu.ro/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html **/ $.jgrid = { defaults : { recordtext: "Vizualizare {0} - {1} din {2}", emptyrecords: "Nu există înregistrări de vizualizat", loadtext: "Încărcare...", pgtext : "Pagina {0} din {1}" }, search : { caption: "Caută...", Find: "Caută", Reset: "Resetare", odata : ['egal', 'diferit', 'mai mic', 'mai mic sau egal','mai mare','mai mare sau egal', 'începe cu','nu începe cu','se găsește în','nu se găsește în','se termină cu','nu se termină cu','conține',''], groupOps: [ { op: "AND", text: "toate" }, { op: "OR", text: "oricare" } ], matchText: " găsite", rulesText: " reguli" }, edit : { addCaption: "Adăugare înregistrare", editCaption: "Modificare înregistrare", bSubmit: "Salvează", bCancel: "Anulare", bClose: "Închide", saveData: "Informațiile au fost modificate! Salvați modificările?", bYes : "Da", bNo : "Nu", bExit : "Anulare", msg: { required:"Câmpul este obligatoriu", number:"Vă rugăm introduceți un număr valid", minValue:"valoarea trebuie sa fie mai mare sau egală cu", maxValue:"valoarea trebuie sa fie mai mică sau egală cu", email: "nu este o adresă de e-mail validă", integer: "Vă rugăm introduceți un număr valid", date: "Vă rugăm să introduceți o dată validă", url: "Nu este un URL valid. Prefixul este necesar('http://' or 'https://')", nodefined : " is not defined!", novalue : " return value is required!", customarray : "Custom function should return array!", customfcheck : "Custom function should be present in case of custom checking!" } }, view : { caption: "Vizualizare înregistrare", bClose: "Închidere" }, del : { caption: "Ștegere", msg: "Ștergeți înregistrarea (înregistrările) selectate?", bSubmit: "Șterge", bCancel: "Anulare" }, nav : { edittext: "", edittitle: "Modifică rândul selectat", addtext:"", addtitle: "Adaugă rând nou", deltext: "", deltitle: "Șterge rândul selectat", searchtext: "", searchtitle: "Căutare înregistrări", refreshtext: "", refreshtitle: "Reîncarcare Grid", alertcap: "Avertisment", alerttext: "Vă rugăm să selectați un rând", viewtext: "", viewtitle: "Vizualizează rândul selectat" }, col : { caption: "Arată/Ascunde coloanele", bSubmit: "Salvează", bCancel: "Anulare" }, errors : { errcap : "Eroare", nourl : "Niciun url nu este setat", norecords: "Nu sunt înregistrări de procesat", model : "Lungimea colNames <> colModel!" }, formatter : { integer : {thousandsSeparator: " ", defaultValue: '0'}, number : {decimalSeparator:",", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: '0,00'}, currency : {decimalSeparator:",", thousandsSeparator: " ", decimalPlaces: 2, prefix: "", suffix:"", defaultValue: '0,00'}, date : { dayNames: [ "Dum", "Lun", "Mar", "Mie", "Joi", "Vin", "Sâm", "Duminică", "Luni", "Marți", "Miercuri", "Joi", "Vineri", "Sâmbătă" ], monthNames: [ "Ian", "Feb", "Mar", "Apr", "Mai", "Iun", "Iul", "Aug", "Sep", "Oct", "Noi", "Dec", "Ianuarie", "Februarie", "Martie", "Aprilie", "Mai", "Iunie", "Iulie", "August", "Septembrie", "Octombrie", "Noiembrie", "Decembrie" ], AmPm : ["am","pm","AM","PM"], /* Here is a problem in romanian: M / F 1st = primul / prima 2nd = Al doilea / A doua 3rd = Al treilea / A treia 4th = Al patrulea/ A patra 5th = Al cincilea / A cincea 6th = Al șaselea / A șasea 7th = Al șaptelea / A șaptea .... */ S: function (j) {return j < 11 || j > 13 ? ['st', 'nd', 'rd', 'th'][Math.min((j - 1) % 10, 3)] : 'th'}, srcformat: 'Y-m-d', newformat: 'd/m/Y', masks : { ISO8601Long:"Y-m-d H:i:s", ISO8601Short:"Y-m-d", ShortDate: "n/j/Y", LongDate: "l, F d, Y", FullDateTime: "l, F d, Y g:i:s A", MonthDay: "F d", ShortTime: "g:i A", LongTime: "g:i:s A", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "F, Y" }, reformatAfterEdit : false }, baseLinkUrl: '', showAction: '', target: '', checkbox : {disabled:true}, idName : 'id' } }; })(jQuery);
JavaScript
;(function($){ /** * jqGrid Greek (el) Translation * Alex Cicovic * http://www.alexcicovic.com * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html **/ $.jgrid = { defaults : { recordtext: "View {0} - {1} of {2}", emptyrecords: "No records to view", loadtext: "Φόρτωση...", pgtext : "Page {0} of {1}" }, search : { caption: "Αναζήτηση...", Find: "Εύρεση", Reset: "Επαναφορά", odata : ['equal', 'not equal', 'less', 'less or equal','greater','greater or equal', 'begins with','does not begin with','is in','is not in','ends with','does not end with','contains','does not contain'], groupOps: [ { op: "AND", text: "all" }, { op: "OR", text: "any" } ], matchText: " match", rulesText: " rules" }, edit : { addCaption: "Εισαγωγή Εγγραφής", editCaption: "Επεξεργασία Εγγραφής", bSubmit: "Καταχώρηση", bCancel: "Άκυρο", bClose: "Κλείσιμο", saveData: "Data has been changed! Save changes?", bYes : "Yes", bNo : "No", bExit : "Cancel", msg: { required:"Το πεδίο είναι απαραίτητο", number:"Το πεδίο δέχεται μόνο αριθμούς", minValue:"Η τιμή πρέπει να είναι μεγαλύτερη ή ίση του ", maxValue:"Η τιμή πρέπει να είναι μικρότερη ή ίση του ", email: "Η διεύθυνση e-mail δεν είναι έγκυρη", integer: "Το πεδίο δέχεται μόνο ακέραιους αριθμούς", url: "is not a valid URL. Prefix required ('http://' or 'https://')", nodefined : " is not defined!", novalue : " return value is required!", customarray : "Custom function should return array!", customfcheck : "Custom function should be present in case of custom checking!" } }, view : { caption: "View Record", bClose: "Close" }, del : { caption: "Διαγραφή", msg: "Διαγραφή των επιλεγμένων εγγραφών;", bSubmit: "Ναι", bCancel: "Άκυρο" }, nav : { edittext: " ", edittitle: "Επεξεργασία επιλεγμένης εγγραφής", addtext:" ", addtitle: "Εισαγωγή νέας εγγραφής", deltext: " ", deltitle: "Διαγραφή επιλεγμένης εγγραφής", searchtext: " ", searchtitle: "Εύρεση Εγγραφών", refreshtext: "", refreshtitle: "Ανανέωση Πίνακα", alertcap: "Προσοχή", alerttext: "Δεν έχετε επιλέξει εγγραφή", viewtext: "", viewtitle: "View selected row" }, col : { caption: "Εμφάνιση / Απόκρυψη Στηλών", bSubmit: "ΟΚ", bCancel: "Άκυρο" }, errors : { errcap : "Σφάλμα", nourl : "Δεν έχει δοθεί διεύθυνση χειρισμού για τη συγκεκριμένη ενέργεια", norecords: "Δεν υπάρχουν εγγραφές προς επεξεργασία", model : "Άνισος αριθμός πεδίων colNames/colModel!" }, formatter : { integer : {thousandsSeparator: " ", defaultValue: '0'}, number : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: '0.00'}, currency : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, prefix: "", suffix:"", defaultValue: '0.00'}, date : { dayNames: [ "Κυρ", "Δευ", "Τρι", "Τετ", "Πεμ", "Παρ", "Σαβ", "Κυριακή", "Δευτέρα", "Τρίτη", "Τετάρτη", "Πέμπτη", "Παρασκευή", "Σάββατο" ], monthNames: [ "Ιαν", "Φεβ", "Μαρ", "Απρ", "Μαι", "Ιουν", "Ιουλ", "Αυγ", "Σεπ", "Οκτ", "Νοε", "Δεκ", "Ιανουάριος", "Φεβρουάριος", "Μάρτιος", "Απρίλιος", "Μάιος", "Ιούνιος", "Ιούλιος", "Αύγουστος", "Σεπτέμβριος", "Οκτώβριος", "Νοέμβριος", "Δεκέμβριος" ], AmPm : ["πμ","μμ","ΠΜ","ΜΜ"], S: function (j) {return j == 1 || j > 1 ? ['η'][Math.min((j - 1) % 10, 3)] : ''}, srcformat: 'Y-m-d', newformat: 'd/m/Y', masks : { ISO8601Long:"Y-m-d H:i:s", ISO8601Short:"Y-m-d", ShortDate: "n/j/Y", LongDate: "l, F d, Y", FullDateTime: "l, F d, Y g:i:s A", MonthDay: "F d", ShortTime: "g:i A", LongTime: "g:i:s A", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "F, Y" }, reformatAfterEdit : false }, baseLinkUrl: '', showAction: '', target: '', checkbox : {disabled:true}, idName : 'id' } }; })(jQuery);
JavaScript
;(function($){ /** * jqGrid Icelandic Translation * jtm@hi.is Univercity of Iceland * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html **/ $.jgrid = { defaults : { recordtext: "View {0} - {1} of {2}", emptyrecords: "No records to view", loadtext: "Hleður...", pgtext : "Page {0} of {1}" }, search : { caption: "Leita...", Find: "Leita", Reset: "Endursetja", odata : ['equal', 'not equal', 'less', 'less or equal','greater','greater or equal', 'begins with','does not begin with','is in','is not in','ends with','does not end with','contains','does not contain'], groupOps: [ { op: "AND", text: "all" }, { op: "OR", text: "any" } ], matchText: " match", rulesText: " rules" }, edit : { addCaption: "Add Record", editCaption: "Edit Record", bSubmit: "Vista", bCancel: "Hætta við", bClose: "Loka", saveData: "Data has been changed! Save changes?", bYes : "Yes", bNo : "No", bExit : "Cancel", msg: { required:"Reitur er nauðsynlegur", number:"Vinsamlega settu inn tölu", minValue:"gildi verður að vera meira en eða jafnt og ", maxValue:"gildi verður að vera minna en eða jafnt og ", email: "er ekki löglegt email", integer: "Vinsamlega settu inn tölu", date: "Please, enter valid date value", url: "is not a valid URL. Prefix required ('http://' or 'https://')", nodefined : " is not defined!", novalue : " return value is required!", customarray : "Custom function should return array!", customfcheck : "Custom function should be present in case of custom checking!" } }, view : { caption: "View Record", bClose: "Close" }, del : { caption: "Eyða", msg: "Eyða völdum færslum ?", bSubmit: "Eyða", bCancel: "Hætta við" }, nav : { edittext: " ", edittitle: "Breyta færslu", addtext:" ", addtitle: "Ný færsla", deltext: " ", deltitle: "Eyða færslu", searchtext: " ", searchtitle: "Leita", refreshtext: "", refreshtitle: "Endurhlaða", alertcap: "Viðvörun", alerttext: "Vinsamlega veldu færslu", viewtext: "", viewtitle: "View selected row" }, col : { caption: "Sýna / fela dálka", bSubmit: "Vista", bCancel: "Hætta við" }, errors : { errcap : "Villa", nourl : "Vantar slóð", norecords: "Engar færslur valdar", model : "Length of colNames <> colModel!" }, formatter : { integer : {thousandsSeparator: " ", defaultValue: '0'}, number : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: '0.00'}, currency : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, prefix: "", suffix:"", defaultValue: '0.00'}, date : { dayNames: [ "Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], monthNames: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], AmPm : ["am","pm","AM","PM"], S: function (j) {return j < 11 || j > 13 ? ['st', 'nd', 'rd', 'th'][Math.min((j - 1) % 10, 3)] : 'th'}, srcformat: 'Y-m-d', newformat: 'd/m/Y', masks : { ISO8601Long:"Y-m-d H:i:s", ISO8601Short:"Y-m-d", ShortDate: "n/j/Y", LongDate: "l, F d, Y", FullDateTime: "l, F d, Y g:i:s A", MonthDay: "F d", ShortTime: "g:i A", LongTime: "g:i:s A", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "F, Y" }, reformatAfterEdit : false }, baseLinkUrl: '', showAction: '', target: '', checkbox : {disabled:true}, idName : 'id' } }; })(jQuery);
JavaScript
;(function($){ /** * jqGrid Chinese Translation for v3.6 * waiting 2010.01.18 * http://waiting.javaeye.com/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * update 2010.05.04 * add double u3000 SPACE for search:odata to fix SEARCH box display err when narrow width from only use of eq/ne/cn/in/lt/gt operator under IE6/7 **/ $.jgrid = { defaults : { recordtext: "{0} - {1}\u3000共 {2} 条", // 共字前是全角空格 emptyrecords: "无数据显示", loadtext: "读取中...", pgtext : " {0} 共 {1} 页" }, search : { caption: "搜索...", Find: "查找", Reset: "重置", odata : ['等于\u3000\u3000', '不等\u3000\u3000', '小于\u3000\u3000', '小于等于','大于\u3000\u3000','大于等于', '开始于','不开始于','属于\u3000\u3000','不属于','结束于','不结束于','包含\u3000\u3000','不包含'], groupOps: [ { op: "AND", text: "所有" }, { op: "OR", text: "任一" } ], matchText: " 匹配", rulesText: " 规则" }, edit : { addCaption: "添加记录", editCaption: "编辑记录", bSubmit: "提交", bCancel: "取消", bClose: "关闭", saveData: "数据已改变,是否保存?", bYes : "是", bNo : "否", bExit : "取消", msg: { required:"此字段必需", number:"请输入有效数字", minValue:"输值必须大于等于 ", maxValue:"输值必须小于等于 ", email: "这不是有效的e-mail地址", integer: "请输入有效整数", date: "请输入有效时间", url: "无效网址。前缀必须为 ('http://' 或 'https://')", nodefined : " 未定义!", novalue : " 需要返回值!", customarray : "自定义函数需要返回数组!", customfcheck : "Custom function should be present in case of custom checking!" } }, view : { caption: "查看记录", bClose: "关闭" }, del : { caption: "删除", msg: "删除所选记录?", bSubmit: "删除", bCancel: "取消" }, nav : { edittext: "", edittitle: "编辑所选记录", addtext:"", addtitle: "添加新记录", deltext: "", deltitle: "删除所选记录", searchtext: "", searchtitle: "查找", refreshtext: "", refreshtitle: "刷新表格", alertcap: "注意", alerttext: "请选择记录", viewtext: "", viewtitle: "查看所选记录" }, col : { caption: "选择列", bSubmit: "确定", bCancel: "取消" }, errors : { errcap : "错误", nourl : "没有设置url", norecords: "没有要处理的记录", model : "colNames 和 colModel 长度不等!" }, formatter : { integer : {thousandsSeparator: " ", defaultValue: '0'}, number : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: '0.00'}, currency : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, prefix: "", suffix:"", defaultValue: '0.00'}, date : { dayNames: [ "Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], monthNames: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], AmPm : ["am","pm","AM","PM"], S: function (j) {return j < 11 || j > 13 ? ['st', 'nd', 'rd', 'th'][Math.min((j - 1) % 10, 3)] : 'th'}, srcformat: 'Y-m-d', newformat: 'm-d-Y', masks : { ISO8601Long:"Y-m-d H:i:s", ISO8601Short:"Y-m-d", ShortDate: "Y/j/n", LongDate: "l, F d, Y", FullDateTime: "l, F d, Y g:i:s A", MonthDay: "F d", ShortTime: "g:i A", LongTime: "g:i:s A", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "F, Y" }, reformatAfterEdit : false }, baseLinkUrl: '', showAction: '', target: '', checkbox : {disabled:true}, idName : 'id' } }; })(jQuery);
JavaScript
;(function($){ /** * jqGrid Bulgarian Translation * Tony Tomov tony@trirand.com * http://trirand.com/blog/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html **/ $.jgrid = { defaults : { recordtext: "{0} - {1} от {2}", emptyrecords: "Няма запис(и)", loadtext: "Зареждам...", pgtext : "Стр. {0} от {1}" }, search : { caption: "Търсене...", Find: "Намери", Reset: "Изчисти", odata : ['равно', 'различно', 'по-малко', 'по-малко или=','по-голямо','по-голямо или =', 'започва с','не започва с','се намира в','не се намира в','завършва с','не завършава с','съдържа', 'не съдържа' ], groupOps: [ { op: "AND", text: "&nbsp;И " }, { op: "OR", text: "ИЛИ" } ], matchText: " включи", rulesText: " клауза" }, edit : { addCaption: "Нов Запис", editCaption: "Редакция Запис", bSubmit: "Запиши", bCancel: "Изход", bClose: "Затвори", saveData: "Данните са променени! Да съхраня ли промените?", bYes : "Да", bNo : "Не", bExit : "Отказ", msg: { required:"Полето е задължително", number:"Въведете валидно число!", minValue:"стойността трябва да е по-голяма или равна от", maxValue:"стойността трябва да е по-малка или равна от", email: "не е валиден ел. адрес", integer: "Въведете валидно цяло число", date: "Въведете валидна дата", url: "e невалиден URL. Изискава се префикс('http://' или 'https://')", nodefined : " е недефинирана!", novalue : " изисква връщане на стойност!", customarray : "Потреб. Функция трябва да върне масив!", customfcheck : "Потребителска функция е задължителна при този тип елемент!" } }, view : { caption: "Преглед запис", bClose: "Затвори" }, del : { caption: "Изтриване", msg: "Да изтрия ли избраният запис?", bSubmit: "Изтрий", bCancel: "Отказ" }, nav : { edittext: " ", edittitle: "Редакция избран запис", addtext:" ", addtitle: "Добавяне нов запис", deltext: " ", deltitle: "Изтриване избран запис", searchtext: " ", searchtitle: "Търсене запис(и)", refreshtext: "", refreshtitle: "Обнови таблица", alertcap: "Предупреждение", alerttext: "Моля, изберете запис", viewtext: "", viewtitle: "Преглед избран запис" }, col : { caption: "Избери колони", bSubmit: "Ок", bCancel: "Изход" }, errors : { errcap : "Грешка", nourl : "Няма посочен url адрес", norecords: "Няма запис за обработка", model : "Модела не съответства на имената!" }, formatter : { integer : {thousandsSeparator: " ", defaultValue: '0'}, number : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: '0.00'}, currency : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, prefix: "", suffix:" лв.", defaultValue: '0.00'}, date : { dayNames: [ "Нед", "Пон", "Вт", "Ср", "Чет", "Пет", "Съб", "Неделя", "Понеделник", "Вторник", "Сряда", "Четвъртък", "Петък", "Събота" ], monthNames: [ "Яну", "Фев", "Мар", "Апр", "Май", "Юни", "Юли", "Авг", "Сеп", "Окт", "Нов", "Дек", "Януари", "Февруари", "Март", "Април", "Май", "Юни", "Юли", "Август", "Септември", "Октомври", "Ноември", "Декември" ], AmPm : ["","","",""], S: function (j) { if(j==7 || j==8 || j== 27 || j== 28) { return 'ми'; } return ['ви', 'ри', 'ти'][Math.min((j - 1) % 10, 2)]; }, srcformat: 'Y-m-d', newformat: 'd/m/Y', masks : { ISO8601Long:"Y-m-d H:i:s", ISO8601Short:"Y-m-d", ShortDate: "n/j/Y", LongDate: "l, F d, Y", FullDateTime: "l, F d, Y g:i:s A", MonthDay: "F d", ShortTime: "g:i A", LongTime: "g:i:s A", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "F, Y" }, reformatAfterEdit : false }, baseLinkUrl: '', showAction: '', target: '', checkbox : {disabled:true}, idName : 'id' } }; })(jQuery);
JavaScript
;(function($){ /** * jqGrid Japanese Translation * OKADA Yoshitada okada.dev@sth.jp * http://trirand.com/blog/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html **/ $.jgrid = { defaults : { recordtext: "{2} \u4EF6\u4E2D {0} - {1} \u3092\u8868\u793A ", emptyrecords: "\u8868\u793A\u3059\u308B\u30EC\u30B3\u30FC\u30C9\u304C\u3042\u308A\u307E\u305B\u3093", loadtext: "\u8aad\u307f\u8fbc\u307f\u4e2d...", pgtext : "{1} \u30DA\u30FC\u30B8\u4E2D {0} \u30DA\u30FC\u30B8\u76EE " }, search : { caption: "\u691c\u7d22...", Find: "\u691c\u7d22", Reset: "\u30ea\u30bb\u30c3\u30c8", odata: ["\u6B21\u306B\u7B49\u3057\u3044", "\u6B21\u306B\u7B49\u3057\u304F\u306A\u3044", "\u6B21\u3088\u308A\u5C0F\u3055\u3044", "\u6B21\u306B\u7B49\u3057\u3044\u304B\u5C0F\u3055\u3044", "\u6B21\u3088\u308A\u5927\u304D\u3044", "\u6B21\u306B\u7B49\u3057\u3044\u304B\u5927\u304D\u3044", "\u6B21\u3067\u59CB\u307E\u308B", "\u6B21\u3067\u59CB\u307E\u3089\u306A\u3044", "\u6B21\u306B\u542B\u307E\u308C\u308B", "\u6B21\u306B\u542B\u307E\u308C\u306A\u3044", "\u6B21\u3067\u7D42\u308F\u308B", "\u6B21\u3067\u7D42\u308F\u3089\u306A\u3044", "\u6B21\u3092\u542B\u3080", "\u6B21\u3092\u542B\u307E\u306A\u3044"], groupOps: [{ op: "AND", text: "\u3059\u3079\u3066\u306E" }, { op: "OR", text: "\u3044\u305A\u308C\u304B\u306E" }], matchText: " \u6B21\u306E", rulesText: " \u6761\u4EF6\u3092\u6E80\u305F\u3059" }, edit : { addCaption: "\u30ec\u30b3\u30fc\u30c9\u8ffd\u52a0", editCaption: "\u30ec\u30b3\u30fc\u30c9\u7de8\u96c6", bSubmit: "\u9001\u4fe1", bCancel: "\u30ad\u30e3\u30f3\u30bb\u30eb", bClose: "\u9589\u3058\u308b", saveData: "\u30C7\u30FC\u30BF\u304C\u5909\u66F4\u3055\u308C\u3066\u3044\u307E\u3059\u3002\u4FDD\u5B58\u3057\u307E\u3059\u304B\uFF1F", bYes: "\u306F\u3044", bNo: "\u3044\u3044\u3048", bExit: "\u30AD\u30E3\u30F3\u30BB\u30EB", msg: { required:"\u3053\u306e\u9805\u76ee\u306f\u5fc5\u9808\u3067\u3059\u3002", number:"\u6b63\u3057\u3044\u6570\u5024\u3092\u5165\u529b\u3057\u3066\u4e0b\u3055\u3044\u3002", minValue:"\u6b21\u306e\u5024\u4ee5\u4e0a\u3067\u5165\u529b\u3057\u3066\u4e0b\u3055\u3044\u3002", maxValue:"\u6b21\u306e\u5024\u4ee5\u4e0b\u3067\u5165\u529b\u3057\u3066\u4e0b\u3055\u3044\u3002", email: "e-mail\u304c\u6b63\u3057\u304f\u3042\u308a\u307e\u305b\u3093\u3002", integer: "\u6b63\u3057\u3044\u6574\u6570\u5024\u3092\u5165\u529b\u3057\u3066\u4e0b\u3055\u3044\u3002", date: "\u6b63\u3057\u3044\u5024\u3092\u5165\u529b\u3057\u3066\u4e0b\u3055\u3044\u3002", url: "\u306F\u6709\u52B9\u306AURL\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002\20\u30D7\u30EC\u30D5\u30A3\u30C3\u30AF\u30B9\u304C\u5FC5\u8981\u3067\u3059\u3002 ('http://' \u307E\u305F\u306F 'https://')", nodefined: " \u304C\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u307E\u305B\u3093", novalue: " \u623B\u308A\u5024\u304C\u5FC5\u8981\u3067\u3059", customarray: "\u30AB\u30B9\u30BF\u30E0\u95A2\u6570\u306F\u914D\u5217\u3092\u8FD4\u3059\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059", customfcheck: "\u30AB\u30B9\u30BF\u30E0\u691C\u8A3C\u306B\u306F\u30AB\u30B9\u30BF\u30E0\u95A2\u6570\u304C\u5FC5\u8981\u3067\u3059" } }, view : { caption: "\u30EC\u30B3\u30FC\u30C9\u3092\u8868\u793A", bClose: "\u9589\u3058\u308B" }, del : { caption: "\u524a\u9664", msg: "\u9078\u629e\u3057\u305f\u30ec\u30b3\u30fc\u30c9\u3092\u524a\u9664\u3057\u307e\u3059\u304b\uff1f", bSubmit: "\u524a\u9664", bCancel: "\u30ad\u30e3\u30f3\u30bb\u30eb" }, nav : { edittext: " ", edittitle: "\u9078\u629e\u3057\u305f\u884c\u3092\u7de8\u96c6", addtext:" ", addtitle: "\u884c\u3092\u65b0\u898f\u8ffd\u52a0", deltext: " ", deltitle: "\u9078\u629e\u3057\u305f\u884c\u3092\u524a\u9664", searchtext: " ", searchtitle: "\u30ec\u30b3\u30fc\u30c9\u691c\u7d22", refreshtext: "", refreshtitle: "\u30b0\u30ea\u30c3\u30c9\u3092\u30ea\u30ed\u30fc\u30c9", alertcap: "\u8b66\u544a", alerttext: "\u884c\u3092\u9078\u629e\u3057\u3066\u4e0b\u3055\u3044\u3002", viewtext: "", viewtitle: "\u9078\u629E\u3057\u305F\u884C\u3092\u8868\u793A" }, col : { caption: "\u5217\u3092\u8868\u793a\uff0f\u96a0\u3059", bSubmit: "\u9001\u4fe1", bCancel: "\u30ad\u30e3\u30f3\u30bb\u30eb" }, errors : { errcap : "\u30a8\u30e9\u30fc", nourl : "URL\u304c\u8a2d\u5b9a\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002", norecords: "\u51e6\u7406\u5bfe\u8c61\u306e\u30ec\u30b3\u30fc\u30c9\u304c\u3042\u308a\u307e\u305b\u3093\u3002", model : "colNames\u306e\u9577\u3055\u304ccolModel\u3068\u4e00\u81f4\u3057\u307e\u305b\u3093\u3002" }, formatter : { integer: { thousandsSeparator: ",", defaultValue: '0' }, number: { decimalSeparator: ".", thousandsSeparator: ",", decimalPlaces: 2, defaultValue: '0.00' }, currency: { decimalSeparator: ".", thousandsSeparator: ",", decimalPlaces: 0, prefix: "", suffix: "", defaultValue: '0' }, date : { dayNames: [ "\u65e5", "\u6708", "\u706b", "\u6c34", "\u6728", "\u91d1", "\u571f", "\u65e5", "\u6708", "\u706b", "\u6c34", "\u6728", "\u91d1", "\u571f" ], monthNames: [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "1\u6708", "2\u6708", "3\u6708", "4\u6708", "5\u6708", "6\u6708", "7\u6708", "8\u6708", "9\u6708", "10\u6708", "11\u6708", "12\u6708" ], AmPm : ["am","pm","AM","PM"], S: "\u756a\u76ee", srcformat: 'Y-m-d', newformat: 'd/m/Y', masks : { ISO8601Long:"Y-m-d H:i:s", ISO8601Short:"Y-m-d", ShortDate: "n/j/Y", LongDate: "l, F d, Y", FullDateTime: "l, F d, Y g:i:s A", MonthDay: "F d", ShortTime: "g:i A", LongTime: "g:i:s A", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "F, Y" }, reformatAfterEdit : false }, baseLinkUrl: '', showAction: '', target: '', checkbox : {disabled:true}, idName : 'id' } }; })(jQuery);
JavaScript
;(function($){ /** * jqGrid (fi) Finnish Translation * Jukka Inkeri awot.fi 2010-05-19 Version * http://awot.fi * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html **/ $.jgrid = { defaults : { //recordtext: "N&auml;yt&auml; {0} - {1} / {2}", recordtext: " {0}-{1}/{2}", emptyrecords: "Ei n&auml;ytett&auml;vi&auml;", loadtext: "Haetaan...", //pgtext : "Sivu {0} / {1}" pgtext : "{0}/{1}" }, search : { caption: "Etsi...", Find: "Etsi", Reset: "Tyhj&auml;&auml;", odata : ['=', '<>', '<', '<=','>','>=', 'alkaa','ei ala','joukossa','ei joukossa ','loppuu','ei lopu','sis&auml;lt&auml;&auml;','ei sis&auml;ll&auml;'], groupOps: [ { op: "JA", text: "kaikki" }, { op: "TAI", text: "mik&auml; tahansa" } ], matchText: " match", rulesText: " rules" }, edit : { addCaption: "Uusi rivi", editCaption: "Muokkaa rivi", bSubmit: "OK", bCancel: "Peru", bClose: "Sulje", saveData: "Tietoja muutettu! Tallenetaanko?", bYes : "K", bNo : "E", bExit : "Peru", msg: { required:"pakollinen", number:"Anna kelvollinen nro", minValue:"arvo oltava >= ", maxValue:"arvo oltava <= ", email: "virheellinen sposti ", integer: "Anna kelvollinen kokonaisluku", date: "Anna kelvollinen pvm", url: "Ei ole sopiva linkki(URL). Alku oltava ('http://' tai 'https://')", nodefined : " ei ole m&auml;&auml;ritelty!", novalue : " paluuarvo vaaditaan!", customarray : "Custom function should return array!", customfcheck : "Custom function should be present in case of custom checking!" } }, view : { caption: "N&auml; rivi", bClose: "Sulje" }, del : { caption: "Poista", msg: "Poista valitut rivi(t)?", bSubmit: "Poista", bCancel: "Peru" }, nav : { edittext: " ", edittitle: "Muokkaa valittu rivi", addtext:" ", addtitle: "Uusi rivi", deltext: " ", deltitle: "Poista valittu rivi", searchtext: " ", searchtitle: "Etsi tietoja", refreshtext: "", refreshtitle: "Lataa uudelleen", alertcap: "Varoitus", alerttext: "Valitse rivi", viewtext: "", viewtitle: "Nayta valitut rivit" }, col : { caption: "Nayta/Piilota sarakkeet", bSubmit: "OK", bCancel: "Peru" }, errors : { errcap : "Virhe", nourl : "url asettamatta", norecords: "Ei muokattavia tietoja", model : "Pituus colNames <> colModel!" }, formatter : { integer : {thousandsSeparator: "", defaultValue: '0'}, number : {decimalSeparator:",", thousandsSeparator: "", decimalPlaces: 2, defaultValue: '0,00'}, currency : {decimalSeparator:",", thousandsSeparator: "", decimalPlaces: 2, prefix: "", suffix:"", defaultValue: '0,00'}, date : { dayNames: [ "Su", "Ma", "Ti", "Ke", "To", "Pe", "La", "Sunnuntai", "Maanantai", "Tiista", "Keskiviikko", "Torstai", "Perjantai", "Lauantai" ], monthNames: [ "Tam", "Hel", "Maa", "Huh", "Tou", "Kes", "Hei", "Elo", "Syy", "Lok", "Mar", "Jou", "Tammikuu", "Helmikuu", "Maaliskuu", "Huhtikuu", "Toukokuu", "Kes&auml;kuu", "Hein&auml;kuu", "Elokuu", "Syyskuu", "Lokakuu", "Marraskuu", "Joulukuu" ], AmPm : ["am","pm","AM","PM"], S: function (j) {return j < 11 || j > 13 ? ['st', 'nd', 'rd', 'th'][Math.min((j - 1) % 10, 3)] : 'th'}, srcformat: 'Y-m-d', newformat: 'd/m/Y', masks : { ISO8601Long:"Y-m-d H:i:s", ISO8601Short:"Y-m-d", ShortDate: "d.m.Y", LongDate: "l, F d, Y", FullDateTime: "l, F d, Y g:i:s A", MonthDay: "F d", ShortTime: "g:i A", LongTime: "g:i:s A", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "F, Y" }, reformatAfterEdit : false }, baseLinkUrl: '', showAction: '', target: '', checkbox : {disabled:true}, idName : 'id' } }; // FI })(jQuery);
JavaScript
;(function($){ /** * jqGrid Galician Translation * Translated by Jorge Barreiro <yortx.barry@gmail.com> * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html **/ $.jgrid = { defaults : { recordtext: "Amosando {0} - {1} de {2}", emptyrecords: "Sen rexistros que amosar", loadtext: "Cargando...", pgtext : "Páxina {0} de {1}" }, search : { caption: "Búsqueda...", Find: "Buscar", Reset: "Limpar", odata : ['igual ', 'diferente a', 'menor que', 'menor ou igual que','maior que','maior ou igual a', 'empece por','non empece por','está en','non está en','termina por','non termina por','contén','non contén'], groupOps: [ { op: "AND", text: "todo" }, { op: "OR", text: "calquera" } ], matchText: " match", rulesText: " regras" }, edit : { addCaption: "Engadir rexistro", editCaption: "Modificar rexistro", bSubmit: "Gardar", bCancel: "Cancelar", bClose: "Pechar", saveData: "Modificáronse os datos, quere gardar os cambios?", bYes : "Si", bNo : "Non", bExit : "Cancelar", msg: { required:"Campo obrigatorio", number:"Introduza un número", minValue:"O valor debe ser maior ou igual a ", maxValue:"O valor debe ser menor ou igual a ", email: "non é un enderezo de correo válido", integer: "Introduza un valor enteiro", date: "Introduza unha data correcta ", url: "non é unha URL válida. Prefixo requerido ('http://' ou 'https://')", nodefined : " non está definido.", novalue : " o valor de retorno é obrigatorio.", customarray : "A función persoalizada debe devolver un array.", customfcheck : "A función persoalizada debe estar presente no caso de ter validación persoalizada." } }, view : { caption: "Consultar rexistro", bClose: "Pechar" }, del : { caption: "Eliminar", msg: "Desexa eliminar os rexistros seleccionados?", bSubmit: "Eliminar", bCancel: "Cancelar" }, nav : { edittext: " ", edittitle: "Modificar a fila seleccionada", addtext:" ", addtitle: "Engadir unha nova fila", deltext: " ", deltitle: "Eliminar a fila seleccionada", searchtext: " ", searchtitle: "Buscar información", refreshtext: "", refreshtitle: "Recargar datos", alertcap: "Aviso", alerttext: "Seleccione unha fila", viewtext: "", viewtitle: "Ver fila seleccionada" }, col : { caption: "Mostrar/ocultar columnas", bSubmit: "Enviar", bCancel: "Cancelar" }, errors : { errcap : "Erro", nourl : "Non especificou unha URL", norecords: "Non hai datos para procesar", model : "As columnas de nomes son diferentes das columnas de modelo" }, formatter : { integer : {thousandsSeparator: ".", defaultValue: '0'}, number : {decimalSeparator:",", thousandsSeparator: ".", decimalPlaces: 2, defaultValue: '0,00'}, currency : {decimalSeparator:",", thousandsSeparator: ".", decimalPlaces: 2, prefix: "", suffix:"", defaultValue: '0,00'}, date : { dayNames: [ "Do", "Lu", "Ma", "Me", "Xo", "Ve", "Sa", "Domingo", "Luns", "Martes", "Mércoles", "Xoves", "Vernes", "Sábado" ], monthNames: [ "Xan", "Feb", "Mar", "Abr", "Mai", "Xuñ", "Xul", "Ago", "Set", "Out", "Nov", "Dec", "Xaneiro", "Febreiro", "Marzo", "Abril", "Maio", "Xuño", "Xullo", "Agosto", "Setembro", "Outubro", "Novembro", "Decembro" ], AmPm : ["am","pm","AM","PM"], S: function (j) {return j < 11 || j > 13 ? ['st', 'nd', 'rd', 'th'][Math.min((j - 1) % 10, 3)] : 'th'}, srcformat: 'Y-m-d', newformat: 'd-m-Y', masks : { ISO8601Long:"Y-m-d H:i:s", ISO8601Short:"Y-m-d", ShortDate: "n/j/Y", LongDate: "l, F d, Y", FullDateTime: "l, F d, Y g:i:s A", MonthDay: "F d", ShortTime: "g:i A", LongTime: "g:i:s A", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "F, Y" }, reformatAfterEdit : false }, baseLinkUrl: '', showAction: '', target: '', checkbox : {disabled:true}, idName : 'id' } }; })(jQuery);
JavaScript
;(function($){ /** * jqGrid Serbian Translation * Александар Миловац(Aleksandar Milovac) aleksandar.milovac@gmail.com * http://trirand.com/blog/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html **/ $.jgrid = { defaults : { recordtext: "Преглед {0} - {1} од {2}", emptyrecords: "Не постоји ниједан запис", loadtext: "Учитавање...", pgtext : "Страна {0} од {1}" }, search : { caption: "Тражење...", Find: "Тражи", Reset: "Ресетуј", odata : ['једнако', 'није једнако', 'мање', 'мање или једнако','веће','веће или једнако', 'почиње са','не почиње са','је у','није у','завршава са','не завршава са','садржи','не садржи'], groupOps: [ { op: "И", text: "сви" }, { op: "ИЛИ", text: "сваки" } ], matchText: " match", rulesText: " правила" }, edit : { addCaption: "Додај запис", editCaption: "Измени запис", bSubmit: "Пошаљи", bCancel: "Одустани", bClose: "Затвори", saveData: "Податак је измењен! Сачувај измене?", bYes : "Да", bNo : "Не", bExit : "Одустани", msg: { required:"Поље је обавезно", number:"Молим, унесите исправан број", minValue:"вредност мора бити већа од или једнака са ", maxValue:"вредност мора бити мања од или једнака са", email: "није исправна имејл адреса", integer: "Молим, унесите исправну целобројну вредност ", date: "Молим, унесите исправан датум", url: "није исправан УРЛ. Потребан је префикс ('http://' or 'https://')", nodefined : " није дефинисан!", novalue : " захтевана је повратна вредност!", customarray : "Custom function should return array!", customfcheck : "Custom function should be present in case of custom checking!" } }, view : { caption: "Погледај запис", bClose: "Затвори" }, del : { caption: "Избриши", msg: "Избриши изабран(е) запис(е)?", bSubmit: "Ибриши", bCancel: "Одбаци" }, nav : { edittext: "", edittitle: "Измени изабрани ред", addtext:"", addtitle: "Додај нови ред", deltext: "", deltitle: "Избриши изабран ред", searchtext: "", searchtitle: "Нађи записе", refreshtext: "", refreshtitle: "Поново учитај податке", alertcap: "Упозорење", alerttext: "Молим, изаберите ред", viewtext: "", viewtitle: "Погледај изабрани ред" }, col : { caption: "Изабери колоне", bSubmit: "ОК", bCancel: "Одбаци" }, errors : { errcap : "Грешка", nourl : "Није постављен URL", norecords: "Нема записа за обраду", model : "Дужина модела colNames <> colModel!" }, formatter : { integer : {thousandsSeparator: " ", defaultValue: '0'}, number : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: '0.00'}, currency : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, prefix: "", suffix:"", defaultValue: '0.00'}, date : { dayNames: [ "Нед", "Пон", "Уто", "Сре", "Чет", "Пет", "Суб", "Недеља", "Понедељак", "Уторак", "Среда", "Четвртак", "Петак", "Субота" ], monthNames: [ "Јан", "Феб", "Мар", "Апр", "Мај", "Јун", "Јул", "Авг", "Сеп", "Окт", "Нов", "Дец", "Јануар", "Фебруар", "Март", "Април", "Мај", "Јун", "Јул", "Август", "Септембар", "Октобар", "Новембар", "Децембар" ], AmPm : ["am","pm","AM","PM"], S: function (j) {return j < 11 || j > 13 ? ['st', 'nd', 'rd', 'th'][Math.min((j - 1) % 10, 3)] : 'th'}, srcformat: 'Y-m-d', newformat: 'd/m/Y', masks : { ISO8601Long:"Y-m-d H:i:s", ISO8601Short:"Y-m-d", ShortDate: "n/j/Y", LongDate: "l, F d, Y", FullDateTime: "l, F d, Y g:i:s A", MonthDay: "F d", ShortTime: "g:i A", LongTime: "g:i:s A", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "F, Y" }, reformatAfterEdit : false }, baseLinkUrl: '', showAction: '', target: '', checkbox : {disabled:true}, idName : 'id' } }; })(jQuery);
JavaScript
;(function($){ /** * jqGrid French Translation * Tony Tomov tony@trirand.com * http://trirand.com/blog/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html **/ $.jgrid = { defaults : { recordtext: "Enregistrements {0} - {1} sur {2}", emptyrecords: "Aucun enregistrement à afficher", loadtext: "Chargement...", pgtext : "Page {0} sur {1}" }, search : { caption: "Recherche...", Find: "Chercher", Reset: "Annuler", odata : ['égal', 'différent', 'inférieur', 'inférieur ou égal','supérieur','supérieur ou égal', 'commence par','ne commence pas par','est dans',"n'est pas dans",'finit par','ne finit pas par','contient','ne contient pas'], groupOps: [ { op: "AND", text: "tous" }, { op: "OR", text: "aucun" } ], matchText: " correspondance", rulesText: " règles" }, edit : { addCaption: "Ajouter", editCaption: "Editer", bSubmit: "Valider", bCancel: "Annuler", bClose: "Fermer", saveData: "Les données ont changé ! Enregistrer les modifications ?", bYes: "Oui", bNo: "Non", bExit: "Annuler", msg: { required: "Champ obligatoire", number: "Saisissez un nombre correct", minValue: "La valeur doit être supérieure ou égale à", maxValue: "La valeur doit être inférieure ou égale à", email: "n'est pas un email correct", integer: "Saisissez un entier correct", url: "n'est pas une adresse correcte. Préfixe requis ('http://' or 'https://')", nodefined : " n'est pas défini!", novalue : " la valeur de retour est requise!", customarray : "Une fonction personnalisée devrait retourner un tableau (array)!", customfcheck : "Une fonction personnalisée devrait être présente dans le cas d'une vérification personnalisée!" } }, view : { caption: "Voir les enregistrement", bClose: "Fermer" }, del : { caption: "Supprimer", msg: "Supprimer les enregistrements sélectionnés ?", bSubmit: "Supprimer", bCancel: "Annuler" }, nav : { edittext: " ", edittitle: "Editer la ligne sélectionnée", addtext:" ", addtitle: "Ajouter une ligne", deltext: " ", deltitle: "Supprimer la ligne sélectionnée", searchtext: " ", searchtitle: "Chercher un enregistrement", refreshtext: "", refreshtitle: "Recharger le tableau", alertcap: "Avertissement", alerttext: "Veuillez sélectionner une ligne", viewtext: "", viewtitle: "Afficher la ligne sélectionnée" }, col : { caption: "Afficher/Masquer les colonnes", bSubmit: "Valider", bCancel: "Annuler" }, errors : { errcap : "Erreur", nourl : "Aucune adresse n'est paramétrée", norecords: "Aucun enregistrement à traiter", model : "Nombre de titres (colNames) <> Nombre de données (colModel)!" }, formatter : { integer : {thousandsSeparator: " ", defaultValue: '0'}, number : {decimalSeparator:",", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: '0,00'}, currency : {decimalSeparator:",", thousandsSeparator: " ", decimalPlaces: 2, prefix: "", suffix:"", defaultValue: '0,00'}, date : { dayNames: [ "Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi" ], monthNames: [ "Jan", "Fév", "Mar", "Avr", "Mai", "Jui", "Jul", "Aou", "Sep", "Oct", "Nov", "Déc", "Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Aout", "Septembre", "Octobre", "Novembre", "Décembre" ], AmPm : ["am","pm","AM","PM"], S: function (j) {return j == 1 ? 'er' : 'e';}, srcformat: 'Y-m-d', newformat: 'd/m/Y', masks : { ISO8601Long:"Y-m-d H:i:s", ISO8601Short:"Y-m-d", ShortDate: "n/j/Y", LongDate: "l, F d, Y", FullDateTime: "l, F d, Y g:i:s A", MonthDay: "F d", ShortTime: "g:i A", LongTime: "g:i:s A", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "F, Y" }, reformatAfterEdit : false }, baseLinkUrl: '', showAction: '', target: '', checkbox : {disabled:true}, idName : 'id' } }; })(jQuery);
JavaScript
;(function($){ /** * jqGrid Czech Translation * Pavel Jirak pavel.jirak@jipas.cz * doplnil Thomas Wagner xwagne01@stud.fit.vutbr.cz * http://trirand.com/blog/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html **/ $.jgrid = { defaults : { recordtext: "Zobrazeno {0} - {1} z {2} záznamů", emptyrecords: "Nenalezeny žádné záznamy", loadtext: "Načítám...", pgtext : "Strana {0} z {1}" }, search : { caption: "Vyhledávám...", Find: "Hledat", Reset: "Reset", odata : ['rovno', 'nerovono', 'menší', 'menší nebo rovno','větší', 'větší nebo rovno', 'začíná s', 'nezačíná s', 'je v', 'není v', 'končí s', 'nekončí s', 'obahuje', 'neobsahuje'], groupOps: [ { op: "AND", text: "všech" }, { op: "OR", text: "některého z" } ], matchText: " hledat podle", rulesText: " pravidel" }, edit : { addCaption: "Přidat záznam", editCaption: "Editace záznamu", bSubmit: "Uložit", bCancel: "Storno", bClose: "Zavřít", saveData: "Data byla změněna! Uložit změny?", bYes : "Ano", bNo : "Ne", bExit : "Zrušit", msg: { required:"Pole je vyžadováno", number:"Prosím, vložte validní číslo", minValue:"hodnota musí být větší než nebo rovná ", maxValue:"hodnota musí být menší než nebo rovná ", email: "není validní e-mail", integer: "Prosím, vložte celé číslo", date: "Prosím, vložte validní datum", url: "není platnou URL. Vyžadován prefix ('http://' or 'https://')", nodefined : " není definován!", novalue : " je vyžadována návratová hodnota!", customarray : "Custom function mělá vrátit pole!", customfcheck : "Custom function by měla být přítomna v případě custom checking!" } }, view : { caption: "Zobrazit záznam", bClose: "Zavřít" }, del : { caption: "Smazat", msg: "Smazat vybraný(é) záznam(y)?", bSubmit: "Smazat", bCancel: "Storno" }, nav : { edittext: " ", edittitle: "Editovat vybraný řádek", addtext:" ", addtitle: "Přidat nový řádek", deltext: " ", deltitle: "Smazat vybraný záznam ", searchtext: " ", searchtitle: "Najít záznamy", refreshtext: "", refreshtitle: "Obnovit tabulku", alertcap: "Varování", alerttext: "Prosím, vyberte řádek", viewtext: "", viewtitle: "Zobrazit vybraný řádek" }, col : { caption: "Zobrazit/Skrýt sloupce", bSubmit: "Uložit", bCancel: "Storno" }, errors : { errcap : "Chyba", nourl : "Není nastavena url", norecords: "Žádné záznamy ke zpracování", model : "Délka colNames <> colModel!" }, formatter : { integer : {thousandsSeparator: " ", defaultValue: '0'}, number : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: '0.00'}, currency : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, prefix: "", suffix:"", defaultValue: '0.00'}, date : { dayNames: [ "Ne", "Po", "Út", "St", "Čt", "Pá", "So", "Neděle", "Pondělí", "Úterý", "Středa", "Čtvrtek", "Pátek", "Sobota" ], monthNames: [ "Led", "Úno", "Bře", "Dub", "Kvě", "Čer", "Čvc", "Srp", "Zář", "Říj", "Lis", "Pro", "Leden", "Únor", "Březen", "Duben", "Květen", "Červen", "Červenec", "Srpen", "Září", "Říjen", "Listopad", "Prosinec" ], AmPm : ["do","od","DO","OD"], S: function (j) {return j < 11 || j > 13 ? ['st', 'nd', 'rd', 'th'][Math.min((j - 1) % 10, 3)] : 'th'}, srcformat: 'Y-m-d', newformat: 'd/m/Y', masks : { ISO8601Long:"Y-m-d H:i:s", ISO8601Short:"Y-m-d", ShortDate: "n/j/Y", LongDate: "l, F d, Y", FullDateTime: "l, F d, Y g:i:s A", MonthDay: "F d", ShortTime: "g:i A", LongTime: "g:i:s A", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "F, Y" }, reformatAfterEdit : false }, baseLinkUrl: '', showAction: '', target: '', checkbox : {disabled:true}, idName : 'id' } }; })(jQuery);
JavaScript
;(function($){ /** * jqGrid English Translation * Tony Tomov tony@trirand.com * http://trirand.com/blog/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html **/ $.jgrid = { defaults : { recordtext: "View {0} - {1} of {2}", emptyrecords: "No records to view", loadtext: "Loading...", pgtext : "Page {0} of {1}" }, search : { caption: "Search...", Find: "Find", Reset: "Reset", odata : ['equal', 'not equal', 'less', 'less or equal','greater','greater or equal', 'begins with','does not begin with','is in','is not in','ends with','does not end with','contains','does not contain'], groupOps: [ { op: "AND", text: "all" }, { op: "OR", text: "any" } ], matchText: " match", rulesText: " rules" }, edit : { addCaption: "Add Record", editCaption: "Edit Record", bSubmit: "Submit", bCancel: "Cancel", bClose: "Close", saveData: "Data has been changed! Save changes?", bYes : "Yes", bNo : "No", bExit : "Cancel", msg: { required:"Field is required", number:"Please, enter valid number", minValue:"value must be greater than or equal to ", maxValue:"value must be less than or equal to", email: "is not a valid e-mail", integer: "Please, enter valid integer value", date: "Please, enter valid date value", url: "is not a valid URL. Prefix required ('http://' or 'https://')", nodefined : " is not defined!", novalue : " return value is required!", customarray : "Custom function should return array!", customfcheck : "Custom function should be present in case of custom checking!" } }, view : { caption: "View Record", bClose: "Close" }, del : { caption: "Delete", msg: "Delete selected record(s)?", bSubmit: "Delete", bCancel: "Cancel" }, nav : { edittext: "", edittitle: "Edit selected row", addtext:"", addtitle: "Add new row", deltext: "", deltitle: "Delete selected row", searchtext: "", searchtitle: "Find records", refreshtext: "", refreshtitle: "Reload Grid", alertcap: "Warning", alerttext: "Please, select row", viewtext: "", viewtitle: "View selected row" }, col : { caption: "Select columns", bSubmit: "Ok", bCancel: "Cancel" }, errors : { errcap : "Error", nourl : "No url is set", norecords: "No records to process", model : "Length of colNames <> colModel!" }, formatter : { integer : {thousandsSeparator: " ", defaultValue: '0'}, number : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: '0.00'}, currency : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, prefix: "", suffix:"", defaultValue: '0.00'}, date : { dayNames: [ "Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], monthNames: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], AmPm : ["am","pm","AM","PM"], S: function (j) {return j < 11 || j > 13 ? ['st', 'nd', 'rd', 'th'][Math.min((j - 1) % 10, 3)] : 'th'}, srcformat: 'Y-m-d', newformat: 'd/m/Y', masks : { ISO8601Long:"Y-m-d H:i:s", ISO8601Short:"Y-m-d", ShortDate: "n/j/Y", LongDate: "l, F d, Y", FullDateTime: "l, F d, Y g:i:s A", MonthDay: "F d", ShortTime: "g:i A", LongTime: "g:i:s A", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "F, Y" }, reformatAfterEdit : false }, baseLinkUrl: '', showAction: '', target: '', checkbox : {disabled:true}, idName : 'id' } }; })(jQuery);
JavaScript
;(function($){ /** * jqGrid Hungarian Translation * Őrszigety Ádám udx6bs@freemail.hu * http://trirand.com/blog/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html **/ $.jgrid = { defaults : { recordtext: "Oldal {0} - {1} / {2}", emptyrecords: "Nincs találat", loadtext: "Betöltés...", pgtext : "Oldal {0} / {1}" }, search : { caption: "Keresés...", Find: "Keres", Reset: "Alapértelmezett", odata : ['egyenlő', 'nem egyenlő', 'kevesebb', 'kevesebb vagy egyenlő','nagyobb','nagyobb vagy egyenlő', 'ezzel kezdődik','nem ezzel kezdődik','tartalmaz','nem tartalmaz','végződik','nem végződik','tartalmaz','nem tartalmaz'], groupOps: [ { op: "AND", text: "all" }, { op: "OR", text: "any" } ], matchText: " match", rulesText: " rules" }, edit : { addCaption: "Új tétel", editCaption: "Tétel szerkesztése", bSubmit: "Mentés", bCancel: "Mégse", bClose: "Bezárás", saveData: "A tétel megváltozott! Tétel mentése?", bYes : "Igen", bNo : "Nem", bExit : "Mégse", msg: { required:"Kötelező mező", number:"Kérjük, adjon meg egy helyes számot", minValue:"Nagyobb vagy egyenlőnek kell lenni mint ", maxValue:"Kisebb vagy egyenlőnek kell lennie mint", email: "hibás emailcím", integer: "Kérjük adjon meg egy helyes egész számot", date: "Kérjük adjon meg egy helyes dátumot", url: "nem helyes cím. Előtag kötelező ('http://' vagy 'https://')", nodefined : " nem definiált!", novalue : " visszatérési érték kötelező!!", customarray : "Custom function should return array!", customfcheck : "Custom function should be present in case of custom checking!" } }, view : { caption: "Tétel megtekintése", bClose: "Bezárás" }, del : { caption: "Törlés", msg: "Kiválaztott tétel(ek) törlése?", bSubmit: "Törlés", bCancel: "Mégse" }, nav : { edittext: "", edittitle: "Tétel szerkesztése", addtext:"", addtitle: "Új tétel hozzáadása", deltext: "", deltitle: "Tétel törlése", searchtext: "", searchtitle: "Keresés", refreshtext: "", refreshtitle: "Frissítés", alertcap: "Figyelmeztetés", alerttext: "Kérem válasszon tételt.", viewtext: "", viewtitle: "Tétel megtekintése" }, col : { caption: "Oszlopok kiválasztása", bSubmit: "Ok", bCancel: "Mégse" }, errors : { errcap : "Hiba", nourl : "Nincs URL beállítva", norecords: "Nincs feldolgozásra váró tétel", model : "colNames és colModel hossza nem egyenlő!" }, formatter : { integer : {thousandsSeparator: " ", defaultValue: '0'}, number : {decimalSeparator:",", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: '0,00'}, currency : {decimalSeparator:",", thousandsSeparator: " ", decimalPlaces: 2, prefix: "", suffix:"", defaultValue: '0,00'}, date : { dayNames: [ "Va", "Hé", "Ke", "Sze", "Csü", "Pé", "Szo", "Vasárnap", "Hétfő", "Kedd", "Szerda", "Csütörtök", "Péntek", "Szombat" ], monthNames: [ "Jan", "Feb", "Már", "Ápr", "Máj", "Jún", "Júl", "Aug", "Szep", "Okt", "Nov", "Dec", "Január", "Február", "Március", "Áprili", "Május", "Június", "Július", "Augusztus", "Szeptember", "Október", "November", "December" ], AmPm : ["de","du","DE","DU"], S: function (j) {return '.-ik';}, srcformat: 'Y-m-d', newformat: 'Y/m/d', masks : { ISO8601Long:"Y-m-d H:i:s", ISO8601Short:"Y-m-d", ShortDate: "Y/j/n", LongDate: "Y. F hó d., l", FullDateTime: "l, F d, Y g:i:s A", MonthDay: "F d", ShortTime: "a g:i", LongTime: "a g:i:s", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "Y, F" }, reformatAfterEdit : false }, baseLinkUrl: '', showAction: '', target: '', checkbox : {disabled:true}, idName : 'id' } }; })(jQuery);
JavaScript
;(function($){ /** * jqGrid Slovak Translation * Milan Cibulka * http://trirand.com/blog/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html **/ $.jgrid = { defaults : { recordtext: "Zobrazených {0} - {1} z {2} záznamov", emptyrecords: "Neboli nájdené žiadne záznamy", loadtext: "Načítám...", pgtext : "Strana {0} z {1}" }, search : { caption: "Vyhľadávam...", Find: "Hľadať", Reset: "Reset", odata : ['rovná sa', 'nerovná sa', 'menšie', 'menšie alebo rovnajúce sa','väčšie', 'väčšie alebo rovnajúce sa', 'začína s', 'nezačína s', 'je v', 'nie je v', 'končí s', 'nekončí s', 'obahuje', 'neobsahuje'], groupOps: [ { op: "AND", text: "všetkých" }, { op: "OR", text: "niektorého z" } ], matchText: " hľadať podla", rulesText: " pravidiel" }, edit : { addCaption: "Pridať záznam", editCaption: "Editácia záznamov", bSubmit: "Uložiť", bCancel: "Storno", bClose: "Zavrieť", saveData: "Údaje boli zmenené! Uložiť zmeny?", bYes : "Ano", bNo : "Nie", bExit : "Zrušiť", msg: { required:"Pole je požadované", number:"Prosím, vložte valídne číslo", minValue:"hodnota musí býť väčšia ako alebo rovná ", maxValue:"hodnota musí býť menšia ako alebo rovná ", email: "nie je valídny e-mail", integer: "Prosím, vložte celé číslo", date: "Prosím, vložte valídny dátum", url: "nie je platnou URL. Požadovaný prefix ('http://' alebo 'https://')", nodefined : " nie je definovaný!", novalue : " je vyžadovaná návratová hodnota!", customarray : "Custom function mala vrátiť pole!", customfcheck : "Custom function by mala byť prítomná v prípade custom checking!" } }, view : { caption: "Zobraziť záznam", bClose: "Zavrieť" }, del : { caption: "Zmazať", msg: "Zmazať vybraný(é) záznam(y)?", bSubmit: "Zmazať", bCancel: "Storno" }, nav : { edittext: " ", edittitle: "Editovať vybraný riadok", addtext:" ", addtitle: "Pridať nový riadek", deltext: " ", deltitle: "Zmazať vybraný záznam ", searchtext: " ", searchtitle: "Nájsť záznamy", refreshtext: "", refreshtitle: "Obnoviť tabuľku", alertcap: "Varovanie", alerttext: "Prosím, vyberte riadok", viewtext: "", viewtitle: "Zobraziť vybraný riadok" }, col : { caption: "Zobrazit/Skrýť stĺpce", bSubmit: "Uložiť", bCancel: "Storno" }, errors : { errcap : "Chyba", nourl : "Nie je nastavená url", norecords: "Žiadne záznamy k spracovaniu", model : "Dĺžka colNames <> colModel!" }, formatter : { integer : {thousandsSeparator: " ", defaultValue: '0'}, number : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: '0.00'}, currency : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, prefix: "", suffix:"", defaultValue: '0.00'}, date : { dayNames: [ "Ne", "Po", "Ut", "St", "Št", "Pi", "So", "Nedela", "Pondelok", "Utorok", "Streda", "Štvrtok", "Piatek", "Sobota" ], monthNames: [ "Jan", "Feb", "Mar", "Apr", "Máj", "Jún", "Júl", "Aug", "Sep", "Okt", "Nov", "Dec", "Január", "Február", "Marec", "Apríl", "Máj", "Jún", "Júl", "August", "September", "Október", "November", "December" ], AmPm : ["do","od","DO","OD"], S: function (j) {return j < 11 || j > 13 ? ['st', 'nd', 'rd', 'th'][Math.min((j - 1) % 10, 3)] : 'th'}, srcformat: 'Y-m-d', newformat: 'd/m/Y', masks : { ISO8601Long:"Y-m-d H:i:s", ISO8601Short:"Y-m-d", ShortDate: "n/j/Y", LongDate: "l, F d, Y", FullDateTime: "l, F d, Y g:i:s A", MonthDay: "F d", ShortTime: "g:i A", LongTime: "g:i:s A", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "F, Y" }, reformatAfterEdit : false }, baseLinkUrl: '', showAction: '', target: '', checkbox : {disabled:true}, idName : 'id' } }; })(jQuery);
JavaScript
/* The below work is licensed under Creative Commons GNU LGPL License. Original work: License: http://creativecommons.org/licenses/LGPL/2.1/ Author: Stefan Goessner/2006 Web: http://goessner.net/ Modifications made: Version: 0.9-p5 Description: Restructured code, JSLint validated (no strict whitespaces), added handling of empty arrays, empty strings, and int/floats values. Author: Michael Schøler/2008-01-29 Web: http://michael.hinnerup.net/blog/2008/01/26/converting-json-to-xml-and-xml-to-json/ Description: json2xml added support to convert functions as CDATA so it will be easy to write characters that cause some problems when convert Author: Tony Tomov */ /*global alert */ var xmlJsonClass = { // Param "xml": Element or document DOM node. // Param "tab": Tab or indent string for pretty output formatting omit or use empty string "" to supress. // Returns: JSON string xml2json: function(xml, tab) { if (xml.nodeType === 9) { // document node xml = xml.documentElement; } var nws = this.removeWhite(xml); var obj = this.toObj(nws); var json = this.toJson(obj, xml.nodeName, "\t"); return "{\n" + tab + (tab ? json.replace(/\t/g, tab) : json.replace(/\t|\n/g, "")) + "\n}"; }, // Param "o": JavaScript object // Param "tab": tab or indent string for pretty output formatting omit or use empty string "" to supress. // Returns: XML string json2xml: function(o, tab) { var toXml = function(v, name, ind) { var xml = ""; var i, n; if (v instanceof Array) { if (v.length === 0) { xml += ind + "<"+name+">__EMPTY_ARRAY_</"+name+">\n"; } else { for (i = 0, n = v.length; i < n; i += 1) { var sXml = ind + toXml(v[i], name, ind+"\t") + "\n"; xml += sXml; } } } else if (typeof(v) === "object") { var hasChild = false; xml += ind + "<" + name; var m; for (m in v) if (v.hasOwnProperty(m)) { if (m.charAt(0) === "@") { xml += " " + m.substr(1) + "=\"" + v[m].toString() + "\""; } else { hasChild = true; } } xml += hasChild ? ">" : "/>"; if (hasChild) { for (m in v) if (v.hasOwnProperty(m)) { if (m === "#text") { xml += v[m]; } else if (m === "#cdata") { xml += "<![CDATA[" + v[m] + "]]>"; } else if (m.charAt(0) !== "@") { xml += toXml(v[m], m, ind+"\t"); } } xml += (xml.charAt(xml.length - 1) === "\n" ? ind : "") + "</" + name + ">"; } } else if (typeof(v) === "function") { xml += ind + "<" + name + ">" + "<![CDATA[" + v + "]]>" + "</" + name + ">"; } else { if (v.toString() === "\"\"" || v.toString().length === 0) { xml += ind + "<" + name + ">__EMPTY_STRING_</" + name + ">"; } else { xml += ind + "<" + name + ">" + v.toString() + "</" + name + ">"; } } return xml; }; var xml = ""; var m; for (m in o) if (o.hasOwnProperty(m)) { xml += toXml(o[m], m, ""); } return tab ? xml.replace(/\t/g, tab) : xml.replace(/\t|\n/g, ""); }, // Internal methods toObj: function(xml) { var o = {}; var FuncTest = /function/i; if (xml.nodeType === 1) { // element node .. if (xml.attributes.length) { // element with attributes .. var i; for (i = 0; i < xml.attributes.length; i += 1) { o["@" + xml.attributes[i].nodeName] = (xml.attributes[i].nodeValue || "").toString(); } } if (xml.firstChild) { // element has child nodes .. var textChild = 0, cdataChild = 0, hasElementChild = false; var n; for (n = xml.firstChild; n; n = n.nextSibling) { if (n.nodeType === 1) { hasElementChild = true; } else if (n.nodeType === 3 && n.nodeValue.match(/[^ \f\n\r\t\v]/)) { // non-whitespace text textChild += 1; } else if (n.nodeType === 4) { // cdata section node cdataChild += 1; } } if (hasElementChild) { if (textChild < 2 && cdataChild < 2) { // structured element with evtl. a single text or/and cdata node .. this.removeWhite(xml); for (n = xml.firstChild; n; n = n.nextSibling) { if (n.nodeType === 3) { // text node o["#text"] = this.escape(n.nodeValue); } else if (n.nodeType === 4) { // cdata node if (FuncTest.test(n.nodeValue)) { o[n.nodeName] = [o[n.nodeName], n.nodeValue]; } else { o["#cdata"] = this.escape(n.nodeValue); } } else if (o[n.nodeName]) { // multiple occurence of element .. if (o[n.nodeName] instanceof Array) { o[n.nodeName][o[n.nodeName].length] = this.toObj(n); } else { o[n.nodeName] = [o[n.nodeName], this.toObj(n)]; } } else { // first occurence of element .. o[n.nodeName] = this.toObj(n); } } } else { // mixed content if (!xml.attributes.length) { o = this.escape(this.innerXml(xml)); } else { o["#text"] = this.escape(this.innerXml(xml)); } } } else if (textChild) { // pure text if (!xml.attributes.length) { o = this.escape(this.innerXml(xml)); if (o === "__EMPTY_ARRAY_") { o = "[]"; } else if (o === "__EMPTY_STRING_") { o = ""; } } else { o["#text"] = this.escape(this.innerXml(xml)); } } else if (cdataChild) { // cdata if (cdataChild > 1) { o = this.escape(this.innerXml(xml)); } else { for (n = xml.firstChild; n; n = n.nextSibling) { if(FuncTest.test(xml.firstChild.nodeValue)) { o = xml.firstChild.nodeValue; break; } else { o["#cdata"] = this.escape(n.nodeValue); } } } } } if (!xml.attributes.length && !xml.firstChild) { o = null; } } else if (xml.nodeType === 9) { // document.node o = this.toObj(xml.documentElement); } else { alert("unhandled node type: " + xml.nodeType); } return o; }, toJson: function(o, name, ind) { var json = name ? ("\"" + name + "\"") : ""; if (o === "[]") { json += (name ? ":[]" : "[]"); } else if (o instanceof Array) { var n, i, ar=[]; for (i = 0, n = o.length; i < n; i += 1) { ar[i] = this.toJson(o[i], "", ind + "\t"); } json += (name ? ":[" : "[") + (ar.length > 1 ? ("\n" + ind + "\t" + ar.join(",\n" + ind + "\t") + "\n" + ind) : ar.join("")) + "]"; } else if (o === null) { json += (name && ":") + "null"; } else if (typeof(o) === "object") { var arr = []; var m; for (m in o) if (o.hasOwnProperty(m)) { arr[arr.length] = this.toJson(o[m], m, ind + "\t"); } json += (name ? ":{" : "{") + (arr.length > 1 ? ("\n" + ind + "\t" + arr.join(",\n" + ind + "\t") + "\n" + ind) : arr.join("")) + "}"; } else if (typeof(o) === "string") { var objRegExp = /(^-?\d+\.?\d*$)/; var FuncTest = /function/i; var os = o.toString(); if (objRegExp.test(os) || FuncTest.test(os) || os==="false" || os==="true") { // int or float json += (name && ":") + os; } else { json += (name && ":") + "\"" + o + "\""; } } else { json += (name && ":") + o.toString(); } return json; }, innerXml: function(node) { var s = ""; if ("innerHTML" in node) { s = node.innerHTML; } else { var asXml = function(n) { var s = "", i; if (n.nodeType === 1) { s += "<" + n.nodeName; for (i = 0; i < n.attributes.length; i += 1) { s += " " + n.attributes[i].nodeName + "=\"" + (n.attributes[i].nodeValue || "").toString() + "\""; } if (n.firstChild) { s += ">"; for (var c = n.firstChild; c; c = c.nextSibling) { s += asXml(c); } s += "</" + n.nodeName + ">"; } else { s += "/>"; } } else if (n.nodeType === 3) { s += n.nodeValue; } else if (n.nodeType === 4) { s += "<![CDATA[" + n.nodeValue + "]]>"; } return s; }; for (var c = node.firstChild; c; c = c.nextSibling) { s += asXml(c); } } return s; }, escape: function(txt) { return txt.replace(/[\\]/g, "\\\\").replace(/[\"]/g, '\\"').replace(/[\n]/g, '\\n').replace(/[\r]/g, '\\r'); }, removeWhite: function(e) { e.normalize(); var n; for (n = e.firstChild; n; ) { if (n.nodeType === 3) { // text node if (!n.nodeValue.match(/[^ \f\n\r\t\v]/)) { // pure whitespace text node var nxt = n.nextSibling; e.removeChild(n); n = nxt; } else { n = n.nextSibling; } } else if (n.nodeType === 1) { // element node this.removeWhite(n); n = n.nextSibling; } else { // any other node n = n.nextSibling; } } return e; } };
JavaScript
;(function($){ /* ** * jqGrid extension for cellediting Grid Data * Tony Tomov tony@trirand.com * http://trirand.com/blog/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl-2.0.html **/ /** * all events and options here are aded anonynous and not in the base grid * since the array is to big. Here is the order of execution. * From this point we use jQuery isFunction * formatCell * beforeEditCell, * onSelectCell (used only for noneditable cels) * afterEditCell, * beforeSaveCell, (called before validation of values if any) * beforeSubmitCell (if cellsubmit remote (ajax)) * afterSubmitCell(if cellsubmit remote (ajax)), * afterSaveCell, * errorCell, * serializeCellData - new * Options * cellsubmit (remote,clientArray) (added in grid options) * cellurl * ajaxCellOptions * */ $.jgrid.extend({ editCell : function (iRow,iCol, ed){ return this.each(function (){ var $t = this, nm, tmp,cc; if (!$t.grid || $t.p.cellEdit !== true) {return;} iCol = parseInt(iCol,10); // select the row that can be used for other methods $t.p.selrow = $t.rows[iRow].id; if (!$t.p.knv) {$($t).jqGrid("GridNav");} // check to see if we have already edited cell if ($t.p.savedRow.length>0) { // prevent second click on that field and enable selects if (ed===true ) { if(iRow == $t.p.iRow && iCol == $t.p.iCol){ return; } } // save the cell $($t).jqGrid("saveCell",$t.p.savedRow[0].id,$t.p.savedRow[0].ic); } else { window.setTimeout(function () { $("#"+$t.p.knv).attr("tabindex","-1").focus();},0); } nm = $t.p.colModel[iCol].name; if (nm=='subgrid' || nm=='cb' || nm=='rn') {return;} cc = $("td:eq("+iCol+")",$t.rows[iRow]); if ($t.p.colModel[iCol].editable===true && ed===true && !cc.hasClass("not-editable-cell")) { if(parseInt($t.p.iCol,10)>=0 && parseInt($t.p.iRow,10)>=0) { $("td:eq("+$t.p.iCol+")",$t.rows[$t.p.iRow]).removeClass("edit-cell ui-state-highlight"); $($t.rows[$t.p.iRow]).removeClass("selected-row ui-state-hover"); } $(cc).addClass("edit-cell ui-state-highlight"); $($t.rows[iRow]).addClass("selected-row ui-state-hover"); try { tmp = $.unformat(cc,{rowId: $t.rows[iRow].id, colModel:$t.p.colModel[iCol]},iCol); } catch (_) { tmp = $(cc).html(); } if($t.p.autoencode) { tmp = $.jgrid.htmlDecode(tmp); } if (!$t.p.colModel[iCol].edittype) {$t.p.colModel[iCol].edittype = "text";} $t.p.savedRow.push({id:iRow,ic:iCol,name:nm,v:tmp}); if($.isFunction($t.p.formatCell)) { var tmp2 = $t.p.formatCell.call($t, $t.rows[iRow].id,nm,tmp,iRow,iCol); if(tmp2 !== undefined ) {tmp = tmp2;} } var opt = $.extend({}, $t.p.colModel[iCol].editoptions || {} ,{id:iRow+"_"+nm,name:nm}); var elc = $.jgrid.createEl($t.p.colModel[iCol].edittype,opt,tmp,true,$.extend({},$.jgrid.ajaxOptions,$t.p.ajaxSelectOptions || {})); if ($.isFunction($t.p.beforeEditCell)) { $t.p.beforeEditCell.call($t, $t.rows[iRow].id,nm,tmp,iRow,iCol); } $(cc).html("").append(elc).attr("tabindex","0"); window.setTimeout(function () { $(elc).focus();},0); $("input, select, textarea",cc).bind("keydown",function(e) { if (e.keyCode === 27) { if($("input.hasDatepicker",cc).length >0) { if( $(".ui-datepicker").is(":hidden") ) { $($t).jqGrid("restoreCell",iRow,iCol); } else { $("input.hasDatepicker",cc).datepicker('hide'); } } else { $($t).jqGrid("restoreCell",iRow,iCol); } } //ESC if (e.keyCode === 13) {$($t).jqGrid("saveCell",iRow,iCol);}//Enter if (e.keyCode == 9) { if(!$t.grid.hDiv.loading ) { if (e.shiftKey) {$($t).jqGrid("prevCell",iRow,iCol);} //Shift TAb else {$($t).jqGrid("nextCell",iRow,iCol);} //Tab } else { return false; } } e.stopPropagation(); }); if ($.isFunction($t.p.afterEditCell)) { $t.p.afterEditCell.call($t, $t.rows[iRow].id,nm,tmp,iRow,iCol); } } else { if (parseInt($t.p.iCol,10)>=0 && parseInt($t.p.iRow,10)>=0) { $("td:eq("+$t.p.iCol+")",$t.rows[$t.p.iRow]).removeClass("edit-cell ui-state-highlight"); $($t.rows[$t.p.iRow]).removeClass("selected-row ui-state-hover"); } cc.addClass("edit-cell ui-state-highlight"); $($t.rows[iRow]).addClass("selected-row ui-state-hover"); if ($.isFunction($t.p.onSelectCell)) { tmp = cc.html().replace(/\&#160\;/ig,''); $t.p.onSelectCell.call($t, $t.rows[iRow].id,nm,tmp,iRow,iCol); } } $t.p.iCol = iCol; $t.p.iRow = iRow; }); }, saveCell : function (iRow, iCol){ return this.each(function(){ var $t= this, fr; if (!$t.grid || $t.p.cellEdit !== true) {return;} if ( $t.p.savedRow.length >= 1) {fr = 0;} else {fr=null;} if(fr !== null) { var cc = $("td:eq("+iCol+")",$t.rows[iRow]),v,v2, cm = $t.p.colModel[iCol], nm = cm.name, nmjq = $.jgrid.jqID(nm) ; switch (cm.edittype) { case "select": if(!cm.editoptions.multiple) { v = $("#"+iRow+"_"+nmjq+">option:selected",$t.rows[iRow]).val(); v2 = $("#"+iRow+"_"+nmjq+">option:selected",$t.rows[iRow]).text(); } else { var sel = $("#"+iRow+"_"+nmjq,$t.rows[iRow]), selectedText = []; v = $(sel).val(); if(v) { v.join(",");} else { v=""; } $("option:selected",sel).each( function(i,selected){ selectedText[i] = $(selected).text(); } ); v2 = selectedText.join(","); } if(cm.formatter) { v2 = v; } break; case "checkbox": var cbv = ["Yes","No"]; if(cm.editoptions){ cbv = cm.editoptions.value.split(":"); } v = $("#"+iRow+"_"+nmjq,$t.rows[iRow]).attr("checked") ? cbv[0] : cbv[1]; v2=v; break; case "password": case "text": case "textarea": case "button" : v = $("#"+iRow+"_"+nmjq,$t.rows[iRow]).val(); v2=v; break; case 'custom' : try { if(cm.editoptions && $.isFunction(cm.editoptions.custom_value)) { v = cm.editoptions.custom_value.call($t, $(".customelement",cc),'get'); if (v===undefined) { throw "e2";} else { v2=v; } } else { throw "e1"; } } catch (e) { if (e=="e1") { $.jgrid.info_dialog(jQuery.jgrid.errors.errcap,"function 'custom_value' "+$.jgrid.edit.msg.nodefined,jQuery.jgrid.edit.bClose); } if (e=="e2") { $.jgrid.info_dialog(jQuery.jgrid.errors.errcap,"function 'custom_value' "+$.jgrid.edit.msg.novalue,jQuery.jgrid.edit.bClose); } else {$.jgrid.info_dialog(jQuery.jgrid.errors.errcap,e.message,jQuery.jgrid.edit.bClose); } } break; } // The common approach is if nothing changed do not do anything if (v2 != $t.p.savedRow[fr].v){ if ($.isFunction($t.p.beforeSaveCell)) { var vv = $t.p.beforeSaveCell.call($t, $t.rows[iRow].id,nm, v, iRow,iCol); if (vv) {v = vv; v2=vv;} } var cv = $.jgrid.checkValues(v,iCol,$t); if(cv[0] === true) { var addpost = {}; if ($.isFunction($t.p.beforeSubmitCell)) { addpost = $t.p.beforeSubmitCell.call($t, $t.rows[iRow].id,nm, v, iRow,iCol); if (!addpost) {addpost={};} } if( $("input.hasDatepicker",cc).length >0) { $("input.hasDatepicker",cc).datepicker('hide'); } if ($t.p.cellsubmit == 'remote') { if ($t.p.cellurl) { var postdata = {}; if($t.p.autoencode) { v = $.jgrid.htmlEncode(v); } postdata[nm] = v; var idname,oper, opers; opers = $t.p.prmNames; idname = opers.id; oper = opers.oper; postdata[idname] = $t.rows[iRow].id; postdata[oper] = opers.editoper; postdata = $.extend(addpost,postdata); $("#lui_"+$t.p.id).show(); $t.grid.hDiv.loading = true; $.ajax( $.extend( { url: $t.p.cellurl, data :$.isFunction($t.p.serializeCellData) ? $t.p.serializeCellData.call($t, postdata) : postdata, type: "POST", complete: function (result, stat) { $("#lui_"+$t.p.id).hide(); $t.grid.hDiv.loading = false; if (stat == 'success') { if ($.isFunction($t.p.afterSubmitCell)) { var ret = $t.p.afterSubmitCell.call($t, result,postdata.id,nm,v,iRow,iCol); if(ret[0] === true) { $(cc).empty(); $($t).jqGrid("setCell",$t.rows[iRow].id, iCol, v2, false, false, true); $(cc).addClass("dirty-cell"); $($t.rows[iRow]).addClass("edited"); if ($.isFunction($t.p.afterSaveCell)) { $t.p.afterSaveCell.call($t, $t.rows[iRow].id,nm, v, iRow,iCol); } $t.p.savedRow.splice(0,1); } else { $.jgrid.info_dialog($.jgrid.errors.errcap,ret[1],$.jgrid.edit.bClose); $($t).jqGrid("restoreCell",iRow,iCol); } } else { $(cc).empty(); $($t).jqGrid("setCell",$t.rows[iRow].id, iCol, v2, false, false, true); $(cc).addClass("dirty-cell"); $($t.rows[iRow]).addClass("edited"); if ($.isFunction($t.p.afterSaveCell)) { $t.p.afterSaveCell.call($t, $t.rows[iRow].id,nm, v, iRow,iCol); } $t.p.savedRow.splice(0,1); } } }, error:function(res,stat) { $("#lui_"+$t.p.id).hide(); $t.grid.hDiv.loading = false; if ($.isFunction($t.p.errorCell)) { $t.p.errorCell.call($t, res,stat); $($t).jqGrid("restoreCell",iRow,iCol); } else { $.jgrid.info_dialog($.jgrid.errors.errcap,res.status+" : "+res.statusText+"<br/>"+stat,$.jgrid.edit.bClose); $($t).jqGrid("restoreCell",iRow,iCol); } } }, $.jgrid.ajaxOptions, $t.p.ajaxCellOptions || {})); } else { try { $.jgrid.info_dialog($.jgrid.errors.errcap,$.jgrid.errors.nourl,$.jgrid.edit.bClose); $($t).jqGrid("restoreCell",iRow,iCol); } catch (e) {} } } if ($t.p.cellsubmit == 'clientArray') { $(cc).empty(); $($t).jqGrid("setCell",$t.rows[iRow].id,iCol, v2, false, false, true); $(cc).addClass("dirty-cell"); $($t.rows[iRow]).addClass("edited"); if ($.isFunction($t.p.afterSaveCell)) { $t.p.afterSaveCell.call($t, $t.rows[iRow].id,nm, v, iRow,iCol); } $t.p.savedRow.splice(0,1); } } else { try { window.setTimeout(function(){$.jgrid.info_dialog($.jgrid.errors.errcap,v+" "+cv[1],$.jgrid.edit.bClose);},100); $($t).jqGrid("restoreCell",iRow,iCol); } catch (e) {} } } else { $($t).jqGrid("restoreCell",iRow,iCol); } } if ($.browser.opera) { $("#"+$t.p.knv).attr("tabindex","-1").focus(); } else { window.setTimeout(function () { $("#"+$t.p.knv).attr("tabindex","-1").focus();},0); } }); }, restoreCell : function(iRow, iCol) { return this.each(function(){ var $t= this, fr; if (!$t.grid || $t.p.cellEdit !== true ) {return;} if ( $t.p.savedRow.length >= 1) {fr = 0;} else {fr=null;} if(fr !== null) { var cc = $("td:eq("+iCol+")",$t.rows[iRow]); // datepicker fix if($.isFunction($.fn.datepicker)) { try { $("input.hasDatepicker",cc).datepicker('hide'); } catch (e) {} } $(cc).empty().attr("tabindex","-1"); $($t).jqGrid("setCell",$t.rows[iRow].id, iCol, $t.p.savedRow[fr].v, false, false, true); if ($.isFunction($t.p.afterRestoreCell)) { $t.p.afterRestoreCell.call($t, $t.rows[iRow].id, $t.p.savedRow[fr].v, iRow, iCol); } $t.p.savedRow.splice(0,1); } window.setTimeout(function () { $("#"+$t.p.knv).attr("tabindex","-1").focus();},0); }); }, nextCell : function (iRow,iCol) { return this.each(function (){ var $t = this, nCol=false; if (!$t.grid || $t.p.cellEdit !== true) {return;} // try to find next editable cell for (var i=iCol+1; i<$t.p.colModel.length; i++) { if ( $t.p.colModel[i].editable ===true) { nCol = i; break; } } if(nCol !== false) { $($t).jqGrid("editCell",iRow,nCol,true); } else { if ($t.p.savedRow.length >0) { $($t).jqGrid("saveCell",iRow,iCol); } } }); }, prevCell : function (iRow,iCol) { return this.each(function (){ var $t = this, nCol=false; if (!$t.grid || $t.p.cellEdit !== true) {return;} // try to find next editable cell for (var i=iCol-1; i>=0; i--) { if ( $t.p.colModel[i].editable ===true) { nCol = i; break; } } if(nCol !== false) { $($t).jqGrid("editCell",iRow,nCol,true); } else { if ($t.p.savedRow.length >0) { $($t).jqGrid("saveCell",iRow,iCol); } } }); }, GridNav : function() { return this.each(function () { var $t = this; if (!$t.grid || $t.p.cellEdit !== true ) {return;} // trick to process keydown on non input elements $t.p.knv = $t.p.id + "_kn"; var selection = $("<span style='width:0px;height:0px;background-color:black;' tabindex='0'><span tabindex='-1' style='width:0px;height:0px;background-color:grey' id='"+$t.p.knv+"'></span></span>"), i, kdir; $(selection).insertBefore($t.grid.cDiv); $("#"+$t.p.knv) .focus() .keydown(function (e){ kdir = e.keyCode; if($t.p.direction == "rtl") { if(kdir==37) { kdir = 39;} else if (kdir==39) { kdir = 37; } } switch (kdir) { case 38: if ($t.p.iRow-1 >0 ) { scrollGrid($t.p.iRow-1,$t.p.iCol,'vu'); $($t).jqGrid("editCell",$t.p.iRow-1,$t.p.iCol,false); } break; case 40 : if ($t.p.iRow+1 <= $t.rows.length-1) { scrollGrid($t.p.iRow+1,$t.p.iCol,'vd'); $($t).jqGrid("editCell",$t.p.iRow+1,$t.p.iCol,false); } break; case 37 : if ($t.p.iCol -1 >= 0) { i = findNextVisible($t.p.iCol-1,'lft'); scrollGrid($t.p.iRow, i,'h'); $($t).jqGrid("editCell",$t.p.iRow, i,false); } break; case 39 : if ($t.p.iCol +1 <= $t.p.colModel.length-1) { i = findNextVisible($t.p.iCol+1,'rgt'); scrollGrid($t.p.iRow,i,'h'); $($t).jqGrid("editCell",$t.p.iRow,i,false); } break; case 13: if (parseInt($t.p.iCol,10)>=0 && parseInt($t.p.iRow,10)>=0) { $($t).jqGrid("editCell",$t.p.iRow,$t.p.iCol,true); } break; } return false; }); function scrollGrid(iR, iC, tp){ if (tp.substr(0,1)=='v') { var ch = $($t.grid.bDiv)[0].clientHeight, st = $($t.grid.bDiv)[0].scrollTop, nROT = $t.rows[iR].offsetTop+$t.rows[iR].clientHeight, pROT = $t.rows[iR].offsetTop; if(tp == 'vd') { if(nROT >= ch) { $($t.grid.bDiv)[0].scrollTop = $($t.grid.bDiv)[0].scrollTop + $t.rows[iR].clientHeight; } } if(tp == 'vu'){ if (pROT < st ) { $($t.grid.bDiv)[0].scrollTop = $($t.grid.bDiv)[0].scrollTop - $t.rows[iR].clientHeight; } } } if(tp=='h') { var cw = $($t.grid.bDiv)[0].clientWidth, sl = $($t.grid.bDiv)[0].scrollLeft, nCOL = $t.rows[iR].cells[iC].offsetLeft+$t.rows[iR].cells[iC].clientWidth, pCOL = $t.rows[iR].cells[iC].offsetLeft; if(nCOL >= cw+parseInt(sl,10)) { $($t.grid.bDiv)[0].scrollLeft = $($t.grid.bDiv)[0].scrollLeft + $t.rows[iR].cells[iC].clientWidth; } else if (pCOL < sl) { $($t.grid.bDiv)[0].scrollLeft = $($t.grid.bDiv)[0].scrollLeft - $t.rows[iR].cells[iC].clientWidth; } } } function findNextVisible(iC,act){ var ind, i; if(act == 'lft') { ind = iC+1; for (i=iC;i>=0;i--){ if ($t.p.colModel[i].hidden !== true) { ind = i; break; } } } if(act == 'rgt') { ind = iC-1; for (i=iC; i<$t.p.colModel.length;i++){ if ($t.p.colModel[i].hidden !== true) { ind = i; break; } } } return ind; } }); }, getChangedCells : function (mthd) { var ret=[]; if (!mthd) {mthd='all';} this.each(function(){ var $t= this,nm; if (!$t.grid || $t.p.cellEdit !== true ) {return;} $($t.rows).each(function(j){ var res = {}; if ($(this).hasClass("edited")) { $('td',this).each( function(i) { nm = $t.p.colModel[i].name; if ( nm !== 'cb' && nm !== 'subgrid') { if (mthd=='dirty') { if ($(this).hasClass('dirty-cell')) { try { res[nm] = $.unformat(this,{rowId:$t.rows[j].id, colModel:$t.p.colModel[i]},i); } catch (e){ res[nm] = $.jgrid.htmlDecode($(this).html()); } } } else { try { res[nm] = $.unformat(this,{rowId:$t.rows[j].id,colModel:$t.p.colModel[i]},i); } catch (e) { res[nm] = $.jgrid.htmlDecode($(this).html()); } } } }); res.id = this.id; ret.push(res); } }); }); return ret; } /// end cell editing }); })(jQuery);
JavaScript
// This file should be used if you want to debug function jqGridInclude() { var pathtojsfiles = "plug_in/jqGrid/js/src/"; // need to be ajusted // set include to false if you do not want some modules to be included var modules = [ { include: false, incfile:'i18n/grid.locale-cn.js'}, // jqGrid translation { include: true, incfile:'grid.base.js'}, // jqGrid base { include: true, incfile:'grid.common.js'}, // jqGrid common for editing { include: true, incfile:'grid.formedit.js'}, // jqGrid Form editing { include: true, incfile:'grid.inlinedit.js'}, // jqGrid inline editing { include: true, incfile:'grid.celledit.js'}, // jqGrid cell editing { include: true, incfile:'grid.subgrid.js'}, //jqGrid subgrid { include: true, incfile:'grid.treegrid.js'}, //jqGrid treegrid { include: true, incfile:'grid.custom.js'}, //jqGrid custom { include: true, incfile:'grid.postext.js'}, //jqGrid postext { include: true, incfile:'grid.tbltogrid.js'}, //jqGrid table to grid { include: true, incfile:'grid.setcolumns.js'}, //jqGrid setcolumns { include: true, incfile:'grid.import.js'}, //jqGrid import { include: true, incfile:'grid.grouping.js'}, //jqGrid grouping { include: true, incfile:'jquery.fmatter.js'}, //jqGrid formater { include: true, incfile:'JsonXml.js'}, //xmljson utils { include: true, incfile:'jquery.searchFilter.js'} // search Plugin ]; var filename; for(var i=0;i<modules.length; i++) { if(modules[i].include === true) { filename = pathtojsfiles+modules[i].incfile; if(jQuery.browser.safari) { jQuery.ajax({url:filename,dataType:'script', async:false, cache: true}); } else { IncludeJavaScript(filename); } } } function IncludeJavaScript(jsFile) { var oHead = document.getElementsByTagName('head')[0]; var oScript = document.createElement('script'); oScript.type = 'text/javascript'; oScript.charset = 'utf-8'; oScript.src = jsFile; oHead.appendChild(oScript); }; }; jqGridInclude();
JavaScript
;(function($) { /* ** * jqGrid extension - Tree Grid * Tony Tomov tony@trirand.com * http://trirand.com/blog/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html **/ $.jgrid.extend({ setTreeNode : function(rd, row){ return this.each(function(){ var $t = this; if( !$t.grid || !$t.p.treeGrid ) { return; } var expCol = $t.p.expColInd, expanded = $t.p.treeReader.expanded_field, isLeaf = $t.p.treeReader.leaf_field, level = $t.p.treeReader.level_field, loaded = $t.p.treeReader.loaded; row.level = rd[level]; if($t.p.treeGridModel == 'nested') { var lft = rd[$t.p.treeReader.left_field], rgt = rd[$t.p.treeReader.right_field]; if(!rd[isLeaf]) { // NS Model rd[isLeaf] = (parseInt(rgt,10) === parseInt(lft,10)+1) ? 'true' : 'false'; } } else { //row.parent_id = rd[$t.p.treeReader.parent_id_field]; } var curLevel = parseInt(rd[level],10), ident,lftpos; if($t.p.tree_root_level === 0) { ident = curLevel+1; lftpos = curLevel; } else { ident = curLevel; lftpos = curLevel -1; } var twrap = "<div class='tree-wrap tree-wrap-"+$t.p.direction+"' style='width:"+(ident*18)+"px;'>"; twrap += "<div style='"+($t.p.direction=="rtl" ? "right:" : "left:")+(lftpos*18)+"px;' class='ui-icon "; if(rd[loaded] != undefined) { if(rd[loaded]=="true" || rd[loaded]===true) { rd[loaded] = true; } else { rd[loaded] = false; } } if(rd[isLeaf] == "true" || rd[isLeaf] === true) { twrap += $t.p.treeIcons.leaf+" tree-leaf'"; rd[isLeaf] = true; rd[expanded] = false; } else { if(rd[expanded] == "true" || rd[expanded] === true) { twrap += $t.p.treeIcons.minus+" tree-minus treeclick'"; rd[expanded] = true; } else { twrap += $t.p.treeIcons.plus+" tree-plus treeclick'"; rd[expanded] = false; } rd[isLeaf] = false; } twrap += "</div></div>"; if(!$t.p.loadonce) { rd[$t.p.localReader.id] = row.id; $t.p.data.push(rd); $t.p._index[row.id]=$t.p.data.length-1; } if(parseInt(rd[level],10) !== parseInt($t.p.tree_root_level,10)) { if(!$($t).jqGrid("isVisibleNode",rd)){ $(row).css("display","none"); } } $("td:eq("+expCol+")",row).wrapInner("<span></span>").prepend(twrap); $(".treeclick",row).bind("click",function(e){ var target = e.target || e.srcElement, ind2 =$(target,$t.rows).closest("tr.jqgrow")[0].id, pos = $t.p._index[ind2], isLeaf = $t.p.treeReader.leaf_field, expanded = $t.p.treeReader.expanded_field; if(!$t.p.data[pos][isLeaf]){ if($t.p.data[pos][expanded]){ $($t).jqGrid("collapseRow",$t.p.data[pos]); $($t).jqGrid("collapseNode",$t.p.data[pos]); } else { $($t).jqGrid("expandRow",$t.p.data[pos]); $($t).jqGrid("expandNode",$t.p.data[pos]); } } return false; }); if($t.p.ExpandColClick === true) { $("span", row).css("cursor","pointer").bind("click",function(e){ var target = e.target || e.srcElement, ind2 =$(target,$t.rows).closest("tr.jqgrow")[0].id, pos = $t.p._index[ind2], isLeaf = $t.p.treeReader.leaf_field, expanded = $t.p.treeReader.expanded_field; if(!$t.p.data[pos][isLeaf]){ if($t.p.data[pos][expanded]){ $($t).jqGrid("collapseRow",$t.p.data[pos]); $($t).jqGrid("collapseNode",$t.p.data[pos]); } else { $($t).jqGrid("expandRow",$t.p.data[pos]); $($t).jqGrid("expandNode",$t.p.data[pos]); } } $($t).jqGrid("setSelection",ind2); return false; }); } }); }, setTreeGrid : function() { return this.each(function (){ var $t = this, i=0, pico; if(!$t.p.treeGrid) { return; } if(!$t.p.treedatatype ) { $.extend($t.p,{treedatatype: $t.p.datatype}); } $t.p.subGrid = false; $t.p.altRows =false; $t.p.pgbuttons = false; $t.p.pginput = false; $t.p.multiselect = false; $t.p.rowList = []; pico = 'ui-icon-triangle-1-' + ($t.p.direction=="rtl" ? 'w' : 'e'); $t.p.treeIcons = $.extend({plus:pico,minus:'ui-icon-triangle-1-s',leaf:'ui-icon-radio-off'},$t.p.treeIcons || {}); if($t.p.treeGridModel == 'nested') { $t.p.treeReader = $.extend({ level_field: "level", left_field:"lft", right_field: "rgt", leaf_field: "isLeaf", expanded_field: "expanded", loaded: "loaded" },$t.p.treeReader); } else if($t.p.treeGridModel == 'adjacency') { $t.p.treeReader = $.extend({ level_field: "level", parent_id_field: "parent", leaf_field: "isLeaf", expanded_field: "expanded", loaded: "loaded" },$t.p.treeReader ); } for (var key in $t.p.colModel){ if($t.p.colModel.hasOwnProperty(key)) { if($t.p.colModel[key].name == $t.p.ExpandColumn) { $t.p.expColInd = i; break; } i++; } } if(!$t.p.expColInd) { $t.p.expColInd = 0; } $.each($t.p.treeReader,function(i,n){ if(n){ $t.p.colNames.push(n); $t.p.colModel.push({name:n,width:1,hidden:true,sortable:false,resizable:false,hidedlg:true,editable:true,search:false}); } }); }); }, expandRow: function (record){ this.each(function(){ var $t = this; if(!$t.grid || !$t.p.treeGrid) { return; } var childern = $($t).jqGrid("getNodeChildren",record), //if ($($t).jqGrid("isVisibleNode",record)) { expanded = $t.p.treeReader.expanded_field; $(childern).each(function(i){ var id = $.jgrid.getAccessor(this,$t.p.localReader.id); $("#"+id,$t.grid.bDiv).css("display",""); if(this[expanded]) { $($t).jqGrid("expandRow",this); } }); //} }); }, collapseRow : function (record) { this.each(function(){ var $t = this; if(!$t.grid || !$t.p.treeGrid) { return; } var childern = $($t).jqGrid("getNodeChildren",record), expanded = $t.p.treeReader.expanded_field; $(childern).each(function(i){ var id = $.jgrid.getAccessor(this,$t.p.localReader.id); $("#"+id,$t.grid.bDiv).css("display","none"); if(this[expanded]){ $($t).jqGrid("collapseRow",this); } }); }); }, // NS ,adjacency models getRootNodes : function() { var result = []; this.each(function(){ var $t = this; if(!$t.grid || !$t.p.treeGrid) { return; } switch ($t.p.treeGridModel) { case 'nested' : var level = $t.p.treeReader.level_field; $($t.p.data).each(function(i){ if(parseInt(this[level],10) === parseInt($t.p.tree_root_level,10)) { result.push(this); } }); break; case 'adjacency' : var parent_id = $t.p.treeReader.parent_id_field; $($t.p.data).each(function(i){ if(this[parent_id] === null || String(this[parent_id]).toLowerCase() == "null") { result.push(this); } }); break; } }); return result; }, getNodeDepth : function(rc) { var ret = null; this.each(function(){ if(!this.grid || !this.p.treeGrid) { return; } var $t = this; switch ($t.p.treeGridModel) { case 'nested' : var level = $t.p.treeReader.level_field; ret = parseInt(rc[level],10) - parseInt($t.p.tree_root_level,10); break; case 'adjacency' : ret = $($t).jqGrid("getNodeAncestors",rc).length; break; } }); return ret; }, getNodeParent : function(rc) { var result = null; this.each(function(){ var $t = this; if(!$t.grid || !$t.p.treeGrid) { return; } switch ($t.p.treeGridModel) { case 'nested' : var lftc = $t.p.treeReader.left_field, rgtc = $t.p.treeReader.right_field, levelc = $t.p.treeReader.level_field, lft = parseInt(rc[lftc],10), rgt = parseInt(rc[rgtc],10), level = parseInt(rc[levelc],10); $(this.p.data).each(function(){ if(parseInt(this[levelc],10) === level-1 && parseInt(this[lftc],10) < lft && parseInt(this[rgtc],10) > rgt) { result = this; return false; } }); break; case 'adjacency' : var parent_id = $t.p.treeReader.parent_id_field, dtid = $t.p.localReader.id; $(this.p.data).each(function(i,val){ if(this[dtid] == rc[parent_id] ) { result = this; return false; } }); break; } }); return result; }, getNodeChildren : function(rc) { var result = []; this.each(function(){ var $t = this; if(!$t.grid || !$t.p.treeGrid) { return; } switch ($t.p.treeGridModel) { case 'nested' : var lftc = $t.p.treeReader.left_field, rgtc = $t.p.treeReader.right_field, levelc = $t.p.treeReader.level_field, lft = parseInt(rc[lftc],10), rgt = parseInt(rc[rgtc],10), level = parseInt(rc[levelc],10); $(this.p.data).each(function(i){ if(parseInt(this[levelc],10) === level+1 && parseInt(this[lftc],10) > lft && parseInt(this[rgtc],10) < rgt) { result.push(this); } }); break; case 'adjacency' : var parent_id = $t.p.treeReader.parent_id_field, dtid = $t.p.localReader.id; $(this.p.data).each(function(i,val){ if(this[parent_id] == rc[dtid]) { result.push(this); } }); break; } }); return result; }, getFullTreeNode : function(rc) { var result = []; this.each(function(){ var $t = this, len; if(!$t.grid || !$t.p.treeGrid) { return; } switch ($t.p.treeGridModel) { case 'nested' : var lftc = $t.p.treeReader.left_field, rgtc = $t.p.treeReader.right_field, levelc = $t.p.treeReader.level_field, lft = parseInt(rc[lftc],10), rgt = parseInt(rc[rgtc],10), level = parseInt(rc[levelc],10); $(this.p.data).each(function(i){ if(parseInt(this[levelc],10) >= level && parseInt(this[lftc],10) >= lft && parseInt(this[lftc],10) <= rgt) { result.push(this); } }); break; case 'adjacency' : result.push(rc); var parent_id = $t.p.treeReader.parent_id_field, dtid = $t.p.localReader.id; $(this.p.data).each(function(i){ len = result.length; for (i = 0; i < len; i++) { if (result[i][dtid] == this[parent_id]) { result.push(this); break; } } }); break; } }); return result; }, // End NS, adjacency Model getNodeAncestors : function(rc) { var ancestors = []; this.each(function(){ if(!this.grid || !this.p.treeGrid) { return; } var parent = $(this).jqGrid("getNodeParent",rc); while (parent) { ancestors.push(parent); parent = $(this).jqGrid("getNodeParent",parent); } }); return ancestors; }, isVisibleNode : function(rc) { var result = true; this.each(function(){ var $t = this; if(!$t.grid || !$t.p.treeGrid) { return; } var ancestors = $($t).jqGrid("getNodeAncestors",rc), expanded = $t.p.treeReader.expanded_field; $(ancestors).each(function(){ result = result && this[expanded]; if(!result) {return false;} }); }); return result; }, isNodeLoaded : function(rc) { var result; this.each(function(){ var $t = this; if(!$t.grid || !$t.p.treeGrid) { return; } var isLeaf = $t.p.treeReader.leaf_field; if(rc.loaded !== undefined) { result = rc.loaded; } else if( rc[isLeaf] || $($t).jqGrid("getNodeChildren",rc).length > 0){ result = true; } else { result = false; } }); return result; }, expandNode : function(rc) { return this.each(function(){ if(!this.grid || !this.p.treeGrid) { return; } var expanded = this.p.treeReader.expanded_field; if(!rc[expanded]) { var id = $.jgrid.getAccessor(rc,this.p.localReader.id); var rc1 = $("#"+id,this.grid.bDiv)[0]; var position = this.p._index[id]; if( $(this).jqGrid("isNodeLoaded",this.p.data[position]) ) { rc[expanded] = true; $("div.treeclick",rc1).removeClass(this.p.treeIcons.plus+" tree-plus").addClass(this.p.treeIcons.minus+" tree-minus"); } else { rc[expanded] = true; $("div.treeclick",rc1).removeClass(this.p.treeIcons.plus+" tree-plus").addClass(this.p.treeIcons.minus+" tree-minus"); this.p.treeANode = rc1.rowIndex; this.p.datatype = this.p.treedatatype; if(this.p.treeGridModel == 'nested') { $(this).jqGrid("setGridParam",{postData:{nodeid:id,n_left:rc.lft,n_right:rc.rgt,n_level:rc.level}}); } else { $(this).jqGrid("setGridParam",{postData:{nodeid:id,parentid:rc.parent_id,n_level:rc.level}}); } $(this).trigger("reloadGrid"); if(this.p.treeGridModel == 'nested') { $(this).jqGrid("setGridParam",{postData:{nodeid:'',n_left:'',n_right:'',n_level:''}}); } else { $(this).jqGrid("setGridParam",{postData:{nodeid:'',parentid:'',n_level:''}}); } } } }); }, collapseNode : function(rc) { return this.each(function(){ if(!this.grid || !this.p.treeGrid) { return; } if(rc.expanded) { rc.expanded = false; var id = $.jgrid.getAccessor(rc,this.p.localReader.id); var rc1 = $("#"+id,this.grid.bDiv)[0]; $("div.treeclick",rc1).removeClass(this.p.treeIcons.minus+" tree-minus").addClass(this.p.treeIcons.plus+" tree-plus"); } }); }, SortTree : function( sortname, newDir, st, datefmt) { return this.each(function(){ if(!this.grid || !this.p.treeGrid) { return; } var i, len, rec, records = [], $t = this, query, roots, rt = $(this).jqGrid("getRootNodes"); // Sorting roots query = $.jgrid.from(rt); query.orderBy(sortname,newDir,st, datefmt); roots = query.select(); // Sorting children for (i = 0, len = roots.length; i < len; i++) { rec = roots[i]; records.push(rec); $(this).jqGrid("collectChildrenSortTree",records, rec, sortname, newDir,st, datefmt); } $.each(records, function(index, row) { var id = $.jgrid.getAccessor(this,$t.p.localReader.id); $('#'+$t.p.id+ ' tbody tr:eq('+index+')').after($('tr#'+id,$t.grid.bDiv)); }); query = null; roots=null;records=null; }); }, collectChildrenSortTree : function(records, rec, sortname, newDir,st, datefmt) { return this.each(function(){ if(!this.grid || !this.p.treeGrid) { return; } var i, len, child, ch, query, children; ch = $(this).jqGrid("getNodeChildren",rec); query = $.jgrid.from(ch); query.orderBy(sortname, newDir, st, datefmt); children = query.select(); for (i = 0, len = children.length; i < len; i++) { child = children[i]; records.push(child); $(this).jqGrid("collectChildrenSortTree",records, child, sortname, newDir, st, datefmt); } }); }, // experimental setTreeRow : function(rowid, data) { var success=false; this.each(function(){ var t = this; if(!t.grid || !t.p.treeGrid) { return; } success = $(t).jqGrid("setRowData",rowid,data); }); return success; }, delTreeNode : function (rowid) { return this.each(function () { var $t = this; if(!$t.grid || !$t.p.treeGrid) { return; } var rc = $($t).jqGrid("getInd",rowid,true); if (rc) { var dr = $($t).jqGrid("getNodeChildren",rc); if(dr.length>0){ for (var i=0;i<dr.length;i++){ $($t).jqGrid("delRowData",dr[i].id); } } $($t).jqGrid("delRowData",rc.id); } }); } }); })(jQuery);
JavaScript