Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (function ($) {
- Drupal.behaviors.schoeller_pricing = {
- attach: function(context) {
- var $placeholder = $('.price-range-replaceholder', context);
- if (!$placeholder.length) {
- return;
- }
- $placeholder.closest('.node').find('input[name="quantity"]').bind('keyup', this.quantity_update_handler);
- },
- quantity_update_handler: function() {
- var $this = $(this),
- quantity = parseInt($this.val(), 10);
- $placeholder = $this.closest('.node').find('.price-range-replaceholder'),
- placeholderText = $placeholder.text(),
- ranges = $placeholder.data('ranges'),
- pps = $placeholder.data('pps'),
- currency = $placeholder.data('currency'),
- before = placeholderText.search(/[0-9,.]+/) !== 0,
- wasComma = false,
- amount = 0;
- if (typeof pps == "undefined") {
- currency = placeholderText.match(/[^0-9,.]+/)[0];
- pps = placeholderText.match(/[0-9,.]+/)[0];
- $placeholder.data({'currency': currency, 'pps': pps});
- }
- // if it's a comma number, replace all periods with commas and vice versa
- if (pps.charAt(pps.length - 3) == ',') {
- wasComma = true;
- pps = pps.replace(/[.]/g, '§').replace(/[,]/g, '.').replace(/[§]/g, ',');
- }
- ranges.amount = parseFloat(pps, 10) - (ranges.unit / 100);
- if (quantity < ranges.ranges[0]) {
- amount = ranges.amount;
- }
- else {
- // loop through ranges in reverse order, break as soon as we got a match
- for (var i = ranges.ranges.length; i > 0; i--) {
- if (ranges.ranges[i-1] <= quantity) {
- // amount - percentage
- amount = (ranges.amount - (ranges.amount * (ranges.percentages[i-1] / 100)));
- break;
- }
- }
- }
- // Done doing maths, re-add unit price and make into a string
- amount = ((ranges.unit / 100) + amount).toString();
- // Add trailing 0s if necessary
- var pos = amount.search(/[.]/);
- // No decimals
- if (pos === -1) {
- amount = amount + '.00';
- }
- // 1 decimal
- if (pos === (amount.length - 2)) {
- amount = amount + '0';
- }
- // if it was a comma number, turn it back into one
- if (wasComma) {
- amount.replace(/[.]/g, '§').replace(/[,]/g, '.').replace(/[§]/g, ',');
- }
- // Re-add the currency symbol
- if (before) {
- amount = currency + amount;
- }
- else {
- amount = amount + currency;
- }
- // @TODO: thousands delimiter?
- $placeholder.text(amount);
- }
- }
- })(jQuery);
Add Comment
Please, Sign In to add comment