diff --git a/app/code/Magento/Authorizenet/view/adminhtml/web/js/direct-post.js b/app/code/Magento/Authorizenet/view/adminhtml/web/js/direct-post.js index 11da861ea5b85..e43341ca2b337 100644 --- a/app/code/Magento/Authorizenet/view/adminhtml/web/js/direct-post.js +++ b/app/code/Magento/Authorizenet/view/adminhtml/web/js/direct-post.js @@ -6,322 +6,347 @@ (function (factory) { if (typeof define === 'function' && define.amd) { define([ - "jquery", - "mage/backend/validation", - "prototype" + 'jquery', + 'mage/backend/validation', + 'prototype' ], factory); } else { factory(jQuery); } }(function (jQuery) { -window.directPost = Class.create(); -directPost.prototype = { - initialize : function(methodCode, iframeId, controller, orderSaveUrl, cgiUrl, nativeAction) { - var prepare = function (event, method) { - if (method === 'authorizenet_directpost') { - this.preparePayment(); - } else { - jQuery('#edit_form') - .off('submitOrder.authorizenet'); + window.directPost = Class.create(); + directPost.prototype = { + initialize: function (methodCode, iframeId, controller, orderSaveUrl, cgiUrl, nativeAction) { + var prepare = function (event, method) { + if (method === 'authorizenet_directpost') { + this.preparePayment(); + } else { + jQuery('#edit_form') + .off('submitOrder.authorizenet'); + } + }; + + this.iframeId = iframeId; + this.controller = controller; + this.orderSaveUrl = orderSaveUrl; + this.nativeAction = nativeAction; + this.cgiUrl = cgiUrl; + this.code = methodCode; + this.inputs = ['cc_type', 'cc_number', 'expiration', 'expiration_yr', 'cc_cid']; + this.headers = []; + this.isValid = true; + this.paymentRequestSent = false; + this.orderIncrementId = false; + this.successUrl = false; + this.hasError = false; + this.tmpForm = false; + + this.onLoadIframe = this.loadIframe.bindAsEventListener(this); + this.onLoadOrderIframe = this.loadOrderIframe.bindAsEventListener(this); + this.onSubmitAdminOrder = this.submitAdminOrder.bindAsEventListener(this); + + jQuery('#edit_form').on('changePaymentMethod', prepare.bind(this)); + + jQuery('#edit_form').trigger( + 'changePaymentMethod', + [ + jQuery('#edit_form').find(':radio[name="payment[method]"]:checked').val() + ] + ); + }, + + validate: function () { + this.isValid = true; + this.inputs.each(function (elemIndex) { + if ($(this.code + '_' + elemIndex)) { + if (!jQuery.validator.validateElement($(this.code + '_' + elemIndex))) { + this.isValid = false; + } + } + }, this); + + return this.isValid; + }, + + changeInputOptions: function (param, value) { + this.inputs.each(function (elemIndex) { + if ($(this.code + '_' + elemIndex)) { + $(this.code + '_' + elemIndex).writeAttribute(param, value); + } + }, this); + }, + + preparePayment: function () { + this.changeInputOptions('autocomplete', 'off'); + jQuery('#edit_form') + .off('submitOrder') + .on('submitOrder.authorizenet', this.submitAdminOrder.bind(this)); + + if ($(this.iframeId)) { + // Temporary solution will be removed after refactoring Authorize.Net (sales) functionality + jQuery('.scalable.save:not(disabled)').removeAttr('onclick'); + jQuery(document).off('click.directPost'); + jQuery(document).on( + 'click.directPost', + '.scalable.save:not(disabled)', + jQuery.proxy(this.onSubmitAdminOrder, this) + ); + $('order-' + this.iframeId).observe('load', this.onLoadOrderIframe); + $(this.iframeId).observe('load', this.onLoadIframe); } - }; - this.iframeId = iframeId; - this.controller = controller; - this.orderSaveUrl = orderSaveUrl; - this.nativeAction = nativeAction; - this.cgiUrl = cgiUrl; - this.code = methodCode; - this.inputs = ['cc_type', 'cc_number', 'expiration', 'expiration_yr', 'cc_cid']; - this.headers = []; - this.isValid = true; - this.paymentRequestSent = false; - this.orderIncrementId = false; - this.successUrl = false; - this.hasError = false; - this.tmpForm = false; - - this.onLoadIframe = this.loadIframe.bindAsEventListener(this); - this.onLoadOrderIframe = this.loadOrderIframe.bindAsEventListener(this); - this.onSubmitAdminOrder = this.submitAdminOrder.bindAsEventListener(this); - - jQuery('#edit_form').on('changePaymentMethod', prepare.bind(this)); - - jQuery('#edit_form').trigger( - 'changePaymentMethod', - [ - jQuery('#edit_form').find(':radio[name="payment[method]"]:checked').val() - ] - ); - }, - - validate : function() { - this.isValid = true; - this.inputs.each(function(elemIndex) { - if ($(this.code + '_' + elemIndex)) { - if (!jQuery.validator.validateElement($(this.code + '_' + elemIndex))) { - this.isValid = false; + }, + + loadIframe: function () { + if (this.paymentRequestSent) { + if (!this.orderRequestSent) { + this.paymentRequestSent = false; + + if (!this.hasError) { + this.returnQuote(); + } else { + this.changeInputOptions('disabled', false); + jQuery('body').trigger('processStop'); + enableElements('save'); + } + } + + if (this.tmpForm) { + document.body.removeChild(this.tmpForm); } } - }, this); + }, - return this.isValid; - }, + loadOrderIframe: function () { + if (this.orderRequestSent) { + $(this.iframeId).hide(); + var data = $('order-' + this.iframeId).contentWindow.document.body.getElementsByTagName('pre')[0].innerHTML; - changeInputOptions : function(param, value) { - this.inputs.each(function(elemIndex) { - if ($(this.code + '_' + elemIndex)) { - $(this.code + '_' + elemIndex).writeAttribute(param, value); + this.saveAdminOrderSuccess(data); + this.orderRequestSent = false; } - }, this); - }, - - preparePayment : function() { - this.changeInputOptions('autocomplete', 'off'); - jQuery('#edit_form') - .off('submitOrder') - .on('submitOrder.authorizenet', this.submitAdminOrder.bind(this)); - if ($(this.iframeId)) { - // Temporary solution will be removed after refactoring Authorize.Net (sales) functionality - jQuery('.scalable.save:not(disabled)').removeAttr('onclick'); - jQuery(document).off('click.directPost'); - jQuery(document).on( - 'click.directPost', - '.scalable.save:not(disabled)', - jQuery.proxy(this.onSubmitAdminOrder, this) - ); - $('order-' + this.iframeId).observe('load', this.onLoadOrderIframe); - $(this.iframeId).observe('load', this.onLoadIframe); - } - }, - - loadIframe : function() { - if (this.paymentRequestSent) { - if (!this.orderRequestSent) { - this.paymentRequestSent = false; - if (!this.hasError) { - this.returnQuote(); - } else { + }, + + showError: function (msg) { + this.hasError = true; + + if (this.controller == 'onepage') { + $(this.iframeId).hide(); + this.resetLoadWaiting(); + } + alert(msg); + }, + + returnQuote: function () { + var url = this.orderSaveUrl.replace('place', 'returnQuote'); + + new Ajax.Request(url, { + onSuccess: function (transport) { + try { + response = transport.responseText.evalJSON(true); + } catch (e) { + response = {}; + } + + if (response.error_message) { + alert(response.error_message); + } + $(this.iframeId).show(); this.changeInputOptions('disabled', false); jQuery('body').trigger('processStop'); enableElements('save'); + }.bind(this) + }); + }, + + setLoadWaiting: function () { + this.headers.each(function (header) { + header.removeClassName('allow'); + }); + checkout.setLoadWaiting('review'); + }, + + resetLoadWaiting: function () { + this.headers.each(function (header) { + header.addClassName('allow'); + }); + checkout.setLoadWaiting(false); + }, + + submitAdminOrder: function () { + // Temporary solution will be removed after refactoring Authorize.Net (sales) functionality + var editForm = jQuery('#edit_form'); + + if (editForm.valid()) { + // Temporary solution will be removed after refactoring Authorize.Net (sales) functionality + paymentMethodEl = editForm.find(':radio[name="payment[method]"]:checked'); + this.hasError = false; + + if (paymentMethodEl.val() == this.code) { + jQuery('body').trigger('processStart'); + setLoaderPosition(); + this.changeInputOptions('disabled', 'disabled'); + this.paymentRequestSent = true; + this.orderRequestSent = true; + // Temporary solutions will be removed after refactoring Authorize.Net (sales) functionality + editForm.attr('action', this.orderSaveUrl); + editForm.attr('target', + jQuery('#order-' + this.iframeId).attr('name')); + editForm.append(this.createHiddenElement('controller', this.controller)); + disableElements('save'); + // Temporary solutions will be removed after refactoring Authorize.Net (sales) functionality + order._realSubmit(); + } else { + editForm.attr('action', this.nativeAction); + editForm.attr('target', '_top'); + disableElements('save'); + // Temporary solutions will be removed after refactoring Authorize.Net (sales) functionality + order._realSubmit(); } } - if (this.tmpForm) { - document.body.removeChild(this.tmpForm); + }, + + recollectQuote: function () { + var area = ['sidebar', 'items', 'shipping_method', 'billing_method', 'totals', 'giftmessage']; + + area = order.prepareArea(area); + var url = order.loadBaseUrl + 'block/' + area; + var info = $('order-items_grid').select('input', 'select', 'textarea'); + var data = {}; + + for (var i = 0; i < info.length; i++) { + if (!info[i].disabled && (info[i].type != 'checkbox' || info[i].checked)) { + data[info[i].name] = info[i].getValue(); + } } - } - }, - - loadOrderIframe : function() { - if (this.orderRequestSent) { - $(this.iframeId).hide(); - var data = $('order-' + this.iframeId).contentWindow.document.body.getElementsByTagName('pre')[0].innerHTML; - this.saveAdminOrderSuccess(data); - this.orderRequestSent = false; - } - }, + data.reset_shipping = true; + data.update_items = true; - showError : function(msg) { - this.hasError = true; - if (this.controller == 'onepage') { - $(this.iframeId).hide(); - this.resetLoadWaiting(); - } - alert(msg); - }, - - returnQuote : function() { - var url = this.orderSaveUrl.replace('place', 'returnQuote'); - new Ajax.Request(url, { - onSuccess : function(transport) { - try { - response = transport.responseText.evalJSON(true); - } catch (e) { - response = {}; + if ($('coupons:code') && $F('coupons:code')) { + data['order[coupon][code]'] = $F('coupons:code'); + } + data.json = true; + new Ajax.Request(url, { + parameters: data, + loaderArea: 'html-body', + onSuccess: function (transport) { + jQuery('#edit_form').submit(); } - if (response.error_message) { - alert(response.error_message); + }); + + }, + + saveAdminOrderSuccess: function (data) { + try { + response = data.evalJSON(true); + } catch (e) { + response = {}; + } + + if (response.directpost) { + this.orderIncrementId = response.directpost.fields.x_invoice_num; + var paymentData = {}; + + for (var key in response.directpost.fields) { + paymentData[key] = response.directpost.fields[key]; } - $(this.iframeId).show(); - this.changeInputOptions('disabled', false); - jQuery('body').trigger('processStop'); - enableElements('save'); - }.bind(this) - }); - }, - - setLoadWaiting : function() { - this.headers.each(function(header) { - header.removeClassName('allow'); - }); - checkout.setLoadWaiting('review'); - }, - - resetLoadWaiting : function() { - this.headers.each(function(header) { - header.addClassName('allow'); - }); - checkout.setLoadWaiting(false); - }, - - submitAdminOrder : function() { - // Temporary solution will be removed after refactoring Authorize.Net (sales) functionality - var editForm = jQuery('#edit_form'); - if (editForm.valid()) { - // Temporary solution will be removed after refactoring Authorize.Net (sales) functionality - paymentMethodEl = editForm.find(':radio[name="payment[method]"]:checked'); - this.hasError = false; - if (paymentMethodEl.val() == this.code) { - jQuery('body').trigger('processStart'); - setLoaderPosition(); - this.changeInputOptions('disabled', 'disabled'); - this.paymentRequestSent = true; - this.orderRequestSent = true; - // Temporary solutions will be removed after refactoring Authorize.Net (sales) functionality - editForm.attr('action', this.orderSaveUrl); - editForm.attr('target', - jQuery('#order-' + this.iframeId).attr('name')); - editForm.append(this.createHiddenElement('controller', this.controller)); - disableElements('save'); - // Temporary solutions will be removed after refactoring Authorize.Net (sales) functionality - order._realSubmit(); + var preparedData = this.preparePaymentRequest(paymentData); + + this.sendPaymentRequest(preparedData); } else { - editForm.attr('action', this.nativeAction); - editForm.attr('target', '_top'); - disableElements('save'); - // Temporary solutions will be removed after refactoring Authorize.Net (sales) functionality - order._realSubmit(); + if (response.redirect) { + window.location = response.redirect; + } + + if (response.error_messages) { + var msg = response.error_messages; + + if (typeof msg == 'object') { + msg = msg.join('\n'); + } + + if (msg) { + alert(msg); + } + } } - } - }, - - recollectQuote : function() { - var area = [ 'sidebar', 'items', 'shipping_method', 'billing_method', 'totals', 'giftmessage' ]; - area = order.prepareArea(area); - var url = order.loadBaseUrl + 'block/' + area; - var info = $('order-items_grid').select('input', 'select', 'textarea'); - var data = {}; - for ( var i = 0; i < info.length; i++) { - if (!info[i].disabled && (info[i].type != 'checkbox' || info[i].checked)) { - data[info[i].name] = info[i].getValue(); + }, + + preparePaymentRequest: function (data) { + if ($(this.code + '_cc_cid')) { + data.x_card_code = $(this.code + '_cc_cid').value; } - } - data.reset_shipping = true; - data.update_items = true; - if ($('coupons:code') && $F('coupons:code')) { - data['order[coupon][code]'] = $F('coupons:code'); - } - data.json = true; - new Ajax.Request(url, { - parameters : data, - loaderArea : 'html-body', - onSuccess : function(transport) { - jQuery('#edit_form').submit(); - }.bind(this) - }); - - }, - - saveAdminOrderSuccess : function(data) { - try { - response = data.evalJSON(true); - } catch (e) { - response = {}; - } + var year = $(this.code + '_expiration_yr').value; - if (response.directpost) { - this.orderIncrementId = response.directpost.fields.x_invoice_num; - var paymentData = {}; - for ( var key in response.directpost.fields) { - paymentData[key] = response.directpost.fields[key]; + if (year.length > 2) { + year = year.substring(2); } - var preparedData = this.preparePaymentRequest(paymentData); - this.sendPaymentRequest(preparedData); - } else { - if (response.redirect) { - window.location = response.redirect; + var month = parseInt($(this.code + '_expiration').value, 10); + + if (month < 10) { + month = '0' + month; } - if (response.error_messages) { - var msg = response.error_messages; - if (typeof (msg) == 'object') { - msg = msg.join("\n"); - } - if (msg) { - alert(msg); - } + + data.x_exp_date = month + '/' + year; + data.x_card_num = $(this.code + '_cc_number').value; + + return data; + }, + + sendPaymentRequest: function (preparedData) { + this.recreateIframe(); + this.tmpForm = document.createElement('form'); + this.tmpForm.style.display = 'none'; + this.tmpForm.enctype = 'application/x-www-form-urlencoded'; + this.tmpForm.method = 'POST'; + document.body.appendChild(this.tmpForm); + this.tmpForm.action = this.cgiUrl; + this.tmpForm.target = $(this.iframeId).readAttribute('name'); + this.tmpForm.setAttribute('target', $(this.iframeId).readAttribute('name')); + + for (var param in preparedData) { + this.tmpForm.appendChild(this.createHiddenElement(param, preparedData[param])); } - } - }, - preparePaymentRequest : function(data) { - if ($(this.code + '_cc_cid')) { - data.x_card_code = $(this.code + '_cc_cid').value; - } - var year = $(this.code + '_expiration_yr').value; - if (year.length > 2) { - year = year.substring(2); - } - var month = parseInt($(this.code + '_expiration').value, 10); - if (month < 10) { - month = '0' + month; - } + this.paymentRequestSent = true; + this.tmpForm.submit(); + }, - data.x_exp_date = month + '/' + year; - data.x_card_num = $(this.code + '_cc_number').value; - - return data; - }, - - sendPaymentRequest : function(preparedData) { - this.recreateIframe(); - this.tmpForm = document.createElement('form'); - this.tmpForm.style.display = 'none'; - this.tmpForm.enctype = 'application/x-www-form-urlencoded'; - this.tmpForm.method = 'POST'; - document.body.appendChild(this.tmpForm); - this.tmpForm.action = this.cgiUrl; - this.tmpForm.target = $(this.iframeId).readAttribute('name'); - this.tmpForm.setAttribute('target', $(this.iframeId).readAttribute('name')); - - for ( var param in preparedData) { - this.tmpForm.appendChild(this.createHiddenElement(param, preparedData[param])); - } + createHiddenElement: function (name, value) { + var field; - this.paymentRequestSent = true; - this.tmpForm.submit(); - }, - - createHiddenElement : function(name, value) { - var field; - if (isIE) { - field = document.createElement('input'); - field.setAttribute('type', 'hidden'); - field.setAttribute('name', name); - field.setAttribute('value', value); - } else { - field = document.createElement('input'); - field.type = 'hidden'; - field.name = name; - field.value = value; - } + if (isIE) { + field = document.createElement('input'); + field.setAttribute('type', 'hidden'); + field.setAttribute('name', name); + field.setAttribute('value', value); + } else { + field = document.createElement('input'); + field.type = 'hidden'; + field.name = name; + field.value = value; + } - return field; - }, - - recreateIframe : function() { - if ($(this.iframeId)) { - var nextElement = $(this.iframeId).next(); - var src = $(this.iframeId).readAttribute('src'); - var name = $(this.iframeId).readAttribute('name'); - $(this.iframeId).stopObserving(); - $(this.iframeId).remove(); - var iframe = ''; - Element.insert(nextElement, {'before':iframe}); - $(this.iframeId).observe('load', this.onLoadIframe); + return field; + }, + + recreateIframe: function () { + if ($(this.iframeId)) { + var nextElement = $(this.iframeId).next(); + var src = $(this.iframeId).readAttribute('src'); + var name = $(this.iframeId).readAttribute('name'); + + $(this.iframeId).stopObserving(); + $(this.iframeId).remove(); + var iframe = ''; + + Element.insert(nextElement, { + 'before': iframe + }); + $(this.iframeId).observe('load', this.onLoadIframe); + } } - } -}; + }; })); diff --git a/app/code/Magento/Catalog/view/adminhtml/web/catalog/product/composite/configure.js b/app/code/Magento/Catalog/view/adminhtml/web/catalog/product/composite/configure.js index 550af3d5edc0b..472e964e70f22 100644 --- a/app/code/Magento/Catalog/view/adminhtml/web/catalog/product/composite/configure.js +++ b/app/code/Magento/Catalog/view/adminhtml/web/catalog/product/composite/configure.js @@ -7,12 +7,12 @@ * @api */ define([ - "Magento_Ui/js/lib/view/utils/async", - "jquery/ui", - "mage/translate", - "prototype", - "Magento_Ui/js/modal/modal" -], function(jQuery){ + 'Magento_Ui/js/lib/view/utils/async', + 'jquery/ui', + 'mage/translate', + 'prototype', + 'Magento_Ui/js/modal/modal' +], function (jQuery) { window.ProductConfigure = Class.create(); @@ -45,11 +45,11 @@ define([ /** * Initialize object */ - initialize: function() { + initialize: function () { var self = this; this._initWindowElements(); - jQuery.async('#product_composite_configure',function (el) { + jQuery.async('#product_composite_configure', function (el) { self.dialog = jQuery(el).modal({ title: jQuery.mage.__('Configure Product'), type: 'slide', @@ -67,7 +67,7 @@ define([ /** * Initialize window elements */ - _initWindowElements: function() { + _initWindowElements: function () { this.blockWindow = $('product_composite_configure'); this.blockForm = $('product_composite_configure_form'); this.blockFormFields = $('product_composite_configure_form_fields'); @@ -85,7 +85,7 @@ define([ * Returns next unique list type id */ _generateListTypeId: function () { - return '_internal_lt_' + (this._listTypeId++); + return '_internal_lt_' + this._listTypeId++; }, /** @@ -99,11 +99,12 @@ define([ * - {urlConfirm: 'http://magento...'} for submit configured data through iFrame when clicked confirm button * - {urlSubmit: 'http://magento...'} for submit configured data through iFrame */ - addListType: function(type, urls) { + addListType: function (type, urls) { if ('undefined' == typeof this.listTypes[type]) { this.listTypes[type] = {}; } Object.extend(this.listTypes[type], urls); + return this; }, @@ -117,11 +118,13 @@ define([ * - {urlSubmit: 'http://magento...'} for submit configured data through iFrame * @return type string */ - addComplexListType: function(types, urlSubmit) { + addComplexListType: function (types, urlSubmit) { var type = this._generateListTypeId(); + this.listTypes[type] = {}; this.listTypes[type].complexTypes = types; this.listTypes[type].urlSubmit = urlSubmit; + return type; }, @@ -131,14 +134,16 @@ define([ * @param listType scope name * @param itemsFilter */ - addItemsFilter: function(listType, itemsFilter) { + addItemsFilter: function (listType, itemsFilter) { if (!listType || !itemsFilter) { return false; } + if ('undefined' == typeof this.itemsFilter[listType]) { this.itemsFilter[listType] = []; } this.itemsFilter[listType] = this.itemsFilter[listType].concat(itemsFilter); + return this; }, @@ -163,6 +168,7 @@ define([ itemConfigured: function (listType, itemId) { var confirmedBlockId = this._getConfirmedBlockId(listType, itemId); var itemBlock = $(confirmedBlockId); + return !!(itemBlock && itemBlock.innerHTML); }, @@ -172,7 +178,7 @@ define([ * @param listType scope name * @param itemId */ - showItemConfiguration: function(listType, itemId) { + showItemConfiguration: function (listType, itemId) { if (!listType || !itemId) { return false; } @@ -196,18 +202,23 @@ define([ * @param listType scope name * @param itemId */ - _requestItemConfiguration: function(listType, itemId) { + _requestItemConfiguration: function (listType, itemId) { if (!this.listTypes[listType].urlFetch) { return false; } var url = this.listTypes[listType].urlFetch; + if (url) { new Ajax.Request(url, { - parameters: {id: itemId}, - onSuccess: function(transport) { + parameters: { + id: itemId + }, + onSuccess: function (transport) { var response = transport.responseText; + if (response.isJSON()) { response = response.evalJSON(); + if (response.error) { this.blockMsg.show(); this.blockMsgError.innerHTML = response.message; @@ -216,15 +227,19 @@ define([ this._showWindow(); } } else if (response) { - response = response + ''; + response += ''; this.blockFormFields.update(response); // Add special div to hold mage data, e.g. scripts to execute on every popup show var mageData = {}; var scripts = response.extractScripts(); + mageData.scripts = scripts; - var scriptHolder = new Element('div', {'style': 'display:none'}); + var scriptHolder = new Element('div', { + 'style': 'display:none' + }); + scriptHolder.mageData = mageData; this.blockFormFields.insert(scriptHolder); @@ -240,29 +255,33 @@ define([ * Triggered on confirm button click * Do submit configured data through iFrame if needed */ - onConfirmBtn: function() { + onConfirmBtn: function () { if (jQuery(this.blockForm).valid()) { if (this.listTypes[this.current.listType].urlConfirm) { this.submit(); } else { this._processFieldsData('item_confirm'); this._closeWindow(); + if (Object.isFunction(this.confirmCallback[this.current.listType])) { this.confirmCallback[this.current.listType](); } } } + return this; }, /** * Triggered on cancel button click */ - onCancelBtn: function() { + onCancelBtn: function () { this._closeWindow(); + if (Object.isFunction(this.cancelCallback[this.current.listType])) { this.cancelCallback[this.current.listType](); } + return this; }, @@ -279,18 +298,25 @@ define([ } var urlConfirm = this.listTypes[this.current.listType].urlConfirm; var urlSubmit = this.listTypes[this.current.listType].urlSubmit; + if (!urlConfirm && !urlSubmit) { return false; } + if (urlConfirm) { this.blockForm.action = urlConfirm; - this.addFields([new Element('input', {type: 'hidden', name: 'id', value: this.current.itemId})]); + this.addFields([new Element('input', { + type: 'hidden', name: 'id', value: this.current.itemId + })]); } else { this.blockForm.action = urlSubmit; var complexTypes = this.listTypes[this.current.listType].complexTypes; + if (complexTypes) { - this.addFields([new Element('input', {type: 'hidden', name: 'configure_complex_list_types', value: complexTypes.join(',')})]); + this.addFields([new Element('input', { + type: 'hidden', name: 'configure_complex_list_types', value: complexTypes.join(',') + })]); } this._processFieldsData('current_confirmed_to_form'); @@ -300,9 +326,11 @@ define([ var tagNames = ['input', 'select', 'textarea']; var names = {}; // Map of added field names + for (var i = 0, len = tagNames.length; i < len; i++) { var tagName = tagNames[i]; var elements = this.blockFormAdd.getElementsByTagName(tagName); + for (var index = 0, elLen = elements.length; index < elLen; index++) { names[elements[index].name] = true; } @@ -311,8 +339,10 @@ define([ for (var i = 0, len = tagNames.length; i < len; i++) { var tagName = tagNames[i]; var elements = this.blockFormConfirmed.getElementsByTagName(tagName); + for (var index = 0, elLen = elements.length; index < elLen; index++) { var element = elements[index]; + if (names[element.name]) { element.setAttribute('configure_disabled', 1); element.setAttribute('configure_prev_disabled', element.disabled ? 1 : 0); @@ -340,17 +370,18 @@ define([ * * @param fields */ - addFields: function(fields) { - fields.each(function(elm) { + addFields: function (fields) { + fields.each(function (elm) { this.blockFormAdd.insert(elm); }.bind(this)); + return this; }, /** * Triggered when form was submitted and iFrame was loaded. Get response from iFrame and handle it */ - onLoadIFrame: function() { + onLoadIFrame: function () { this.blockFormConfirmed.select('[configure_disabled=1]').each(function (element) { element.disabled = element.getAttribute('configure_prev_disabled') == '1'; }); @@ -358,7 +389,8 @@ define([ this._processFieldsData('form_confirmed_to_confirmed'); var response = this.blockIFrame.contentWindow[this.iFrameJSVarname]; - if (response && "object" == typeof response) { + + if (response && 'object' == typeof response) { if (this.listTypes[this.current.listType].urlConfirm) { if (response.ok) { this._closeWindow(); @@ -368,9 +400,11 @@ define([ this.blockMsg.show(); this.blockMsgError.innerHTML = response.message; this._showWindow(); + return false; } } + if (Object.isFunction(this.onLoadIFrameCallback[this.current.listType])) { this.onLoadIFrameCallback[this.current.listType](response); } @@ -386,19 +420,22 @@ define([ /** * Helper for fetching content from iFrame */ - _getIFrameContent: function() { - var content = (this.blockIFrame.contentWindow || this.blockIFrame.contentDocument); + _getIFrameContent: function () { + var content = this.blockIFrame.contentWindow || this.blockIFrame.contentDocument; + if (content.document) { - content=content.document; + content = content.document; } + return content; }, /** * Helper to find qty of currently confirmed item */ - getCurrentConfirmedQtyElement: function() { + getCurrentConfirmedQtyElement: function () { var elms = $(this.confirmedCurrentId).getElementsByTagName('input'); + for (var i = 0; i < elms.length; i++) { if (elms[i].name == 'qty') { return elms[i]; @@ -409,8 +446,9 @@ define([ /** * Helper to find qty of active form */ - getCurrentFormQtyElement: function() { + getCurrentFormQtyElement: function () { var elms = this.blockFormFields.getElementsByTagName('input'); + for (var i = 0; i < elms.length; i++) { if (elms[i].name == 'qty') { return elms[i]; @@ -421,7 +459,7 @@ define([ /** * Show configuration window */ - _showWindow: function() { + _showWindow: function () { this.dialog.modal('openModal'); //this._toggleSelectsExceptBlock(false); @@ -453,7 +491,7 @@ define([ /** * Close configuration window */ - _closeWindow: function() { + _closeWindow: function () { this.dialog.modal('closeModal'); //this.blockWindow.style.display = 'none'; //this.clean('window'); @@ -464,8 +502,9 @@ define([ * * @param confirmCallback */ - setConfirmCallback: function(listType, confirmCallback) { + setConfirmCallback: function (listType, confirmCallback) { this.confirmCallback[listType] = confirmCallback; + return this; }, @@ -474,8 +513,9 @@ define([ * * @param cancelCallback */ - setCancelCallback: function(listType, cancelCallback) { + setCancelCallback: function (listType, cancelCallback) { this.cancelCallback[listType] = cancelCallback; + return this; }, @@ -484,8 +524,9 @@ define([ * * @param onLoadIFrameCallback */ - setOnLoadIFrameCallback: function(listType, onLoadIFrameCallback) { + setOnLoadIFrameCallback: function (listType, onLoadIFrameCallback) { this.onLoadIFrameCallback[listType] = onLoadIFrameCallback; + return this; }, @@ -494,8 +535,9 @@ define([ * * @param showWindowCallback */ - setShowWindowCallback: function(listType, showWindowCallback) { + setShowWindowCallback: function (listType, showWindowCallback) { this.showWindowCallback[listType] = showWindowCallback; + return this; }, @@ -504,8 +546,9 @@ define([ * * @param beforeSubmitCallback */ - setBeforeSubmitCallback: function(listType, beforeSubmitCallback) { + setBeforeSubmitCallback: function (listType, beforeSubmitCallback) { this.beforeSubmitCallback[listType] = beforeSubmitCallback; + return this; }, @@ -514,13 +557,14 @@ define([ * * @param method can be 'all' or 'current' */ - clean: function(method) { + clean: function (method) { var listInfo = null; var listTypes = null; var removeConfirmed = function (listTypes) { - this.blockConfirmed.childElements().each(function(elm) { + this.blockConfirmed.childElements().each(function (elm) { for (var i = 0, len = listTypes.length; i < len; i++) { var pattern = this.blockConfirmed.id + '[' + listTypes[i] + ']'; + if (elm.id.indexOf(pattern) == 0) { elm.remove(); break; @@ -533,11 +577,13 @@ define([ case 'current': listInfo = this.listTypes[this.current.listType]; listTypes = [this.current.listType]; + if (listInfo && listInfo.complexTypes) { listTypes = listTypes.concat(listInfo.complexTypes); } removeConfirmed(listTypes); break; + case 'window': this.blockFormFields.update(); this.blockMsg.hide(); @@ -549,6 +595,7 @@ define([ if (this.listTypes[method]) { listInfo = this.listTypes[method]; listTypes = [method]; + if (listInfo.complexTypes) { listTypes = listTypes.concat(listInfo.complexTypes); } @@ -578,7 +625,7 @@ define([ * * @param method can be 'item_confirm', 'item_restore', 'current_confirmed_to_form', 'form_confirmed_to_confirmed' */ - _processFieldsData: function(method) { + _processFieldsData: function (method) { /** * Internal function for rename fields names of some list type @@ -587,18 +634,20 @@ define([ * @param method can be 'current_confirmed_to_form', 'form_confirmed_to_confirmed' * @param blockItem */ - var _renameFields = function(method, blockItem, listType) { + var _renameFields = function (method, blockItem, listType) { var pattern = null; var patternFlat = null; var replacement = null; - var replacementFlat = null + var replacementFlat = null; var scopeArr = blockItem.id.match(/.*\[\w+\]\[([^\]]+)\]$/); var itemId = scopeArr[1]; + if (method == 'current_confirmed_to_form') { pattern = RegExp('(\\w+)(\\[?)'); patternFlat = RegExp('(\\w+)'); replacement = 'item[' + itemId + '][$1]$2'; replacementFlat = 'item_' + itemId + '_$1'; + if (listType) { replacement = 'list[' + listType + '][item][' + itemId + '][$1]$2'; replacementFlat = 'list_' + listType + '_' + replacementFlat; @@ -606,6 +655,7 @@ define([ } else if (method == 'form_confirmed_to_confirmed') { var stPattern = 'item\\[' + itemId + '\\]\\[(\\w+)\\](.*)'; var stPatternFlat = 'item_' + itemId + '_(\\w+)'; + if (listType) { stPattern = 'list\\[' + listType + '\\]\\[item\\]\\[' + itemId + '\\]\\[(\\w+)\\](.*)'; stPatternFlat = 'list_' + listType + '_' + stPatternFlat; @@ -626,29 +676,35 @@ define([ } } }; + rename(blockItem.getElementsByTagName('input')); rename(blockItem.getElementsByTagName('select')); rename(blockItem.getElementsByTagName('textarea')); - }.bind(this); + }; switch (method) { case 'item_confirm': if (!$(this.confirmedCurrentId)) { - this.blockConfirmed.insert(new Element('div', {id: this.confirmedCurrentId})); + this.blockConfirmed.insert(new Element('div', { + id: this.confirmedCurrentId + })); } else { $(this.confirmedCurrentId).update(); } - this.blockFormFields.childElements().each(function(elm) { + this.blockFormFields.childElements().each(function (elm) { $(this.confirmedCurrentId).insert(elm); }.bind(this)); break; + case 'item_restore': this.blockFormFields.update(); // clone confirmed to form var mageData = null; - $(this.confirmedCurrentId).childElements().each(function(elm) { + + $(this.confirmedCurrentId).childElements().each(function (elm) { var cloned = elm.cloneNode(true); + if (elm.mageData) { cloned.mageData = elm.mageData; mageData = elm.mageData; @@ -661,9 +717,10 @@ define([ var getConfirmedValues = function (elms) { for (var i = 0; i < elms.length; i++) { if (elms[i].name) { - if ('undefined' == typeof fieldsValue[elms[i].name] ) { + if ('undefined' == typeof fieldsValue[elms[i].name]) { fieldsValue[elms[i].name] = {}; } + if (elms[i].type == 'checkbox') { fieldsValue[elms[i].name][elms[i].value] = elms[i].checked; } else if (elms[i].type == 'radio') { @@ -675,7 +732,8 @@ define([ } } } - }.bind(this); + }; + getConfirmedValues($(this.confirmedCurrentId).getElementsByTagName('input')); getConfirmedValues($(this.confirmedCurrentId).getElementsByTagName('select')); getConfirmedValues($(this.confirmedCurrentId).getElementsByTagName('textarea')); @@ -697,7 +755,8 @@ define([ } } } - }.bind(this); + }; + restoreConfirmedValues(this.blockFormFields.getElementsByTagName('input')); restoreConfirmedValues(this.blockFormFields.getElementsByTagName('select')); restoreConfirmedValues(this.blockFormFields.getElementsByTagName('textarea')); @@ -705,8 +764,9 @@ define([ // Execute scripts if (mageData && mageData.scripts) { this.restorePhase = true; + try { - mageData.scripts.map(function(script) { + mageData.scripts.map(function (script) { return eval(script); }); } catch (e) { @@ -715,10 +775,13 @@ define([ this.restorePhase = false; } break; + case 'current_confirmed_to_form': var allowedListTypes = {}; + allowedListTypes[this.current.listType] = true; var listInfo = this.listTypes[this.current.listType]; + if (listInfo.complexTypes) { for (var i = 0, len = listInfo.complexTypes.length; i < len; i++) { allowedListTypes[listInfo.complexTypes[i]] = true; @@ -726,22 +789,26 @@ define([ } this.blockFormConfirmed.update(); - this.blockConfirmed.childElements().each(function(blockItem) { + this.blockConfirmed.childElements().each(function (blockItem) { var scopeArr = blockItem.id.match(/.*\[(\w+)\]\[([^\]]+)\]$/); var listType = scopeArr[1]; var itemId = scopeArr[2]; - if (allowedListTypes[listType] && (!this.itemsFilter[listType] - || this.itemsFilter[listType].indexOf(itemId) != -1)) { + + if (allowedListTypes[listType] && (!this.itemsFilter[listType] || + this.itemsFilter[listType].indexOf(itemId) != -1)) { _renameFields(method, blockItem, listInfo.complexTypes ? listType : null); this.blockFormConfirmed.insert(blockItem); } }.bind(this)); break; + case 'form_confirmed_to_confirmed': var listInfo = this.listTypes[this.current.listType]; - this.blockFormConfirmed.childElements().each(function(blockItem) { + + this.blockFormConfirmed.childElements().each(function (blockItem) { var scopeArr = blockItem.id.match(/.*\[(\w+)\]\[([^\]]+)\]$/); var listType = scopeArr[1]; + _renameFields(method, blockItem, listInfo.complexTypes ? listType : null); this.blockConfirmed.insert(blockItem); }.bind(this)); @@ -755,14 +822,15 @@ define([ * @param object element * @param object event */ - changeOptionQty: function(element, event) - { + changeOptionQty: function (element, event) { var checkQty = true; + if ('undefined' != typeof event) { if (event.keyCode == 8 || event.keyCode == 46) { checkQty = false; } } + if (checkQty && (Number(element.value) <= 0 || isNaN(Number(element.value)))) { element.value = 1; } diff --git a/app/code/Magento/Rule/view/adminhtml/web/rules.js b/app/code/Magento/Rule/view/adminhtml/web/rules.js index 1423c05fefcaf..5c4be367b9cb3 100644 --- a/app/code/Magento/Rule/view/adminhtml/web/rules.js +++ b/app/code/Magento/Rule/view/adminhtml/web/rules.js @@ -8,16 +8,16 @@ */ define([ - "jquery", + 'jquery', 'Magento_Ui/js/modal/alert', - "mage/translate", - "prototype" -], function(jQuery){ + 'mage/translate', + 'prototype' +], function (jQuery) { var VarienRulesForm = new Class.create(); VarienRulesForm.prototype = { - initialize : function(parent, newChildUrl){ + initialize: function (parent, newChildUrl) { this.parent = $(parent); this.newChildUrl = newChildUrl; this.shownElement = null; @@ -26,26 +26,31 @@ define([ this.readOnly = false; var elems = this.parent.getElementsByClassName('rule-param'); - for (var i=0; i30) { - str = str.substr(0, 30)+'...'; + } else if (str.length > 30) { + str = str.substr(0, 30) + '...'; } label.innerHTML = str.escapeHTML(); } } else { elem = container.down('.element-value-changer'); + if (elem.value) { this.addRuleNewChild(elem); } @@ -258,10 +295,12 @@ define([ var parent_id = elem.id.replace(/^.*__(.*)__.*$/, '$1'); var children_ul_id = elem.id.replace(/__/g, ':').replace(/[^:]*$/, 'children').replace(/:/g, '__'); var children_ul = $(this.parent).select('#' + children_ul_id)[0]; - var max_id = 0, i; + var max_id = 0, + i; var children_inputs = Selector.findChildElements(children_ul, $A(['input.hidden'])); + if (children_inputs.length) { - children_inputs.each(function(el){ + children_inputs.each(function (el) { if (el.id.match(/__type$/)) { i = 1 * el.id.replace(/^.*__.*?([0-9]+)__.*$/, '$1'); max_id = i > max_id ? i : max_id; @@ -271,16 +310,19 @@ define([ var new_id = parent_id + '--' + (max_id + 1); var new_type = elem.value; var new_elem = document.createElement('LI'); + new_elem.className = 'rule-param-wait'; new_elem.innerHTML = jQuery.mage.__('This won\'t take long . . .'); children_ul.insertBefore(new_elem, $(elem).up('li')); new Ajax.Request(this.newChildUrl, { evalScripts: true, - parameters: {form_key: FORM_KEY, type:new_type.replace('/','-'), id:new_id }, + parameters: { + form_key: FORM_KEY, type: new_type.replace('/', '-'), id: new_id + }, onComplete: this.onAddNewChildComplete.bind(this, new_elem), - onSuccess: function(transport) { - if(this._processSuccess(transport)) { + onSuccess: function (transport) { + if (this._processSuccess(transport)) { $(new_elem).update(transport.responseText); } }.bind(this), @@ -288,21 +330,25 @@ define([ }); }, - _processSuccess : function(transport) { + _processSuccess: function (transport) { if (transport.responseText.isJSON()) { - var response = transport.responseText.evalJSON() + var response = transport.responseText.evalJSON(); + if (response.error) { alert(response.message); } - if(response.ajaxExpired && response.ajaxRedirect) { + + if (response.ajaxExpired && response.ajaxRedirect) { setLocation(response.ajaxRedirect); } + return false; } + return true; }, - _processFailure : function(transport) { + _processFailure: function (transport) { location.href = BASE_URL; }, @@ -313,13 +359,15 @@ define([ $(new_elem).removeClassName('rule-param-wait'); var elems = new_elem.getElementsByClassName('rule-param'); - for (var i=0; i*'}); - } - } - }); - } else { - objects.each(function(item) { - if($(source).formObj && $(source).formObj.validator) { - $(source).formObj.validator.reset(item); - } - $(item).removeClassName('required-entry'); - var label = findFieldLabel($(item)); - if (label) { - var span = label.down('span'); - if (span) { - Element.remove(span); + 'jquery', + 'jquery/ui', + 'mage/translate', + 'mage/validation', + 'prototype' +], function (jQuery) { + + window.giftMessagesController = { + toogleRequired: function (source, objects) { + if (!$(source).value.blank()) { + objects.each(function (item) { + $(item).addClassName('required-entry'); + var label = findFieldLabel($(item)); + + if (label) { + var span = label.down('span'); + + if (!span) { + Element.insert(label, { + bottom: ' *' + }); + } } + }); + } else { + objects.each(function (item) { + if ($(source).formObj && $(source).formObj.validator) { + $(source).formObj.validator.reset(item); + } + $(item).removeClassName('required-entry'); + var label = findFieldLabel($(item)); + + if (label) { + var span = label.down('span'); + + if (span) { + Element.remove(span); + } + } + // Hide validation advices if exist + if ($(item) && $(item).advices) { + $(item).advices.each(function (pair) { + if (pair.value != null) pair.value.hide(); + }); + } + }); + } + }, + toogleGiftMessage: function (container) { + if (!$(container).toogleGiftMessage) { + $(container).toogleGiftMessage = true; + $(this.getFieldId(container, 'edit')).show(); + $(container).down('.action-link').addClassName('open'); + $(container).down('.default-text').hide(); + $(container).down('.close-text').show(); + } else { + $(container).toogleGiftMessage = false; + $(this.getFieldId(container, 'message')).formObj = $(this.getFieldId(container, 'form')); + var form = jQuery('#' + this.getFieldId(container, 'form')); + + jQuery('#' + this.getFieldId(container, 'form')).validate({ + errorClass: 'mage-error' + }); + + if (!form.valid()) { + return false; } - // Hide validation advices if exist - if ($(item) && $(item).advices) { - $(item).advices.each(function (pair) { - if (pair.value != null) pair.value.hide(); - }); - } - }); - } - }, - toogleGiftMessage: function(container) { - if(!$(container).toogleGiftMessage) { - $(container).toogleGiftMessage = true; - $(this.getFieldId(container, 'edit')).show(); - $(container).down('.action-link').addClassName('open'); - $(container).down('.default-text').hide(); - $(container).down('.close-text').show(); - } else { - $(container).toogleGiftMessage = false; + + new Ajax.Request($(this.getFieldId(container, 'form')).action, { + parameters: Form.serialize($(this.getFieldId(container, 'form')), true), + loaderArea: container, + onComplete: function (transport) { + + $(container).down('.action-link').removeClassName('open'); + $(container).down('.default-text').show(); + $(container).down('.close-text').hide(); + $(this.getFieldId(container, 'edit')).hide(); + + if (transport.responseText.match(/YES/g)) { + $(container).down('.default-text').down('.edit').show(); + $(container).down('.default-text').down('.add').hide(); + } else { + $(container).down('.default-text').down('.add').show(); + $(container).down('.default-text').down('.edit').hide(); + } + + }.bind(this) + }); + } + + return false; + }, + saveGiftMessage: function (container) { $(this.getFieldId(container, 'message')).formObj = $(this.getFieldId(container, 'form')); + var form = jQuery('#' + this.getFieldId(container, 'form')); - jQuery('#' + this.getFieldId(container, 'form')).validate({errorClass: 'mage-error'}); - if(!form.valid()) { - return false; + form.validate({ + errorClass: 'mage-error' + }); + + if (!form.valid()) { + return; } new Ajax.Request($(this.getFieldId(container, 'form')).action, { parameters: Form.serialize($(this.getFieldId(container, 'form')), true), loaderArea: container, - onComplete: function(transport) { - - $(container).down('.action-link').removeClassName('open'); - $(container).down('.default-text').show(); - $(container).down('.close-text').hide(); - $(this.getFieldId(container, 'edit')).hide(); - if (transport.responseText.match(/YES/g)) { - $(container).down('.default-text').down('.edit').show(); - $(container).down('.default-text').down('.add').hide(); - } else { - $(container).down('.default-text').down('.add').show(); - $(container).down('.default-text').down('.edit').hide(); - } + onSuccess: function (response) { + var message = '' + + response.responseText + + ''; - }.bind(this) + jQuery('#messages').html(message); + jQuery(document).scrollTop(0); + } }); + }, + getFieldId: function (container, name) { + return container + '_' + name; } + }; - return false; - }, - saveGiftMessage: function(container) { - $(this.getFieldId(container, 'message')).formObj = $(this.getFieldId(container, 'form')); + function findFieldLabel(field) { + var tdField = $(field).up('td'); - var form = jQuery('#' + this.getFieldId(container, 'form')); - form.validate({errorClass: 'mage-error'}); + if (tdField) { + var tdLabel = tdField.previous('td'); - if(!form.valid()) { - return; - } + if (tdLabel) { + var label = tdLabel.down('label'); - new Ajax.Request($(this.getFieldId(container, 'form')).action, { - parameters: Form.serialize($(this.getFieldId(container, 'form')), true), - loaderArea: container, - onSuccess: function(response) { - var message = '' - + response.responseText - + ''; - jQuery('#messages').html(message); - jQuery(document).scrollTop(0); + if (label) { + return label; + } } - }); - }, - getFieldId: function(container, name) { - return container + '_' + name; - } -}; - -function findFieldLabel(field) { - var tdField = $(field).up('td'); - if (tdField) { - var tdLabel = tdField.previous('td'); - if (tdLabel) { - var label = tdLabel.down('label'); - if (label) { - return label; - } - } + } + + return false; } - return false; -} + window.findFieldLabel = findFieldLabel; -window.findFieldLabel = findFieldLabel; + window.GiftOptionsPopup = Class.create(); + GiftOptionsPopup.prototype = { + //giftOptionsWindowMask: null, + giftOptionsWindow: null, -window.GiftOptionsPopup = Class.create(); -GiftOptionsPopup.prototype = { - //giftOptionsWindowMask: null, - giftOptionsWindow: null, + initialize: function () { + $$('.action-link').each(function (el) { + Event.observe(el, 'click', this.showItemGiftOptions.bind(this)); + }, this); - initialize: function() { - $$('.action-link').each(function (el) { - Event.observe(el, 'click', this.showItemGiftOptions.bind(this)); - }, this); + // Move gift options popup to start of body, because soon it will contain FORM tag that can break DOM layout if within other FORM + var oldPopupContainer = $('gift_options_configure'); - // Move gift options popup to start of body, because soon it will contain FORM tag that can break DOM layout if within other FORM - var oldPopupContainer = $('gift_options_configure'); - if (oldPopupContainer) { - oldPopupContainer.remove(); - } + if (oldPopupContainer) { + oldPopupContainer.remove(); + } - var newPopupContainer = $('gift_options_configure_new'); - $(document.body).insert({top: newPopupContainer}); - newPopupContainer.id = 'gift_options_configure'; + var newPopupContainer = $('gift_options_configure_new'); - // Put controls container inside a FORM tag so we can use Validator - var form = new Element('form', {action: '#', id: 'gift_options_configuration_form', method: 'post'}); - var formContents = $('gift_options_form_contents'); - if (formContents) { - formContents.parentNode.appendChild(form); - form.appendChild(formContents); - } + $(document.body).insert({ + top: newPopupContainer + }); + newPopupContainer.id = 'gift_options_configure'; + + // Put controls container inside a FORM tag so we can use Validator + var form = new Element('form', { + action: '#', id: 'gift_options_configuration_form', method: 'post' + }); + var formContents = $('gift_options_form_contents'); - this.giftOptionsWindow = $('gift_options_configure'); - - jQuery(this.giftOptionsWindow).dialog({ - autoOpen: false, - modal: true, - resizable: false, - dialogClass: 'gift-options-popup', - minWidth: 500, - width: '75%', - position: { - my: 'left+12.5% top', - at: 'center top', - of: 'body' - }, - open: function () { - jQuery(this).closest('.ui-dialog').addClass('ui-dialog-active'); - - var topMargin = jQuery(this).closest('.ui-dialog').children('.ui-dialog-titlebar').outerHeight() + 30; - jQuery(this).closest('.ui-dialog').css('margin-top', topMargin); - }, - close: function() { - jQuery(this).closest('.ui-dialog').removeClass('ui-dialog-active'); + if (formContents) { + formContents.parentNode.appendChild(form); + form.appendChild(formContents); } - }); - }, - showItemGiftOptions : function(event) { - var element = Event.element(event).id; - var itemId = element.sub('gift_options_link_',''); + this.giftOptionsWindow = $('gift_options_configure'); + + jQuery(this.giftOptionsWindow).dialog({ + autoOpen: false, + modal: true, + resizable: false, + dialogClass: 'gift-options-popup', + minWidth: 500, + width: '75%', + position: { + my: 'left+12.5% top', + at: 'center top', + of: 'body' + }, + open: function () { + jQuery(this).closest('.ui-dialog').addClass('ui-dialog-active'); + + var topMargin = jQuery(this).closest('.ui-dialog').children('.ui-dialog-titlebar').outerHeight() + 30; + + jQuery(this).closest('.ui-dialog').css('margin-top', topMargin); + }, + close: function () { + jQuery(this).closest('.ui-dialog').removeClass('ui-dialog-active'); + } + }); + }, - jQuery(this.giftOptionsWindow).dialog('open'); + showItemGiftOptions: function (event) { + var element = Event.element(event).id; + var itemId = element.sub('gift_options_link_', ''); - this.setTitle(itemId); + jQuery(this.giftOptionsWindow).dialog('open'); - Event.observe($('gift_options_cancel_button'), 'click', this.onCloseButton.bind(this)); - Event.observe($('gift_options_ok_button'), 'click', this.onOkButton.bind(this)); - Event.stop(event); - }, + this.setTitle(itemId); - setTitle : function (itemId) { - var productTitleElement = $('order_item_' + itemId + '_title'); - var productTitle = ''; - if (productTitleElement) { - productTitle = productTitleElement.innerHTML; - } - jQuery(this.giftOptionsWindow).dialog({ title: jQuery.mage.__('Gift Options for ') + productTitle }); - }, + Event.observe($('gift_options_cancel_button'), 'click', this.onCloseButton.bind(this)); + Event.observe($('gift_options_ok_button'), 'click', this.onOkButton.bind(this)); + Event.stop(event); + }, - onOkButton : function() { - var giftOptionsForm = jQuery('#gift_options_configuration_form'); - if (!giftOptionsForm.validate({errorClass: 'mage-error'}).valid()) { - return false; - } - if (jQuery.isFunction(giftOptionsForm[0].reset)) { - giftOptionsForm[0].reset(); + setTitle: function (itemId) { + var productTitleElement = $('order_item_' + itemId + '_title'); + var productTitle = ''; + + if (productTitleElement) { + productTitle = productTitleElement.innerHTML; + } + jQuery(this.giftOptionsWindow).dialog({ + title: jQuery.mage.__('Gift Options for ') + productTitle + }); + }, + + onOkButton: function () { + var giftOptionsForm = jQuery('#gift_options_configuration_form'); + + if (!giftOptionsForm.validate({ + errorClass: 'mage-error' + }).valid()) { + return false; + } + + if (jQuery.isFunction(giftOptionsForm[0].reset)) { + giftOptionsForm[0].reset(); + } + this.closeWindow(); + + return true; + }, + + onCloseButton: function () { + this.closeWindow(); + }, + + closeWindow: function () { + jQuery(this.giftOptionsWindow).dialog('close'); } - this.closeWindow(); - return true; - }, + }; - onCloseButton : function() { - this.closeWindow(); - }, + window.GiftMessageSet = Class.create(); - closeWindow : function() { - jQuery(this.giftOptionsWindow).dialog('close'); - } -} + GiftMessageSet.prototype = { + destPrefix: 'current_item_giftmessage_', + sourcePrefix: 'giftmessage_', + fields: ['sender', 'recipient', 'message'], + isObserved: false, + callback: null, + initialize: function () { + $$('.action-link').each(function (el) { + Event.observe(el, 'click', this.setData.bind(this)); + }, this); + }, + + setData: function (event) { + var element = Event.element(event).id; + + this.id = element.sub('gift_options_link_', ''); + + if ($('gift-message-form-data-' + this.id)) { + this.fields.each(function (el) { + if ($(this.sourcePrefix + this.id + '_' + el) && $(this.destPrefix + el)) { + $(this.destPrefix + el).value = $(this.sourcePrefix + this.id + '_' + el).value; + } + }, this); + $('gift_options_giftmessage').show(); + } else if ($('gift_options_giftmessage')) { + $('gift_options_giftmessage').hide(); + } + + if (!this.isObserved) { + Event.observe('gift_options_ok_button', 'click', this.saveData.bind(this)); + this.isObserved = true; + } + }, + + prepareSaveData: function () { + var hash = $H(); -window.GiftMessageSet = Class.create(); + $$('div[id^=gift_options_data_]').each(function (el) { + var fields = el.select('input', 'select', 'textarea'); + var data = Form.serializeElements(fields, true); -GiftMessageSet.prototype = { - destPrefix: 'current_item_giftmessage_', - sourcePrefix: 'giftmessage_', - fields: ['sender', 'recipient', 'message'], - isObserved: false, - callback: null, + hash.update(data); + }); - initialize: function() { - $$('.action-link').each(function (el) { - Event.observe(el, 'click', this.setData.bind(this)); - }, this); - }, + return hash; + }, - setData: function(event) { - var element = Event.element(event).id; - this.id = element.sub('gift_options_link_',''); + setSaveCallback: function (callback) { + if (typeof callback == 'function') { + this.callback = callback; + } + }, - if ($('gift-message-form-data-' + this.id)) { - this.fields.each(function(el) { + saveData: function (event) { + this.fields.each(function (el) { if ($(this.sourcePrefix + this.id + '_' + el) && $(this.destPrefix + el)) { - $(this.destPrefix + el).value = $(this.sourcePrefix + this.id + '_' + el).value + $(this.sourcePrefix + this.id + '_' + el).value = $(this.destPrefix + el).value; } }, this); - $('gift_options_giftmessage').show(); - } else if ($('gift_options_giftmessage')) { - $('gift_options_giftmessage').hide(); - } - if (!this.isObserved) { - Event.observe('gift_options_ok_button', 'click', this.saveData.bind(this)); - this.isObserved = true; - } - }, - - prepareSaveData: function() { - var hash = $H(); - $$("div[id^=gift_options_data_]").each(function (el) { - var fields = el.select('input', 'select', 'textarea'); - var data = Form.serializeElements(fields, true); - hash.update(data); - }); - return hash; - }, - - setSaveCallback: function(callback) { - if (typeof callback == 'function') { - this.callback = callback; - } - }, + if ($(this.sourcePrefix + this.id + '_form')) { + $(this.sourcePrefix + this.id + '_form').request(); + } else if (typeof order != 'undefined') { + var data = this.prepareSaveData(); + var self = this; - saveData: function(event){ - this.fields.each(function(el) { - if ($(this.sourcePrefix + this.id + '_' + el) && $(this.destPrefix + el)) { - $(this.sourcePrefix + this.id + '_' + el).value = $(this.destPrefix + el).value; + jQuery.when(order.loadArea(['items'], true, data.toObject())).done(function () { + if (self.callback !== null) { + self.callback(); + } + }); } - }, this); - if ($(this.sourcePrefix + this.id + '_form')) { - $(this.sourcePrefix + this.id + '_form').request(); - } else if (typeof(order) != 'undefined') { - var data = this.prepareSaveData(); - var self = this; - jQuery.when(order.loadArea(['items'], true, data.toObject())).done(function() { - if (self.callback !== null) { - self.callback(); - } - }); } - } -}; + }; }); diff --git a/app/code/Magento/Shipping/view/adminhtml/web/order/packaging.js b/app/code/Magento/Shipping/view/adminhtml/web/order/packaging.js index 02579b20b6dd0..38ba66d354386 100644 --- a/app/code/Magento/Shipping/view/adminhtml/web/order/packaging.js +++ b/app/code/Magento/Shipping/view/adminhtml/web/order/packaging.js @@ -3,811 +3,900 @@ * See COPYING.txt for license details. */ -define(["prototype"], function(){ - -window.Packaging = Class.create(); -Packaging.prototype = { - /** - * Initialize object - */ - initialize: function(params) { - this.packageIncrement = 0; - this.packages = []; - this.itemsAll = []; - this.createLabelUrl = params.createLabelUrl ? params.createLabelUrl : null; - this.itemsGridUrl = params.itemsGridUrl ? params.itemsGridUrl : null; - this.errorQtyOverLimit = params.errorQtyOverLimit; - this.titleDisabledSaveBtn = params.titleDisabledSaveBtn; - this.window = $('packaging_window'); - this.messages = this.window.select('.message-warning')[0]; - this.packagesContent = $('packages_content'); - this.template = $('package_template'); - this.paramsCreateLabelRequest = {}; - this.validationErrorMsg = params.validationErrorMsg; - - this.defaultItemsQty = params.shipmentItemsQty ? params.shipmentItemsQty : null; - this.defaultItemsPrice = params.shipmentItemsPrice ? params.shipmentItemsPrice : null; - this.defaultItemsName = params.shipmentItemsName ? params.shipmentItemsName : null; - this.defaultItemsWeight = params.shipmentItemsWeight ? params.shipmentItemsWeight : null; - this.defaultItemsProductId = params.shipmentItemsProductId ? params.shipmentItemsProductId : null; - this.defaultItemsOrderItemId = params.shipmentItemsOrderItemId ? params.shipmentItemsOrderItemId : null; - - this.shippingInformation= params.shippingInformation ? params.shippingInformation : null; - this.thisPage = params.thisPage ? params.thisPage : null; - this.customizableContainers = params.customizable ? params.customizable : []; - - this.eps = .000001; - }, - - /** - * Get Package Id - */ - getPackageId: function(packageBlock) { - return packageBlock.id.match(/\d{0,}$/)[0]; - }, - -//******************** Setters **********************************// - setLabelCreatedCallback: function(callback) { - this.labelCreatedCallback = callback; - }, - setCancelCallback: function(callback) { - this.cancelCallback = callback; - }, - setConfirmPackagingCallback: function(callback) { - this.confirmPackagingCallback = callback; - }, - setItemQtyCallback: function(callback) { - this.itemQtyCallback = callback; - }, - setCreateLabelUrl: function(url) { - this.createLabelUrl = url; - }, - setParamsCreateLabelRequest: function(params) { - Object.extend(this.paramsCreateLabelRequest, params); - }, -//******************** End Setters *******************************// - - showWindow: function() { - if (this.packagesContent.childElements().length == 0) { - this.newPackage(); - } - jQuery(this.window).modal('openModal') - }, +define(['prototype'], function () { + + window.Packaging = Class.create(); + Packaging.prototype = { + /** + * Initialize object + */ + initialize: function (params) { + this.packageIncrement = 0; + this.packages = []; + this.itemsAll = []; + this.createLabelUrl = params.createLabelUrl ? params.createLabelUrl : null; + this.itemsGridUrl = params.itemsGridUrl ? params.itemsGridUrl : null; + this.errorQtyOverLimit = params.errorQtyOverLimit; + this.titleDisabledSaveBtn = params.titleDisabledSaveBtn; + this.window = $('packaging_window'); + this.messages = this.window.select('.message-warning')[0]; + this.packagesContent = $('packages_content'); + this.template = $('package_template'); + this.paramsCreateLabelRequest = {}; + this.validationErrorMsg = params.validationErrorMsg; + + this.defaultItemsQty = params.shipmentItemsQty ? params.shipmentItemsQty : null; + this.defaultItemsPrice = params.shipmentItemsPrice ? params.shipmentItemsPrice : null; + this.defaultItemsName = params.shipmentItemsName ? params.shipmentItemsName : null; + this.defaultItemsWeight = params.shipmentItemsWeight ? params.shipmentItemsWeight : null; + this.defaultItemsProductId = params.shipmentItemsProductId ? params.shipmentItemsProductId : null; + this.defaultItemsOrderItemId = params.shipmentItemsOrderItemId ? params.shipmentItemsOrderItemId : null; + + this.shippingInformation = params.shippingInformation ? params.shippingInformation : null; + this.thisPage = params.thisPage ? params.thisPage : null; + this.customizableContainers = params.customizable ? params.customizable : []; + + this.eps = 0.000001; + }, + + /** + * Get Package Id + */ + getPackageId: function (packageBlock) { + return packageBlock.id.match(/\d{0,}$/)[0]; + }, + + //******************** Setters **********************************// + setLabelCreatedCallback: function (callback) { + this.labelCreatedCallback = callback; + }, + setCancelCallback: function (callback) { + this.cancelCallback = callback; + }, + setConfirmPackagingCallback: function (callback) { + this.confirmPackagingCallback = callback; + }, + setItemQtyCallback: function (callback) { + this.itemQtyCallback = callback; + }, + setCreateLabelUrl: function (url) { + this.createLabelUrl = url; + }, + setParamsCreateLabelRequest: function (params) { + Object.extend(this.paramsCreateLabelRequest, params); + }, + //******************** End Setters *******************************// + + showWindow: function () { + if (this.packagesContent.childElements().length == 0) { + this.newPackage(); + } + jQuery(this.window).modal('openModal'); + }, - cancelPackaging: function() { - if (Object.isFunction(this.cancelCallback)) { - this.cancelCallback(); - } - }, + cancelPackaging: function () { + if (Object.isFunction(this.cancelCallback)) { + this.cancelCallback(); + } + }, - confirmPackaging: function(params) { - if (Object.isFunction(this.confirmPackagingCallback)) { - this.confirmPackagingCallback(); - } - }, - - checkAllItems: function(headCheckbox) { - $(headCheckbox).up('table').select('tbody input[type="checkbox"]').each(function(checkbox){ - checkbox.checked = headCheckbox.checked; - this._observeQty.call(checkbox); - }.bind(this)); - }, - - cleanPackages: function() { - this.packagesContent.update(); - this.packages = []; - this.itemsAll = []; - this.packageIncrement = 0; - this._setAllItemsPackedState(); - this.messages.hide().update(); - }, - - sendCreateLabelRequest: function() { - var self = this; - if (!this.validate()) { - this.messages.show().update(this.validationErrorMsg); - return; - } else { + confirmPackaging: function (params) { + if (Object.isFunction(this.confirmPackagingCallback)) { + this.confirmPackagingCallback(); + } + }, + + checkAllItems: function (headCheckbox) { + $(headCheckbox).up('table').select('tbody input[type="checkbox"]').each(function (checkbox) { + checkbox.checked = headCheckbox.checked; + this._observeQty.call(checkbox); + }.bind(this)); + }, + + cleanPackages: function () { + this.packagesContent.update(); + this.packages = []; + this.itemsAll = []; + this.packageIncrement = 0; + this._setAllItemsPackedState(); this.messages.hide().update(); - } - if (this.createLabelUrl) { - var weight, length, width, height = null; - var packagesParams = []; - this.packagesContent.childElements().each(function(pack) { - var packageId = this.getPackageId(pack); - weight = parseFloat(pack.select('input[name="container_weight"]')[0].value); - length = parseFloat(pack.select('input[name="container_length"]')[0].value); - width = parseFloat(pack.select('input[name="container_width"]')[0].value); - height = parseFloat(pack.select('input[name="container_height"]')[0].value); - packagesParams[packageId] = { - container: pack.select('select[name="package_container"]')[0].value, - customs_value: parseFloat(pack.select('input[name="package_customs_value"]')[0].value, 10), - weight: isNaN(weight) ? '' : weight, - length: isNaN(length) ? '' : length, - width: isNaN(width) ? '' : width, - height: isNaN(height) ? '' : height, - weight_units: pack.select('select[name="container_weight_units"]')[0].value, - dimension_units: pack.select('select[name="container_dimension_units"]')[0].value - }; - if (isNaN(packagesParams[packageId]['customs_value'])) { - packagesParams[packageId]['customs_value'] = 0; - } - if ('undefined' != typeof pack.select('select[name="package_size"]')[0]) { - if ('' != pack.select('select[name="package_size"]')[0].value) { - packagesParams[packageId]['size'] = pack.select('select[name="package_size"]')[0].value; + }, + + sendCreateLabelRequest: function () { + var self = this; + + if (!this.validate()) { + this.messages.show().update(this.validationErrorMsg); + + return; + } + this.messages.hide().update(); + + if (this.createLabelUrl) { + var weight, length, width, height = null; + var packagesParams = []; + + this.packagesContent.childElements().each(function (pack) { + var packageId = this.getPackageId(pack); + + weight = parseFloat(pack.select('input[name="container_weight"]')[0].value); + length = parseFloat(pack.select('input[name="container_length"]')[0].value); + width = parseFloat(pack.select('input[name="container_width"]')[0].value); + height = parseFloat(pack.select('input[name="container_height"]')[0].value); + packagesParams[packageId] = { + container: pack.select('select[name="package_container"]')[0].value, + customs_value: parseFloat(pack.select('input[name="package_customs_value"]')[0].value, 10), + weight: isNaN(weight) ? '' : weight, + length: isNaN(length) ? '' : length, + width: isNaN(width) ? '' : width, + height: isNaN(height) ? '' : height, + weight_units: pack.select('select[name="container_weight_units"]')[0].value, + dimension_units: pack.select('select[name="container_dimension_units"]')[0].value + }; + + if (isNaN(packagesParams[packageId]['customs_value'])) { + packagesParams[packageId]['customs_value'] = 0; } - } - if ('undefined' != typeof pack.select('input[name="container_girth"]')[0]) { - if ('' != pack.select('input[name="container_girth"]')[0].value) { - packagesParams[packageId]['girth'] = pack.select('input[name="container_girth"]')[0].value; - packagesParams[packageId]['girth_dimension_units'] = pack.select('select[name="container_girth_dimension_units"]')[0].value; + + if ('undefined' != typeof pack.select('select[name="package_size"]')[0]) { + if ('' != pack.select('select[name="package_size"]')[0].value) { + packagesParams[packageId]['size'] = pack.select('select[name="package_size"]')[0].value; + } + } + + if ('undefined' != typeof pack.select('input[name="container_girth"]')[0]) { + if ('' != pack.select('input[name="container_girth"]')[0].value) { + packagesParams[packageId]['girth'] = pack.select('input[name="container_girth"]')[0].value; + packagesParams[packageId]['girth_dimension_units'] = pack.select('select[name="container_girth_dimension_units"]')[0].value; + } + } + + if ('undefined' != typeof pack.select('select[name="content_type"]')[0] && 'undefined' != typeof pack.select('input[name="content_type_other"]')[0]) { + packagesParams[packageId]['content_type'] = pack.select('select[name="content_type"]')[0].value; + packagesParams[packageId]['content_type_other'] = pack.select('input[name="content_type_other"]')[0].value; + } else { + packagesParams[packageId]['content_type'] = ''; + packagesParams[packageId]['content_type_other'] = ''; + } + var deliveryConfirmation = pack.select('select[name="delivery_confirmation_types"]'); + + if (deliveryConfirmation.length) { + packagesParams[packageId]['delivery_confirmation'] = deliveryConfirmation[0].value; + } + }.bind(this)); + + for (var packageId in this.packages) { + if (!isNaN(packageId)) { + this.paramsCreateLabelRequest['packages[' + packageId + ']' + '[params]' + '[container]'] = packagesParams[packageId]['container']; + this.paramsCreateLabelRequest['packages[' + packageId + ']' + '[params]' + '[weight]'] = packagesParams[packageId]['weight']; + this.paramsCreateLabelRequest['packages[' + packageId + ']' + '[params]' + '[customs_value]'] = packagesParams[packageId]['customs_value']; + this.paramsCreateLabelRequest['packages[' + packageId + ']' + '[params]' + '[length]'] = packagesParams[packageId]['length']; + this.paramsCreateLabelRequest['packages[' + packageId + ']' + '[params]' + '[width]'] = packagesParams[packageId]['width']; + this.paramsCreateLabelRequest['packages[' + packageId + ']' + '[params]' + '[height]'] = packagesParams[packageId]['height']; + this.paramsCreateLabelRequest['packages[' + packageId + ']' + '[params]' + '[weight_units]'] = packagesParams[packageId]['weight_units']; + this.paramsCreateLabelRequest['packages[' + packageId + ']' + '[params]' + '[dimension_units]'] = packagesParams[packageId]['dimension_units']; + this.paramsCreateLabelRequest['packages[' + packageId + ']' + '[params]' + '[content_type]'] = packagesParams[packageId]['content_type']; + this.paramsCreateLabelRequest['packages[' + packageId + ']' + '[params]' + '[content_type_other]'] = packagesParams[packageId]['content_type_other']; + + if ('undefined' != typeof packagesParams[packageId]['size']) { + this.paramsCreateLabelRequest['packages[' + packageId + ']' + '[params]' + '[size]'] = packagesParams[packageId]['size']; + } + + if ('undefined' != typeof packagesParams[packageId]['girth']) { + this.paramsCreateLabelRequest['packages[' + packageId + ']' + '[params]' + '[girth]'] = packagesParams[packageId]['girth']; + this.paramsCreateLabelRequest['packages[' + packageId + ']' + '[params]' + '[girth_dimension_units]'] = packagesParams[packageId]['girth_dimension_units']; + } + + if ('undefined' != typeof packagesParams[packageId]['delivery_confirmation']) { + this.paramsCreateLabelRequest['packages[' + packageId + ']' + '[params]' + '[delivery_confirmation]'] = packagesParams[packageId]['delivery_confirmation']; + } + + for (var packedItemId in this.packages[packageId]['items']) { + if (!isNaN(packedItemId)) { + this.paramsCreateLabelRequest['packages[' + packageId + ']' + '[items]' + '[' + packedItemId + '][qty]'] = this.packages[packageId]['items'][packedItemId]['qty']; + this.paramsCreateLabelRequest['packages[' + packageId + ']' + '[items]' + '[' + packedItemId + '][customs_value]'] = this.packages[packageId]['items'][packedItemId]['customs_value']; + this.paramsCreateLabelRequest['packages[' + packageId + ']' + '[items]' + '[' + packedItemId + '][price]'] = self.defaultItemsPrice[packedItemId]; + this.paramsCreateLabelRequest['packages[' + packageId + ']' + '[items]' + '[' + packedItemId + '][name]'] = self.defaultItemsName[packedItemId]; + this.paramsCreateLabelRequest['packages[' + packageId + ']' + '[items]' + '[' + packedItemId + '][weight]'] = self.defaultItemsWeight[packedItemId]; + this.paramsCreateLabelRequest['packages[' + packageId + ']' + '[items]' + '[' + packedItemId + '][product_id]'] = self.defaultItemsProductId[packedItemId]; + this.paramsCreateLabelRequest['packages[' + packageId + ']' + '[items]' + '[' + packedItemId + '][order_item_id]'] = self.defaultItemsOrderItemId[packedItemId]; + } + } } } - if ('undefined' != typeof pack.select('select[name="content_type"]')[0] && 'undefined' != typeof pack.select('input[name="content_type_other"]')[0]) { - packagesParams[packageId]['content_type'] = pack.select('select[name="content_type"]')[0].value; - packagesParams[packageId]['content_type_other'] = pack.select('input[name="content_type_other"]')[0].value; + + new Ajax.Request(this.createLabelUrl, { + parameters: this.paramsCreateLabelRequest, + onSuccess: function (transport) { + var response = transport.responseText; + + if (response.isJSON()) { + response = response.evalJSON(); + + if (response.error) { + this.messages.show().innerHTML = response.message; + } else if (response.ok && Object.isFunction(this.labelCreatedCallback)) { + this.labelCreatedCallback(response); + } + } + }.bind(this) + }); + + if (this.paramsCreateLabelRequest['code'] && + this.paramsCreateLabelRequest['carrier_title'] && + this.paramsCreateLabelRequest['method_title'] && + this.paramsCreateLabelRequest['price'] + ) { + var a = this.paramsCreateLabelRequest['code']; + var b = this.paramsCreateLabelRequest['carrier_title']; + var c = this.paramsCreateLabelRequest['method_title']; + var d = this.paramsCreateLabelRequest['price']; + + this.paramsCreateLabelRequest = {}; + this.paramsCreateLabelRequest['code'] = a; + this.paramsCreateLabelRequest['carrier_title'] = b; + this.paramsCreateLabelRequest['method_title'] = c; + this.paramsCreateLabelRequest['price'] = d; } else { - packagesParams[packageId]['content_type'] = ''; - packagesParams[packageId]['content_type_other'] = ''; - } - var deliveryConfirmation = pack.select('select[name="delivery_confirmation_types"]'); - if (deliveryConfirmation.length) { - packagesParams[packageId]['delivery_confirmation'] = deliveryConfirmation[0].value + this.paramsCreateLabelRequest = {}; } - }.bind(this)); - for (var packageId in this.packages) { - if (!isNaN(packageId)) { - this.paramsCreateLabelRequest['packages['+packageId+']'+'[params]'+'[container]'] = packagesParams[packageId]['container']; - this.paramsCreateLabelRequest['packages['+packageId+']'+'[params]'+'[weight]'] = packagesParams[packageId]['weight']; - this.paramsCreateLabelRequest['packages['+packageId+']'+'[params]'+'[customs_value]'] = packagesParams[packageId]['customs_value']; - this.paramsCreateLabelRequest['packages['+packageId+']'+'[params]'+'[length]'] = packagesParams[packageId]['length']; - this.paramsCreateLabelRequest['packages['+packageId+']'+'[params]'+'[width]'] = packagesParams[packageId]['width']; - this.paramsCreateLabelRequest['packages['+packageId+']'+'[params]'+'[height]'] = packagesParams[packageId]['height']; - this.paramsCreateLabelRequest['packages['+packageId+']'+'[params]'+'[weight_units]'] = packagesParams[packageId]['weight_units']; - this.paramsCreateLabelRequest['packages['+packageId+']'+'[params]'+'[dimension_units]'] = packagesParams[packageId]['dimension_units']; - this.paramsCreateLabelRequest['packages['+packageId+']'+'[params]'+'[content_type]'] = packagesParams[packageId]['content_type']; - this.paramsCreateLabelRequest['packages['+packageId+']'+'[params]'+'[content_type_other]'] = packagesParams[packageId]['content_type_other']; - - if ('undefined' != typeof packagesParams[packageId]['size']) { - this.paramsCreateLabelRequest['packages['+packageId+']'+'[params]'+'[size]'] = packagesParams[packageId]['size']; - } - - if ('undefined' != typeof packagesParams[packageId]['girth']) { - this.paramsCreateLabelRequest['packages['+packageId+']'+'[params]'+'[girth]'] = packagesParams[packageId]['girth']; - this.paramsCreateLabelRequest['packages['+packageId+']'+'[params]'+'[girth_dimension_units]'] = packagesParams[packageId]['girth_dimension_units']; - } - - if ('undefined' != typeof packagesParams[packageId]['delivery_confirmation']) { - this.paramsCreateLabelRequest['packages['+packageId+']'+'[params]'+'[delivery_confirmation]'] = packagesParams[packageId]['delivery_confirmation']; - } - for (var packedItemId in this.packages[packageId]['items']) { - if (!isNaN(packedItemId)) { - this.paramsCreateLabelRequest['packages['+packageId+']'+'[items]'+'['+packedItemId+'][qty]'] = this.packages[packageId]['items'][packedItemId]['qty']; - this.paramsCreateLabelRequest['packages['+packageId+']'+'[items]'+'['+packedItemId+'][customs_value]'] = this.packages[packageId]['items'][packedItemId]['customs_value']; - this.paramsCreateLabelRequest['packages['+packageId+']'+'[items]'+'['+packedItemId+'][price]'] = self.defaultItemsPrice[packedItemId]; - this.paramsCreateLabelRequest['packages['+packageId+']'+'[items]'+'['+packedItemId+'][name]'] = self.defaultItemsName[packedItemId]; - this.paramsCreateLabelRequest['packages['+packageId+']'+'[items]'+'['+packedItemId+'][weight]'] = self.defaultItemsWeight[packedItemId]; - this.paramsCreateLabelRequest['packages['+packageId+']'+'[items]'+'['+packedItemId+'][product_id]'] = self.defaultItemsProductId[packedItemId]; - this.paramsCreateLabelRequest['packages['+packageId+']'+'[items]'+'['+packedItemId+'][order_item_id]'] = self.defaultItemsOrderItemId[packedItemId]; - } - } - } - } - - new Ajax.Request(this.createLabelUrl, { - parameters: this.paramsCreateLabelRequest, - onSuccess: function(transport) { - var response = transport.responseText; - if (response.isJSON()) { - response = response.evalJSON(); - if (response.error) { - this.messages.show().innerHTML = response.message; - } else if (response.ok && Object.isFunction(this.labelCreatedCallback)) { - this.labelCreatedCallback(response); - } - } - }.bind(this) - }); - if (this.paramsCreateLabelRequest['code'] - && this.paramsCreateLabelRequest['carrier_title'] - && this.paramsCreateLabelRequest['method_title'] - && this.paramsCreateLabelRequest['price'] - ) { - var a = this.paramsCreateLabelRequest['code']; - var b = this.paramsCreateLabelRequest['carrier_title']; - var c = this.paramsCreateLabelRequest['method_title']; - var d = this.paramsCreateLabelRequest['price']; - - this.paramsCreateLabelRequest = {}; - this.paramsCreateLabelRequest['code'] = a; - this.paramsCreateLabelRequest['carrier_title'] = b; - this.paramsCreateLabelRequest['method_title'] = c; - this.paramsCreateLabelRequest['price'] = d; - } else { - this.paramsCreateLabelRequest = {}; } - } - }, - - validate: function() { - var dimensionElements = $("packaging_window").select( - 'input[name=container_length],input[name=container_width],input[name=container_height],input[name=container_girth]:not("._disabled")' - ); - var callback = null; - if ( dimensionElements.any(function(element) { return !!element.value; })) { - callback = function(element) { $(element).addClassName('required-entry'); }; - } else { - callback = function(element) { $(element).removeClassName('required-entry'); }; - } - dimensionElements.each(callback); - - return result = $$('[id^="package_block_"] input').collect(function (element) { - return this.validateElement(element) - }, this).all(); - }, - - validateElement: function(elm) { - var cn = $w(elm.className); - return result = cn.all(function(value) { - var v = Validation.get(value); - if (Validation.isVisible(elm) && !v.test($F(elm), elm)) { - $(elm).addClassName('validation-failed'); - return false; + }, + + validate: function () { + var dimensionElements = $('packaging_window').select( + 'input[name=container_length],input[name=container_width],input[name=container_height],input[name=container_girth]:not("._disabled")' + ); + var callback = null; + + if (dimensionElements.any(function (element) { + return !!element.value; + })) { + callback = function (element) { + $(element).addClassName('required-entry'); + }; } else { + callback = function (element) { + $(element).removeClassName('required-entry'); + }; + } + dimensionElements.each(callback); + + return result = $$('[id^="package_block_"] input').collect(function (element) { + return this.validateElement(element); + }, this).all(); + }, + + validateElement: function (elm) { + var cn = $w(elm.className); + + return result = cn.all(function (value) { + var v = Validation.get(value); + + if (Validation.isVisible(elm) && !v.test($F(elm), elm)) { + $(elm).addClassName('validation-failed'); + + return false; + } $(elm).removeClassName('validation-failed'); + return true; + + }); + }, + + validateCustomsValue: function () { + var items = []; + var isValid = true; + var itemsPrepare = []; + var itemsPacked = []; + + this.packagesContent.childElements().each(function (pack) { + itemsPrepare = pack.select('[data-role="package-items"]')[0]; + + if (itemsPrepare) { + items = items.concat(itemsPrepare.select('.grid tbody tr')); + } + itemsPacked = pack.select('.package_items')[0]; + + if (itemsPacked) { + items = items.concat(itemsPacked.select('.grid tbody tr')); + } + }); + + items.each(function (item) { + var itemCustomsValue = item.select('[name="customs_value"]')[0]; + + if (!this.validateElement(itemCustomsValue)) { + isValid = false; + } + }.bind(this)); + + if (isValid) { + this.messages.hide().update(); + } else { + this.messages.show().update(this.validationErrorMsg); } - }); - }, - validateCustomsValue: function() { - var items = []; - var isValid = true; - var itemsPrepare = []; - var itemsPacked = []; + return isValid; + }, + + newPackage: function () { + var pack = this.template.cloneNode(true); + + pack.id = 'package_block_' + ++this.packageIncrement; + pack.addClassName('package-block'); + pack.select('[data-role=package-number]')[0].update(this.packageIncrement); + this.packagesContent.insert({ + top: pack + }); + pack.select('[data-action=package-save-items]')[0].hide(); + pack.show(); + }, + + deletePackage: function (obj) { + var pack = $(obj).up('[id^="package_block"]'); + + var packItems = pack.select('.package_items')[0]; + var packageId = this.getPackageId(pack); - this.packagesContent.childElements().each(function(pack) { - itemsPrepare = pack.select('[data-role="package-items"]')[0]; - if (itemsPrepare) { - items = items.concat(itemsPrepare.select('.grid tbody tr')); + delete this.packages[packageId]; + pack.remove(); + this.messages.hide().update(); + this._setAllItemsPackedState(); + }, + + deleteItem: function (obj) { + var item = $(obj).up('tr'); + var itemId = item.select('[type="checkbox"]')[0].value; + var pack = $(obj).up('[id^="package_block"]'); + var packItems = pack.select('.package_items')[0]; + var packageId = this.getPackageId(pack); + + delete this.packages[packageId]['items'][itemId]; + + if (item.offsetParent.rows.length <= 2) { /* head + this last row */ + $(packItems).hide(); + } + item.remove(); + this.messages.hide().update(); + this._recalcContainerWeightAndCustomsValue(packItems); + this._setAllItemsPackedState(); + }, + + recalcContainerWeightAndCustomsValue: function (obj) { + var pack = $(obj).up('[id^="package_block"]'); + var packItems = pack.select('.package_items')[0]; + + if (packItems) { + if (!this.validateCustomsValue()) { + return; + } + this._recalcContainerWeightAndCustomsValue(packItems); + } + }, + + getItemsForPack: function (obj) { + if (this.itemsGridUrl) { + var parameters = $H({ + 'shipment_id': this.shipmentId + }); + var packageBlock = $(obj).up('[id^="package_block"]'); + var packagePrapare = packageBlock.select('[data-role=package-items]')[0]; + var packagePrapareGrid = packagePrapare.select('.grid_prepare')[0]; + + new Ajax.Request(this.itemsGridUrl, { + parameters: parameters, + onSuccess: function (transport) { + var response = transport.responseText; + + if (response) { + packagePrapareGrid.update(response); + this.processPackagePrepare(packagePrapareGrid); + + if (packagePrapareGrid.select('.grid tbody tr').length) { + packageBlock.select('[data-action=package-add-items]')[0].hide(); + packageBlock.select('[data-action=package-save-items]')[0].show(); + packagePrapare.show(); + } else { + packagePrapareGrid.update(); + } + } + }.bind(this) + }); } - itemsPacked = pack.select('.package_items')[0]; - if (itemsPacked) { - items = items.concat(itemsPacked.select('.grid tbody tr')); + }, + + getPackedItemsQty: function () { + var items = []; + + for (var packageId in this.packages) { + if (!isNaN(packageId)) { + for (var packedItemId in this.packages[packageId]['items']) { + if (!isNaN(packedItemId)) { + if (items[packedItemId]) { + items[packedItemId] += this.packages[packageId]['items'][packedItemId]['qty']; + } else { + items[packedItemId] = this.packages[packageId]['items'][packedItemId]['qty']; + } + } + } + } } - }.bind(this)); - items.each(function(item) { - var itemCustomsValue = item.select('[name="customs_value"]')[0]; - if (!this.validateElement(itemCustomsValue)) { - isValid = false; + return items; + }, + + _parseQty: function (obj) { + var qty = $(obj).hasClassName('qty-decimal') ? parseFloat(obj.value) : parseInt(obj.value); + + if (isNaN(qty) || qty <= 0) { + qty = 1; } - }.bind(this)); - if (isValid) { + return qty; + }, + + packItems: function (obj) { + var anySelected = false; + var packageBlock = $(obj).up('[id^="package_block"]'); + var packageId = this.getPackageId(packageBlock); + var packagePrepare = packageBlock.select('[data-role=package-items]')[0]; + var packagePrepareGrid = packagePrepare.select('.grid_prepare')[0]; + + // check for exceeds the total shipped quantity + var checkExceedsQty = false; + this.messages.hide().update(); - } else { - this.messages.show().update(this.validationErrorMsg); - } - return isValid; - }, - - newPackage: function() { - var pack = this.template.cloneNode(true); - pack.id = 'package_block_' + (++this.packageIncrement); - pack.addClassName('package-block'); - pack.select('[data-role=package-number]')[0].update(this.packageIncrement); - this.packagesContent.insert({top: pack}); - pack.select('[data-action=package-save-items]')[0].hide(); - pack.show(); - }, - - deletePackage: function(obj) { - var pack = $(obj).up('[id^="package_block"]'); - - var packItems = pack.select('.package_items')[0]; - var packageId = this.getPackageId(pack); - - delete this.packages[packageId]; - pack.remove(); - this.messages.hide().update(); - this._setAllItemsPackedState(); - }, - - deleteItem: function(obj) { - var item = $(obj).up('tr'); - var itemId = item.select('[type="checkbox"]')[0].value; - var pack = $(obj).up('[id^="package_block"]'); - var packItems = pack.select('.package_items')[0]; - var packageId = this.getPackageId(pack); - - delete this.packages[packageId]['items'][itemId]; - if (item.offsetParent.rows.length <= 2) { /* head + this last row */ - $(packItems).hide(); - } - item.remove(); - this.messages.hide().update(); - this._recalcContainerWeightAndCustomsValue(packItems); - this._setAllItemsPackedState() - }, - - recalcContainerWeightAndCustomsValue: function(obj) { - var pack = $(obj).up('[id^="package_block"]'); - var packItems = pack.select('.package_items')[0]; - if (packItems) { + packagePrepareGrid.select('.grid tbody tr').each(function (item) { + var checkbox = item.select('[type="checkbox"]')[0]; + var itemId = checkbox.value; + var qtyValue = this._parseQty(item.select('[name="qty"]')[0]); + + item.select('[name="qty"]')[0].value = qtyValue; + + if (checkbox.checked && this._checkExceedsQty(itemId, qtyValue)) { + this.messages.show().update(this.errorQtyOverLimit); + checkExceedsQty = true; + } + }.bind(this)); + + if (checkExceedsQty) { + return; + } + if (!this.validateCustomsValue()) { return; } - this._recalcContainerWeightAndCustomsValue(packItems); - } - }, - getItemsForPack: function(obj) { - if (this.itemsGridUrl) { - var parameters = $H({'shipment_id': this.shipmentId}); - var packageBlock = $(obj).up('[id^="package_block"]'); - var packagePrapare = packageBlock.select('[data-role=package-items]')[0]; - var packagePrapareGrid = packagePrapare.select('.grid_prepare')[0]; - new Ajax.Request(this.itemsGridUrl, { - parameters: parameters, - onSuccess: function(transport) { - var response = transport.responseText; - if (response) { - packagePrapareGrid.update(response); - this.processPackagePrepare(packagePrapareGrid); - if (packagePrapareGrid.select('.grid tbody tr').length) { - packageBlock.select('[data-action=package-add-items]')[0].hide(); - packageBlock.select('[data-action=package-save-items]')[0].show(); - packagePrapare.show(); + // prepare items for packing + packagePrepareGrid.select('.grid tbody tr').each(function (item) { + var checkbox = item.select('[type="checkbox"]')[0]; + + if (checkbox.checked) { + var qty = item.select('[name="qty"]')[0]; + var qtyValue = this._parseQty(qty); + + item.select('[name="qty"]')[0].value = qtyValue; + anySelected = true; + qty.disabled = 'disabled'; + checkbox.disabled = 'disabled'; + packagePrepareGrid.select('.grid th [type="checkbox"]')[0].up('th label').hide(); + item.select('[data-action=package-delete-item]')[0].show(); + } else { + item.remove(); + } + }.bind(this)); + + // packing items + if (anySelected) { + var packItems = packageBlock.select('.package_items')[0]; + + if (!packItems) { + packagePrepare.insert(new Element('div').addClassName('grid_prepare')); + packagePrepare.insert({ + after: packagePrepareGrid + }); + packItems = packagePrepareGrid.removeClassName('grid_prepare').addClassName('package_items'); + packItems.select('.grid tbody tr').each(function (item) { + var itemId = item.select('[type="checkbox"]')[0].value; + var qtyValue = parseFloat(item.select('[name="qty"]')[0].value); + + qtyValue = qtyValue <= 0 ? 1 : qtyValue; + + if ('undefined' == typeof this.packages[packageId]) { + this.packages[packageId] = { + 'items': [], 'params': {} + }; + } + + if ('undefined' == typeof this.packages[packageId]['items'][itemId]) { + this.packages[packageId]['items'][itemId] = {}; + this.packages[packageId]['items'][itemId]['qty'] = qtyValue; } else { - packagePrapareGrid.update(); + this.packages[packageId]['items'][itemId]['qty'] += qtyValue; } - } - }.bind(this) - }); - } - }, - - getPackedItemsQty: function() { - var items = []; - for (var packageId in this.packages) { - if (!isNaN(packageId)) { - for (var packedItemId in this.packages[packageId]['items']) { - if (!isNaN(packedItemId)) { - if (items[packedItemId]) { - items[packedItemId] += this.packages[packageId]['items'][packedItemId]['qty']; - } else { - items[packedItemId] = this.packages[packageId]['items'][packedItemId]['qty'] - } - } - } - } - } - return items; - }, + }.bind(this)); + } else { + packagePrepareGrid.select('.grid tbody tr').each(function (item) { + var itemId = item.select('[type="checkbox"]')[0].value; + var qtyValue = parseFloat(item.select('[name="qty"]')[0].value); - _parseQty: function(obj) { - var qty = $(obj).hasClassName('qty-decimal') ? parseFloat(obj.value) : parseInt(obj.value); - if (isNaN(qty) || qty <= 0) { - qty = 1; - } - return qty; - }, - - packItems: function(obj) { - var anySelected = false; - var packageBlock = $(obj).up('[id^="package_block"]'); - var packageId = this.getPackageId(packageBlock); - var packagePrepare = packageBlock.select('[data-role=package-items]')[0]; - var packagePrepareGrid = packagePrepare.select('.grid_prepare')[0]; - - // check for exceeds the total shipped quantity - var checkExceedsQty = false; - this.messages.hide().update(); - packagePrepareGrid.select('.grid tbody tr').each(function(item) { - var checkbox = item.select('[type="checkbox"]')[0]; - var itemId = checkbox.value; - var qtyValue = this._parseQty(item.select('[name="qty"]')[0]); - item.select('[name="qty"]')[0].value = qtyValue; - if (checkbox.checked && this._checkExceedsQty(itemId, qtyValue)) { - this.messages.show().update(this.errorQtyOverLimit); - checkExceedsQty = true; - } - }.bind(this)); - if (checkExceedsQty) { - return; - } + qtyValue = qtyValue <= 0 ? 1 : qtyValue; - if (!this.validateCustomsValue()) { - return; - } + if ('undefined' == typeof this.packages[packageId]['items'][itemId]) { + this.packages[packageId]['items'][itemId] = {}; + this.packages[packageId]['items'][itemId]['qty'] = qtyValue; + packItems.select('.grid tbody')[0].insert(item); + } else { + this.packages[packageId]['items'][itemId]['qty'] += qtyValue; + var packItem = packItems.select('[type="checkbox"][value="' + itemId + '"]')[0].up('tr').select('[name="qty"]')[0]; - // prepare items for packing - packagePrepareGrid.select('.grid tbody tr').each(function(item) { - var checkbox = item.select('[type="checkbox"]')[0]; - if (checkbox.checked) { - var qty = item.select('[name="qty"]')[0]; - var qtyValue = this._parseQty(qty); - item.select('[name="qty"]')[0].value = qtyValue; - anySelected = true; - qty.disabled = 'disabled'; - checkbox.disabled = 'disabled'; - packagePrepareGrid.select('.grid th [type="checkbox"]')[0].up('th label').hide(); - item.select('[data-action=package-delete-item]')[0].show(); - } else { - item.remove(); - } - }.bind(this)); - - // packing items - if (anySelected) { - var packItems = packageBlock.select('.package_items')[0]; - if (!packItems) { - packagePrepare.insert(new Element('div').addClassName('grid_prepare')); - packagePrepare.insert({after: packagePrepareGrid}); - packItems = packagePrepareGrid.removeClassName('grid_prepare').addClassName('package_items'); - packItems.select('.grid tbody tr').each(function(item) { - var itemId = item.select('[type="checkbox"]')[0].value; - var qtyValue = parseFloat(item.select('[name="qty"]')[0].value); - qtyValue = (qtyValue <= 0) ? 1 : qtyValue; - - if ('undefined' == typeof this.packages[packageId]) { - this.packages[packageId] = {'items': [], 'params': {}}; - } - if ('undefined' == typeof this.packages[packageId]['items'][itemId]) { - this.packages[packageId]['items'][itemId] = {}; - this.packages[packageId]['items'][itemId]['qty'] = qtyValue; - } else { - this.packages[packageId]['items'][itemId]['qty'] += qtyValue; - } - }.bind(this)); + packItem.value = this.packages[packageId]['items'][itemId]['qty']; + } + }.bind(this)); + packagePrepareGrid.update(); + } + $(packItems).show(); + this._recalcContainerWeightAndCustomsValue(packItems); } else { - packagePrepareGrid.select('.grid tbody tr').each(function(item) { - var itemId = item.select('[type="checkbox"]')[0].value; - var qtyValue = parseFloat(item.select('[name="qty"]')[0].value); - qtyValue = (qtyValue <= 0) ? 1 : qtyValue; - - if ('undefined' == typeof this.packages[packageId]['items'][itemId]) { - this.packages[packageId]['items'][itemId] = {}; - this.packages[packageId]['items'][itemId]['qty'] = qtyValue; - packItems.select('.grid tbody')[0].insert(item); - } else { - this.packages[packageId]['items'][itemId]['qty'] += qtyValue; - var packItem = packItems.select('[type="checkbox"][value="'+itemId+'"]')[0].up('tr').select('[name="qty"]')[0]; - packItem.value = this.packages[packageId]['items'][itemId]['qty']; - } - }.bind(this)); packagePrepareGrid.update(); } - $(packItems).show(); - this._recalcContainerWeightAndCustomsValue(packItems); - } else { - packagePrepareGrid.update(); - } - // show/hide disable/enable - packagePrepare.hide(); - packageBlock.select('[data-action=package-save-items]')[0].hide(); - packageBlock.select('[data-action=package-add-items]')[0].show(); - this._setAllItemsPackedState() - }, - - validateItemQty: function (itemId, qty) { - return (this.defaultItemsQty[itemId] < qty) ? this.defaultItemsQty[itemId] : qty; - }, - - changeMeasures: function(obj) { - var incr = 0; - var incrSelected = 0; - obj.childElements().each(function(option) { - if (option.selected) { - incrSelected = incr; - } - incr++; - }.bind(this)); - - var packageBlock = $(obj).up('[id^="package_block"]'); - packageBlock.select('.measures').each(function(item){ - if (item.name != obj.name) { - var incr = 0; - item.select('option').each(function(option){ - if (incr == incrSelected) { - item.value = option.value; - //option.selected = true - } - incr++; - }.bind(this)); + // show/hide disable/enable + packagePrepare.hide(); + packageBlock.select('[data-action=package-save-items]')[0].hide(); + packageBlock.select('[data-action=package-add-items]')[0].show(); + this._setAllItemsPackedState(); + }, + + validateItemQty: function (itemId, qty) { + return this.defaultItemsQty[itemId] < qty ? this.defaultItemsQty[itemId] : qty; + }, + + changeMeasures: function (obj) { + var incr = 0; + var incrSelected = 0; + + obj.childElements().each(function (option) { + if (option.selected) { + incrSelected = incr; + } + incr++; + }); + + var packageBlock = $(obj).up('[id^="package_block"]'); + + packageBlock.select('.measures').each(function (item) { + if (item.name != obj.name) { + var incr = 0; + + item.select('option').each(function (option) { + if (incr == incrSelected) { + item.value = option.value; + //option.selected = true + } + incr++; + }); + } + }); + + }, + + checkSizeAndGirthParameter: function (obj, enabled) { + if (enabled == 0) { + return; } - }.bind(this)); + var currentNode = obj; - }, + while (currentNode.nodeName != 'TBODY') { + currentNode = currentNode.parentNode; + } - checkSizeAndGirthParameter: function(obj, enabled) { - if (enabled == 0) { - return; - } - var currentNode = obj; + if (!currentNode) { + return; + } - while (currentNode.nodeName != 'TBODY') { - currentNode = currentNode.parentNode; - } - if (!currentNode) { - return; - } + var packageSize = currentNode.select('select[name=package_size]'); + var packageContainer = currentNode.select('select[name=package_container]'); + var packageGirth = currentNode.select('input[name=container_girth]'); + var packageGirthDimensionUnits = currentNode.select('select[name=container_girth_dimension_units]'); - var packageSize = currentNode.select('select[name=package_size]'); - var packageContainer = currentNode.select('select[name=package_container]'); - var packageGirth = currentNode.select('input[name=container_girth]'); - var packageGirthDimensionUnits = currentNode.select('select[name=container_girth_dimension_units]'); + if (packageSize.length <= 0) { + return; + } - if (packageSize.length <= 0) { - return; - } + var girthEnabled = packageContainer[0].value == 'NONRECTANGULAR' || packageContainer[0].value == 'VARIABLE'; - var girthEnabled = packageContainer[0].value == 'NONRECTANGULAR' || packageContainer[0].value == 'VARIABLE'; - - if (!girthEnabled) { - packageGirth[0].value=''; - packageGirth[0].disable(); - packageGirth[0].addClassName('_disabled'); - packageGirthDimensionUnits[0].disable(); - packageGirthDimensionUnits[0].addClassName('_disabled'); - } else { - packageGirth[0].enable(); - packageGirth[0].removeClassName('_disabled'); - packageGirthDimensionUnits[0].enable(); - packageGirthDimensionUnits[0].removeClassName('_disabled'); - } + if (!girthEnabled) { + packageGirth[0].value = ''; + packageGirth[0].disable(); + packageGirth[0].addClassName('_disabled'); + packageGirthDimensionUnits[0].disable(); + packageGirthDimensionUnits[0].addClassName('_disabled'); + } else { + packageGirth[0].enable(); + packageGirth[0].removeClassName('_disabled'); + packageGirthDimensionUnits[0].enable(); + packageGirthDimensionUnits[0].removeClassName('_disabled'); + } - var sizeEnabled = (packageContainer[0].value == 'NONRECTANGULAR' || packageContainer[0].value == 'RECTANGULAR' - || packageContainer[0].value == 'VARIABLE'); - - if (!sizeEnabled) { - option = document.createElement('OPTION'); - option.value = ''; - option.text = ''; - packageSize[0].options.add(option); - packageSize[0].value = ''; - packageSize[0].disable(); - packageSize[0].addClassName('_disabled'); - } else { - for (i = 0; i < packageSize[0].length; i ++) { - if (packageSize[0].options[i].value == '') { - packageSize[0].removeChild(packageSize[0].options[i]); + var sizeEnabled = packageContainer[0].value == 'NONRECTANGULAR' || packageContainer[0].value == 'RECTANGULAR' || + packageContainer[0].value == 'VARIABLE'; + + if (!sizeEnabled) { + option = document.createElement('OPTION'); + option.value = ''; + option.text = ''; + packageSize[0].options.add(option); + packageSize[0].value = ''; + packageSize[0].disable(); + packageSize[0].addClassName('_disabled'); + } else { + for (i = 0; i < packageSize[0].length; i++) { + if (packageSize[0].options[i].value == '') { + packageSize[0].removeChild(packageSize[0].options[i]); + } } + packageSize[0].enable(); + packageSize[0].removeClassName('_disabled'); } - packageSize[0].enable(); - packageSize[0].removeClassName('_disabled'); - } - }, + }, - changeContainerType: function(obj) { - if (this.customizableContainers.length <= 0) { - return; - } + changeContainerType: function (obj) { + if (this.customizableContainers.length <= 0) { + return; + } + + var disable = true; - var disable = true; - for (var i in this.customizableContainers) { - if (this.customizableContainers[i] == obj.value) { - disable = false; - break; + for (var i in this.customizableContainers) { + if (this.customizableContainers[i] == obj.value) { + disable = false; + break; + } } - } - var currentNode = obj; - while (currentNode.nodeName != 'TBODY') { - currentNode = currentNode.parentNode; - } - if (!currentNode) { - return; - } + var currentNode = obj; + + while (currentNode.nodeName != 'TBODY') { + currentNode = currentNode.parentNode; + } + + if (!currentNode) { + return; + } + + $(currentNode).select( + 'input[name=container_length],input[name=container_width],input[name=container_height],select[name=container_dimension_units]' + ).each(function (inputElement) { + if (disable) { + Form.Element.disable(inputElement); + inputElement.addClassName('_disabled'); - $(currentNode).select( - 'input[name=container_length],input[name=container_width],input[name=container_height],select[name=container_dimension_units]' - ).each(function(inputElement) { - if (disable) { - Form.Element.disable(inputElement); - inputElement.addClassName('_disabled'); - if (inputElement.nodeName == 'INPUT') { - $(inputElement).value = '' + if (inputElement.nodeName == 'INPUT') { + $(inputElement).value = ''; + } + } else { + Form.Element.enable(inputElement); + inputElement.removeClassName('_disabled'); } + }); + }, + + changeContentTypes: function (obj) { + var packageBlock = $(obj).up('[id^="package_block"]'); + var contentType = packageBlock.select('[name=content_type]')[0]; + var contentTypeOther = packageBlock.select('[name=content_type_other]')[0]; + + if (contentType.value == 'OTHER') { + Form.Element.enable(contentTypeOther); + contentTypeOther.removeClassName('_disabled'); } else { - Form.Element.enable(inputElement); - inputElement.removeClassName('_disabled'); - } - }) - }, - - changeContentTypes: function(obj) { - var packageBlock = $(obj).up('[id^="package_block"]'); - var contentType = packageBlock.select('[name=content_type]')[0]; - var contentTypeOther = packageBlock.select('[name=content_type_other]')[0]; - if (contentType.value == 'OTHER') { - Form.Element.enable(contentTypeOther); - contentTypeOther.removeClassName('_disabled'); - } else { - Form.Element.disable(contentTypeOther); - contentTypeOther.addClassName('_disabled'); - } + Form.Element.disable(contentTypeOther); + contentTypeOther.addClassName('_disabled'); + } + + }, - }, - -//******************** Private functions **********************************// - _getItemsCount: function(items) { - var count = 0; - items.each(function(itemCount) { - if (!isNaN(itemCount)) { - count += parseFloat(itemCount); - } - }.bind(this)); - return count; - }, - - /** - * Show/hide disable/enable buttons in case of all items packed state - */ - _setAllItemsPackedState: function() { - var addPackageBtn = $$('[data-action=add-packages]')[0]; - var savePackagesBtn = $$('[data-action=save-packages]')[0]; - if (this._getItemsCount(this.itemsAll) > 0 - && (this._checkExceedsQtyFinal(this._getItemsCount(this.getPackedItemsQty()),this._getItemsCount(this.itemsAll))) - ) { - this.packagesContent.select('[data-action=package-add-items]').each(function(button){ - button.disabled = 'disabled'; - button.addClassName('_disabled'); + //******************** Private functions **********************************// + _getItemsCount: function (items) { + var count = 0; + + items.each(function (itemCount) { + if (!isNaN(itemCount)) { + count += parseFloat(itemCount); + } }); - addPackageBtn.addClassName('_disabled'); - Form.Element.disable(addPackageBtn); - savePackagesBtn.removeClassName('_disabled'); - Form.Element.enable(savePackagesBtn); - savePackagesBtn.title = ''; - - // package number recalculation - var packagesRecalc = []; - this.packagesContent.childElements().each(function(pack) { - if (!pack.select('.package_items .grid tbody tr').length) { - pack.remove(); + + return count; + }, + + /** + * Show/hide disable/enable buttons in case of all items packed state + */ + _setAllItemsPackedState: function () { + var addPackageBtn = $$('[data-action=add-packages]')[0]; + var savePackagesBtn = $$('[data-action=save-packages]')[0]; + + if (this._getItemsCount(this.itemsAll) > 0 && + this._checkExceedsQtyFinal(this._getItemsCount(this.getPackedItemsQty()), this._getItemsCount(this.itemsAll)) + ) { + this.packagesContent.select('[data-action=package-add-items]').each(function (button) { + button.disabled = 'disabled'; + button.addClassName('_disabled'); + }); + addPackageBtn.addClassName('_disabled'); + Form.Element.disable(addPackageBtn); + savePackagesBtn.removeClassName('_disabled'); + Form.Element.enable(savePackagesBtn); + savePackagesBtn.title = ''; + + // package number recalculation + var packagesRecalc = []; + + this.packagesContent.childElements().each(function (pack) { + if (!pack.select('.package_items .grid tbody tr').length) { + pack.remove(); + } + }); + var packagesCount = this.packagesContent.childElements().length; + + this.packageIncrement = packagesCount; + this.packagesContent.childElements().each(function (pack) { + var packageId = this.getPackageId(pack); + + pack.id = 'package_block_' + packagesCount; + pack.select('[data-role=package-number]')[0].update(packagesCount); + packagesRecalc[packagesCount] = this.packages[packageId]; + --packagesCount; + }.bind(this)); + this.packages = packagesRecalc; + + } else { + this.packagesContent.select('[data-action=package-add-items]').each(function (button) { + button.removeClassName('_disabled'); + Form.Element.enable(button); + }); + addPackageBtn.removeClassName('_disabled'); + Form.Element.enable(addPackageBtn); + savePackagesBtn.addClassName('_disabled'); + Form.Element.disable(savePackagesBtn); + savePackagesBtn.title = this.titleDisabledSaveBtn; + } + }, + + processPackagePrepare: function (packagePrepare) { + var itemsAll = [], + qty, + itemId, + qtyValue = 0, + value = 1; + + packagePrepare.select('.grid tbody tr').each(function (item) { + qty = item.select('[name="qty"]')[0], + itemId = item.select('[type="checkbox"]')[0].value, + qtyValue = parseFloat(qty.value); + + if (Object.isFunction(this.itemQtyCallback)) { + value = this.itemQtyCallback(itemId); + + if (typeof value !== 'undefined') { + qtyValue = parseFloat(value); + qtyValue = this.validateItemQty(itemId, qtyValue); + qty.value = qtyValue; + } + } else { + value = item.select('[name="qty"]')[0].value; + qtyValue = typeof value == 'string' && value.length == 0 ? 0 : parseFloat(value); + + if (isNaN(qtyValue) || qtyValue < 0) { + qtyValue = 1; + } + } + + if (qtyValue == 0) { + item.remove(); + + return; + } + var packedItems = this.getPackedItemsQty(); + + itemsAll[itemId] = qtyValue; + + for (var packedItemId in packedItems) { + if (!isNaN(packedItemId)) { + var packedQty = packedItems[packedItemId]; + + if (itemId == packedItemId) { + if (qtyValue == packedQty || qtyValue <= packedQty) { + item.remove(); + } else if (qtyValue > packedQty) { + /* fix float number precision */ + qty.value = Number(Number(Math.round(qtyValue - packedQty + 'e+4') + 'e-4').toFixed(4)); + } + } + } } }.bind(this)); - var packagesCount = this.packagesContent.childElements().length; - this.packageIncrement = packagesCount; - this.packagesContent.childElements().each(function(pack) { - var packageId = this.getPackageId(pack); - pack.id = 'package_block_' + packagesCount; - pack.select('[data-role=package-number]')[0].update(packagesCount); - packagesRecalc[packagesCount] = this.packages[packageId]; - --packagesCount; + + if (!this.itemsAll.length) { + this.itemsAll = itemsAll; + } + + packagePrepare.select('tbody input[type="checkbox"]').each(function (item) { + $(item).observe('change', this._observeQty); + this._observeQty.call(item); }.bind(this)); - this.packages = packagesRecalc; + }, - } else { - this.packagesContent.select('[data-action=package-add-items]').each(function(button){ - button.removeClassName('_disabled'); - Form.Element.enable(button); - }); - addPackageBtn.removeClassName('_disabled'); - Form.Element.enable(addPackageBtn); - savePackagesBtn.addClassName('_disabled'); - Form.Element.disable(savePackagesBtn); - savePackagesBtn.title = this.titleDisabledSaveBtn; - } - }, - - processPackagePrepare: function(packagePrepare) { - var itemsAll = [], - qty, - itemId, - qtyValue = 0, - value = 1; - - packagePrepare.select('.grid tbody tr').each(function(item) { - qty = item.select('[name="qty"]')[0], - itemId = item.select('[type="checkbox"]')[0].value, - qtyValue = parseFloat(qty.value); - - if (Object.isFunction(this.itemQtyCallback)) { - value = this.itemQtyCallback(itemId); - if (typeof value !== 'undefined') { - qtyValue = parseFloat(value); - qtyValue = this.validateItemQty(itemId, qtyValue); - qty.value = qtyValue; - } + _observeQty: function () { + /** this = input[type="checkbox"] */ + var tr = jQuery(this).closest('tr')[0], + qty = $(tr.cells[tr.cells.length - 1]).select('input[name="qty"]')[0]; + + if (qty.disabled = !this.checked) { + $(qty).addClassName('_disabled'); } else { - value = item.select('[name="qty"]')[0].value; - qtyValue = ((typeof value == 'string') && (value.length == 0)) ? 0 : parseFloat(value); - if (isNaN(qtyValue) || qtyValue < 0) { + $(qty).removeClassName('_disabled'); + } + }, + + _checkExceedsQty: function (itemId, qty) { + var packedItemQty = this.getPackedItemsQty()[itemId] ? this.getPackedItemsQty()[itemId] : 0; + var allItemQty = this.itemsAll[itemId]; + + return qty * (1 - this.eps) > allItemQty * (1 + this.eps) - packedItemQty * (1 - this.eps); + }, + + _checkExceedsQtyFinal: function (checkOne, defQty) { + return checkOne * (1 + this.eps) >= defQty * (1 - this.eps); + }, + + _recalcContainerWeightAndCustomsValue: function (container) { + var packageBlock = container.up('[id^="package_block"]'); + var packageId = this.getPackageId(packageBlock); + var containerWeight = packageBlock.select('[name="container_weight"]')[0]; + var containerCustomsValue = packageBlock.select('[name="package_customs_value"]')[0]; + + containerWeight.value = 0; + containerCustomsValue.value = 0; + container.select('.grid tbody tr').each(function (item) { + var itemId = item.select('[type="checkbox"]')[0].value; + var qtyValue = parseFloat(item.select('[name="qty"]')[0].value); + + if (isNaN(qtyValue) || qtyValue <= 0) { qtyValue = 1; + item.select('[name="qty"]')[0].value = qtyValue; } + var itemWeight = parseFloat(this._getElementText(item.select('[data-role=item-weight]')[0])); + + containerWeight.value = parseFloat(containerWeight.value) + itemWeight * qtyValue; + var itemCustomsValue = parseFloat(item.select('[name="customs_value"]')[0].value) || 0; + + containerCustomsValue.value = parseFloat(containerCustomsValue.value) + itemCustomsValue * qtyValue; + this.packages[packageId]['items'][itemId]['customs_value'] = itemCustomsValue; + }.bind(this)); + containerWeight.value = parseFloat(parseFloat(Math.round(containerWeight.value + 'e+4') + 'e-4').toFixed(4)); + containerCustomsValue.value = parseFloat(Math.round(containerCustomsValue.value + 'e+2') + 'e-2').toFixed(2); + + if (containerCustomsValue.value == 0) { + containerCustomsValue.value = ''; } - if (qtyValue == 0) { - item.remove(); - return; - } - var packedItems = this.getPackedItemsQty(); - itemsAll[itemId] = qtyValue; - for (var packedItemId in packedItems) { - if (!isNaN(packedItemId)) { - var packedQty = packedItems[packedItemId]; - if (itemId == packedItemId) { - if (qtyValue == packedQty || qtyValue <= packedQty) { - item.remove(); - } else if (qtyValue > packedQty) { - /* fix float number precision */ - qty.value = Number(Number(Math.round((qtyValue - packedQty) + "e+4") + "e-4").toFixed(4)); - } - } - } + }, + + _getElementText: function (el) { + if ('string' == typeof el.textContent) { + return el.textContent; } - }.bind(this)); - if (!this.itemsAll.length) { - this.itemsAll = itemsAll; - } - packagePrepare.select('tbody input[type="checkbox"]').each(function(item){ - $(item).observe('change', this._observeQty); - this._observeQty.call(item); - }.bind(this)); - }, - - _observeQty: function() { - /** this = input[type="checkbox"] */ - var tr = jQuery(this).closest('tr')[0], - qty = $(tr.cells[tr.cells.length - 1]).select('input[name="qty"]')[0]; - - if (qty.disabled = !this.checked) { - $(qty).addClassName('_disabled'); - } else { - $(qty).removeClassName('_disabled'); - } - }, - - _checkExceedsQty: function(itemId, qty) { - var packedItemQty = this.getPackedItemsQty()[itemId] ? this.getPackedItemsQty()[itemId] : 0; - var allItemQty = this.itemsAll[itemId]; - return (qty * (1 - this.eps) > (allItemQty * (1 + this.eps) - packedItemQty * (1 - this.eps))); - }, - - _checkExceedsQtyFinal: function(checkOne, defQty) { - return checkOne * (1 + this.eps) >= defQty * (1 - this.eps); - }, - - _recalcContainerWeightAndCustomsValue: function(container) { - var packageBlock = container.up('[id^="package_block"]'); - var packageId = this.getPackageId(packageBlock); - var containerWeight = packageBlock.select('[name="container_weight"]')[0]; - var containerCustomsValue = packageBlock.select('[name="package_customs_value"]')[0]; - containerWeight.value = 0; - containerCustomsValue.value = 0; - container.select('.grid tbody tr').each(function(item) { - var itemId = item.select('[type="checkbox"]')[0].value; - var qtyValue = parseFloat(item.select('[name="qty"]')[0].value); - if (isNaN(qtyValue) || qtyValue <= 0) { - qtyValue = 1; - item.select('[name="qty"]')[0].value = qtyValue; + if ('string' == typeof el.innerText) { + return el.innerText; } - var itemWeight = parseFloat(this._getElementText(item.select('[data-role=item-weight]')[0])); - containerWeight.value = parseFloat(containerWeight.value) + (itemWeight * qtyValue); - var itemCustomsValue = parseFloat(item.select('[name="customs_value"]')[0].value) || 0; - containerCustomsValue.value = parseFloat(containerCustomsValue.value) + itemCustomsValue * qtyValue; - this.packages[packageId]['items'][itemId]['customs_value'] = itemCustomsValue; - }.bind(this)); - containerWeight.value = parseFloat(parseFloat(Math.round(containerWeight.value + "e+4") + "e-4").toFixed(4)); - containerCustomsValue.value = parseFloat(Math.round(containerCustomsValue.value + "e+2") + "e-2").toFixed(2); - if (containerCustomsValue.value == 0) { - containerCustomsValue.value = ''; - } - }, - _getElementText: function(el) { - if ('string' == typeof el.textContent) { - return el.textContent; - } - if ('string' == typeof el.innerText) { - return el.innerText; + return el.innerHTML.replace(/<[^>]*>/g, ''); } - return el.innerHTML.replace(/<[^>]*>/g,''); - } -//******************** End Private functions ******************************// -}; + //******************** End Private functions ******************************// + }; }); diff --git a/app/code/Magento/Swagger/view/frontend/web/swagger-ui/js/lang/en.js b/app/code/Magento/Swagger/view/frontend/web/swagger-ui/js/lang/en.js index 776a8b72e0d6d..19282d5dff46a 100644 --- a/app/code/Magento/Swagger/view/frontend/web/swagger-ui/js/lang/en.js +++ b/app/code/Magento/Swagger/view/frontend/web/swagger-ui/js/lang/en.js @@ -1,53 +1,55 @@ -'use strict'; +/*eslint max-len: ["error", { "ignoreStrings": true }]*/ +(function () { + 'use strict'; -/* jshint quotmark: double */ -window.SwaggerTranslator.learn({ - "Warning: Deprecated":"Warning: Deprecated", - "Implementation Notes":"Implementation Notes", - "Response Class":"Response Class", - "Status":"Status", - "Parameters":"Parameters", - "Parameter":"Parameter", - "Value":"Value", - "Description":"Description", - "Parameter Type":"Parameter Type", - "Data Type":"Data Type", - "Response Messages":"Response Messages", - "HTTP Status Code":"HTTP Status Code", - "Reason":"Reason", - "Response Model":"Response Model", - "Request URL":"Request URL", - "Response Body":"Response Body", - "Response Code":"Response Code", - "Response Headers":"Response Headers", - "Hide Response":"Hide Response", - "Headers":"Headers", - "Try it out!":"Try it out!", - "Show/Hide":"Show/Hide", - "List Operations":"List Operations", - "Expand Operations":"Expand Operations", - "Raw":"Raw", - "can't parse JSON. Raw result":"can't parse JSON. Raw result", - "Model Schema":"Model Schema", - "Model":"Model", - "apply":"apply", - "Username":"Username", - "Password":"Password", - "Terms of service":"Terms of service", - "Created by":"Created by", - "See more at":"See more at", - "Contact the developer":"Contact the developer", - "api version":"api version", - "Response Content Type":"Response Content Type", - "fetching resource":"fetching resource", - "fetching resource list":"fetching resource list", - "Explore":"Explore", - "Show Swagger Petstore Example Apis":"Show Swagger Petstore Example Apis", - "Can't read from server. It may not have the appropriate access-control-origin settings.":"Can't read from server. It may not have the appropriate access-control-origin settings.", - "Please specify the protocol for":"Please specify the protocol for", - "Can't read swagger JSON from":"Can't read swagger JSON from", - "Finished Loading Resource Information. Rendering Swagger UI":"Finished Loading Resource Information. Rendering Swagger UI", - "Unable to read api":"Unable to read api", - "from path":"from path", - "server returned":"server returned" -}); + window.SwaggerTranslator.learn({ + 'Warning: Deprecated': 'Warning: Deprecated', + 'Implementation Notes': 'Implementation Notes', + 'Response Class': 'Response Class', + 'Status': 'Status', + 'Parameters': 'Parameters', + 'Parameter': 'Parameter', + 'Value': 'Value', + 'Description': 'Description', + 'Parameter Type': 'Parameter Type', + 'Data Type': 'Data Type', + 'Response Messages': 'Response Messages', + 'HTTP Status Code': 'HTTP Status Code', + 'Reason': 'Reason', + 'Response Model': 'Response Model', + 'Request URL': 'Request URL', + 'Response Body': 'Response Body', + 'Response Code': 'Response Code', + 'Response Headers': 'Response Headers', + 'Hide Response': 'Hide Response', + 'Headers': 'Headers', + 'Try it out!': 'Try it out!', + 'Show/Hide': 'Show/Hide', + 'List Operations': 'List Operations', + 'Expand Operations': 'Expand Operations', + 'Raw': 'Raw', + 'can\'t parse JSON. Raw result': 'can\'t parse JSON. Raw result', + 'Model Schema': 'Model Schema', + 'Model': 'Model', + 'apply': 'apply', + 'Username': 'Username', + 'Password': 'Password', + 'Terms of service': 'Terms of service', + 'Created by': 'Created by', + 'See more at': 'See more at', + 'Contact the developer': 'Contact the developer', + 'api version': 'api version', + 'Response Content Type': 'Response Content Type', + 'fetching resource': 'fetching resource', + 'fetching resource list': 'fetching resource list', + 'Explore': 'Explore', + 'Show Swagger Petstore Example Apis': 'Show Swagger Petstore Example Apis', + 'Can\'t read from server. It may not have the appropriate access-control-origin settings.': 'Can\'t read from server. It may not have the appropriate access-control-origin settings.', + 'Please specify the protocol for': 'Please specify the protocol for', + 'Can\'t read swagger JSON from': 'Can\'t read swagger JSON from', + 'Finished Loading Resource Information. Rendering Swagger UI': 'Finished Loading Resource Information. Rendering Swagger UI', + 'Unable to read api': 'Unable to read api', + 'from path': 'from path', + 'server returned': 'server returned' + }); +})(); diff --git a/app/code/Magento/Swagger/view/frontend/web/swagger-ui/js/lang/es.js b/app/code/Magento/Swagger/view/frontend/web/swagger-ui/js/lang/es.js index a8dff60b6a9bf..a4cc093098edb 100644 --- a/app/code/Magento/Swagger/view/frontend/web/swagger-ui/js/lang/es.js +++ b/app/code/Magento/Swagger/view/frontend/web/swagger-ui/js/lang/es.js @@ -1,52 +1,54 @@ -'use strict'; +/*eslint max-len: ["error", { "ignoreStrings": true }]*/ +(function () { + 'use strict'; -/* jshint quotmark: double */ -window.SwaggerTranslator.learn({ - "Warning: Deprecated":"Advertencia: Obsoleto", - "Implementation Notes":"Notas de implementación", - "Response Class":"Clase de la Respuesta", - "Status":"Status", - "Parameters":"Parámetros", - "Parameter":"Parámetro", - "Value":"Valor", - "Description":"Descripción", - "Parameter Type":"Tipo del Parámetro", - "Data Type":"Tipo del Dato", - "Response Messages":"Mensajes de la Respuesta", - "HTTP Status Code":"Código de Status HTTP", - "Reason":"Razón", - "Response Model":"Modelo de la Respuesta", - "Request URL":"URL de la Solicitud", - "Response Body":"Cuerpo de la Respuesta", - "Response Code":"Código de la Respuesta", - "Response Headers":"Encabezados de la Respuesta", - "Hide Response":"Ocultar Respuesta", - "Try it out!":"Pruébalo!", - "Show/Hide":"Mostrar/Ocultar", - "List Operations":"Listar Operaciones", - "Expand Operations":"Expandir Operaciones", - "Raw":"Crudo", - "can't parse JSON. Raw result":"no puede parsear el JSON. Resultado crudo", - "Model Schema":"Esquema del Modelo", - "Model":"Modelo", - "apply":"aplicar", - "Username":"Nombre de usuario", - "Password":"Contraseña", - "Terms of service":"Términos de Servicio", - "Created by":"Creado por", - "See more at":"Ver más en", - "Contact the developer":"Contactar al desarrollador", - "api version":"versión de la api", - "Response Content Type":"Tipo de Contenido (Content Type) de la Respuesta", - "fetching resource":"buscando recurso", - "fetching resource list":"buscando lista del recurso", - "Explore":"Explorar", - "Show Swagger Petstore Example Apis":"Mostrar Api Ejemplo de Swagger Petstore", - "Can't read from server. It may not have the appropriate access-control-origin settings.":"No se puede leer del servidor. Tal vez no tiene la configuración de control de acceso de origen (access-control-origin) apropiado.", - "Please specify the protocol for":"Por favor, especificar el protocola para", - "Can't read swagger JSON from":"No se puede leer el JSON de swagger desde", - "Finished Loading Resource Information. Rendering Swagger UI":"Finalizada la carga del recurso de Información. Mostrando Swagger UI", - "Unable to read api":"No se puede leer la api", - "from path":"desde ruta", - "server returned":"el servidor retornó" -}); + window.SwaggerTranslator.learn({ + 'Warning: Deprecated': 'Advertencia: Obsoleto', + 'Implementation Notes': 'Notas de implementación', + 'Response Class': 'Clase de la Respuesta', + 'Status': 'Status', + 'Parameters': 'Parámetros', + 'Parameter': 'Parámetro', + 'Value': 'Valor', + 'Description': 'Descripción', + 'Parameter Type': 'Tipo del Parámetro', + 'Data Type': 'Tipo del Dato', + 'Response Messages': 'Mensajes de la Respuesta', + 'HTTP Status Code': 'Código de Status HTTP', + 'Reason': 'Razón', + 'Response Model': 'Modelo de la Respuesta', + 'Request URL': 'URL de la Solicitud', + 'Response Body': 'Cuerpo de la Respuesta', + 'Response Code': 'Código de la Respuesta', + 'Response Headers': 'Encabezados de la Respuesta', + 'Hide Response': 'Ocultar Respuesta', + 'Try it out!': 'Pruébalo!', + 'Show/Hide': 'Mostrar/Ocultar', + 'List Operations': 'Listar Operaciones', + 'Expand Operations': 'Expandir Operaciones', + 'Raw': 'Crudo', + 'can\'t parse JSON. Raw result': 'no puede parsear el JSON. Resultado crudo', + 'Model Schema': 'Esquema del Modelo', + 'Model': 'Modelo', + 'apply': 'aplicar', + 'Username': 'Nombre de usuario', + 'Password': 'Contraseña', + 'Terms of service': 'Términos de Servicio', + 'Created by': 'Creado por', + 'See more at': 'Ver más en', + 'Contact the developer': 'Contactar al desarrollador', + 'api version': 'versión de la api', + 'Response Content Type': 'Tipo de Contenido (Content Type) de la Respuesta', + 'fetching resource': 'buscando recurso', + 'fetching resource list': 'buscando lista del recurso', + 'Explore': 'Explorar', + 'Show Swagger Petstore Example Apis': 'Mostrar Api Ejemplo de Swagger Petstore', + 'Can\'t read from server. It may not have the appropriate access-control-origin settings.': 'No se puede leer del servidor. Tal vez no tiene la configuración de control de acceso de origen (access-control-origin) apropiado.', + 'Please specify the protocol for': 'Por favor, especificar el protocola para', + 'Can\'t read swagger JSON from': 'No se puede leer el JSON de swagger desde', + 'Finished Loading Resource Information. Rendering Swagger UI': 'Finalizada la carga del recurso de Información. Mostrando Swagger UI', + 'Unable to read api': 'No se puede leer la api', + 'from path': 'desde ruta', + 'server returned': 'el servidor retornó' + }); +})(); diff --git a/app/code/Magento/Swagger/view/frontend/web/swagger-ui/js/lang/pt.js b/app/code/Magento/Swagger/view/frontend/web/swagger-ui/js/lang/pt.js index f2e7c13d41378..ab1ea7a1cd8d1 100644 --- a/app/code/Magento/Swagger/view/frontend/web/swagger-ui/js/lang/pt.js +++ b/app/code/Magento/Swagger/view/frontend/web/swagger-ui/js/lang/pt.js @@ -1,53 +1,55 @@ -'use strict'; +/*eslint max-len: ["error", { "ignoreStrings": true }]*/ +(function () { + 'use strict'; -/* jshint quotmark: double */ -window.SwaggerTranslator.learn({ - "Warning: Deprecated":"Aviso: Depreciado", - "Implementation Notes":"Notas de Implementação", - "Response Class":"Classe de resposta", - "Status":"Status", - "Parameters":"Parâmetros", - "Parameter":"Parâmetro", - "Value":"Valor", - "Description":"Descrição", - "Parameter Type":"Tipo de parâmetro", - "Data Type":"Tipo de dados", - "Response Messages":"Mensagens de resposta", - "HTTP Status Code":"Código de status HTTP", - "Reason":"Razão", - "Response Model":"Modelo resposta", - "Request URL":"URL requisição", - "Response Body":"Corpo da resposta", - "Response Code":"Código da resposta", - "Response Headers":"Cabeçalho da resposta", - "Headers":"Cabeçalhos", - "Hide Response":"Esconder resposta", - "Try it out!":"Tente agora!", - "Show/Hide":"Mostrar/Esconder", - "List Operations":"Listar operações", - "Expand Operations":"Expandir operações", - "Raw":"Cru", - "can't parse JSON. Raw result":"Falha ao analisar JSON. Resulto cru", - "Model Schema":"Modelo esquema", - "Model":"Modelo", - "apply":"Aplicar", - "Username":"Usuário", - "Password":"Senha", - "Terms of service":"Termos do serviço", - "Created by":"Criado por", - "See more at":"Veja mais em", - "Contact the developer":"Contate o desenvolvedor", - "api version":"Versão api", - "Response Content Type":"Tipo de conteúdo da resposta", - "fetching resource":"busca recurso", - "fetching resource list":"buscando lista de recursos", - "Explore":"Explorar", - "Show Swagger Petstore Example Apis":"Show Swagger Petstore Example Apis", - "Can't read from server. It may not have the appropriate access-control-origin settings.":"Não é possível ler do servidor. Pode não ter as apropriadas configurações access-control-origin", - "Please specify the protocol for":"Por favor especifique o protocolo", - "Can't read swagger JSON from":"Não é possível ler o JSON Swagger de", - "Finished Loading Resource Information. Rendering Swagger UI":"Carregar informação de recurso finalizada. Renderizando Swagger UI", - "Unable to read api":"Não foi possível ler api", - "from path":"do caminho", - "server returned":"servidor retornou" -}); + window.SwaggerTranslator.learn({ + 'Warning: Deprecated': 'Aviso: Depreciado', + 'Implementation Notes': 'Notas de Implementação', + 'Response Class': 'Classe de resposta', + 'Status': 'Status', + 'Parameters': 'Parâmetros', + 'Parameter': 'Parâmetro', + 'Value': 'Valor', + 'Description': 'Descrição', + 'Parameter Type': 'Tipo de parâmetro', + 'Data Type': 'Tipo de dados', + 'Response Messages': 'Mensagens de resposta', + 'HTTP Status Code': 'Código de status HTTP', + 'Reason': 'Razão', + 'Response Model': 'Modelo resposta', + 'Request URL': 'URL requisição', + 'Response Body': 'Corpo da resposta', + 'Response Code': 'Código da resposta', + 'Response Headers': 'Cabeçalho da resposta', + 'Headers': 'Cabeçalhos', + 'Hide Response': 'Esconder resposta', + 'Try it out!': 'Tente agora!', + 'Show/Hide': 'Mostrar/Esconder', + 'List Operations': 'Listar operações', + 'Expand Operations': 'Expandir operações', + 'Raw': 'Cru', + 'can\'t parse JSON. Raw result': 'Falha ao analisar JSON. Resulto cru', + 'Model Schema': 'Modelo esquema', + 'Model': 'Modelo', + 'apply': 'Aplicar', + 'Username': 'Usuário', + 'Password': 'Senha', + 'Terms of service': 'Termos do serviço', + 'Created by': 'Criado por', + 'See more at': 'Veja mais em', + 'Contact the developer': 'Contate o desenvolvedor', + 'api version': 'Versão api', + 'Response Content Type': 'Tipo de conteúdo da resposta', + 'fetching resource': 'busca recurso', + 'fetching resource list': 'buscando lista de recursos', + 'Explore': 'Explorar', + 'Show Swagger Petstore Example Apis': 'Show Swagger Petstore Example Apis', + 'Can\'t read from server. It may not have the appropriate access-control-origin settings.': 'Não é possível ler do servidor. Pode não ter as apropriadas configurações access-control-origin', + 'Please specify the protocol for': 'Por favor especifique o protocolo', + 'Can\'t read swagger JSON from': 'Não é possível ler o JSON Swagger de', + 'Finished Loading Resource Information. Rendering Swagger UI': 'Carregar informação de recurso finalizada. Renderizando Swagger UI', + 'Unable to read api': 'Não foi possível ler api', + 'from path': 'do caminho', + 'server returned': 'servidor retornou' + }); +})(); diff --git a/app/code/Magento/Swagger/view/frontend/web/swagger-ui/js/lang/ru.js b/app/code/Magento/Swagger/view/frontend/web/swagger-ui/js/lang/ru.js index 065100f73f99c..3d5a15e424db2 100644 --- a/app/code/Magento/Swagger/view/frontend/web/swagger-ui/js/lang/ru.js +++ b/app/code/Magento/Swagger/view/frontend/web/swagger-ui/js/lang/ru.js @@ -1,52 +1,54 @@ -'use strict'; +/*eslint max-len: ["error", { "ignoreStrings": true }]*/ +(function () { + 'use strict'; -/* jshint quotmark: double */ -window.SwaggerTranslator.learn({ - "Warning: Deprecated":"Ворнинг: Депрекейтед", - "Implementation Notes":"Заметки", - "Response Class":"Пример ответа", - "Status":"Статус", - "Parameters":"Параметры", - "Parameter":"Параметр", - "Value":"Значение", - "Description":"Описание", - "Parameter Type":"Тип параметра", - "Data Type":"Тип данных", - "HTTP Status Code":"HTTP код", - "Reason":"Причина", - "Response Model":"Структура ответа", - "Request URL":"URL запроса", - "Response Body":"Тело ответа", - "Response Code":"HTTP код ответа", - "Response Headers":"Заголовки ответа", - "Hide Response":"Спрятать ответ", - "Response Messages":"Что может прийти в ответ", - "Try it out!":"Попробовать!", - "Show/Hide":"Показать/Скрыть", - "List Operations":"Операции кратко", - "Expand Operations":"Операции подробно", - "Raw":"В сыром виде", - "can't parse JSON. Raw result":"Не удается распарсить ответ:", - "Model Schema":"Структура", - "Model":"Описание", - "apply":"применить", - "Username":"Имя пользователя", - "Password":"Пароль", - "Terms of service":"Условия использования", - "Created by":"Разработано", - "See more at":"Еще тут", - "Contact the developer":"Связаться с разработчиком", - "api version":"Версия API", - "Response Content Type":"Content Type ответа", - "fetching resource":"Получение ресурса", - "fetching resource list":"Получение ресурсов", - "Explore":"Поехали", - "Show Swagger Petstore Example Apis":"Показать примеры АПИ", - "Can't read from server. It may not have the appropriate access-control-origin settings.":"Не удается получить ответ от сервера. Возможно, какая-то лажа с настройками доступа", - "Please specify the protocol for":"Пожалуйста, укажите протогол для", - "Can't read swagger JSON from":"Не получается прочитать swagger json из", - "Finished Loading Resource Information. Rendering Swagger UI":"Загрузка информации о ресурсах завершена. Рендерим", - "Unable to read api":"Не удалось прочитать api", - "from path":"по адресу", - "server returned":"сервер сказал" -}); + window.SwaggerTranslator.learn({ + 'Warning: Deprecated': 'Ворнинг: Депрекейтед', + 'Implementation Notes': 'Заметки', + 'Response Class': 'Пример ответа', + 'Status': 'Статус', + 'Parameters': 'Параметры', + 'Parameter': 'Параметр', + 'Value': 'Значение', + 'Description': 'Описание', + 'Parameter Type': 'Тип параметра', + 'Data Type': 'Тип данных', + 'HTTP Status Code': 'HTTP код', + 'Reason': 'Причина', + 'Response Model': 'Структура ответа', + 'Request URL': 'URL запроса', + 'Response Body': 'Тело ответа', + 'Response Code': 'HTTP код ответа', + 'Response Headers': 'Заголовки ответа', + 'Hide Response': 'Спрятать ответ', + 'Response Messages': 'Что может прийти в ответ', + 'Try it out!': 'Попробовать!', + 'Show/Hide': 'Показать/Скрыть', + 'List Operations': 'Операции кратко', + 'Expand Operations': 'Операции подробно', + 'Raw': 'В сыром виде', + 'can\'t parse JSON. Raw result': 'Не удается распарсить ответ:', + 'Model Schema': 'Структура', + 'Model': 'Описание', + 'apply': 'применить', + 'Username': 'Имя пользователя', + 'Password': 'Пароль', + 'Terms of service': 'Условия использования', + 'Created by': 'Разработано', + 'See more at': 'Еще тут', + 'Contact the developer': 'Связаться с разработчиком', + 'api version': 'Версия API', + 'Response Content Type': 'Content Type ответа', + 'fetching resource': 'Получение ресурса', + 'fetching resource list': 'Получение ресурсов', + 'Explore': 'Поехали', + 'Show Swagger Petstore Example Apis': 'Показать примеры АПИ', + 'Can\'t read from server. It may not have the appropriate access-control-origin settings.': 'Не удается получить ответ от сервера. Возможно, какая-то лажа с настройками доступа', + 'Please specify the protocol for': 'Пожалуйста, укажите протогол для', + 'Can\'t read swagger JSON from': 'Не получается прочитать swagger json из', + 'Finished Loading Resource Information. Rendering Swagger UI': 'Загрузка информации о ресурсах завершена. Рендерим', + 'Unable to read api': 'Не удалось прочитать api', + 'from path': 'по адресу', + 'server returned': 'сервер сказал' + }); +})(); diff --git a/app/code/Magento/Swagger/view/frontend/web/swagger-ui/js/lang/translator.js b/app/code/Magento/Swagger/view/frontend/web/swagger-ui/js/lang/translator.js index 591f6d409430a..68c6b34d21e34 100644 --- a/app/code/Magento/Swagger/view/frontend/web/swagger-ui/js/lang/translator.js +++ b/app/code/Magento/Swagger/view/frontend/web/swagger-ui/js/lang/translator.js @@ -1,39 +1,46 @@ -'use strict'; +(function () { + 'use strict'; -/** - * Translator for documentation pages. - * - * To enable translation you should include one of language-files in your index.html - * after . - * For example - - * - * If you wish to translate some new texsts you should do two things: - * 1. Add a new phrase pair ("New Phrase": "New Translation") into your language file (for example lang/ru.js). It will be great if you add it in other language files too. - * 2. Mark that text it templates this way New Phrase or . - * The main thing here is attribute data-sw-translate. Only inner html, title-attribute and value-attribute are going to translate. - * - */ -window.SwaggerTranslator = { + /** + * Translator for documentation pages. + * + * To enable translation you should include one of language-files in your index.html + * after . + * For example - + * + * If you wish to translate some new texsts you should do two things: + * 1. Add a new phrase pair ("New Phrase": "New Translation") into your language file (for example lang/ru.js). + * It will be great if you add it in other language files too. + * 2. Mark that text it templates this way New Phrase + * or . + * The main thing here is attribute data-sw-translate. + * Only inner html, title-attribute and value-attribute are going to translate. + */ + window.SwaggerTranslator = { + _words: [], - _words:[], + /** @function translate */ + translate: function (sel) { + var $this = this; - translate: function(sel) { - var $this = this; - sel = sel || '[data-sw-translate]'; + sel = sel || '[data-sw-translate]'; - $(sel).each(function() { - $(this).html($this._tryTranslate($(this).html())); + $(sel).each(function () { + $(this).html($this._tryTranslate($(this).html())); - $(this).val($this._tryTranslate($(this).val())); - $(this).attr('title', $this._tryTranslate($(this).attr('title'))); - }); - }, + $(this).val($this._tryTranslate($(this).val())); + $(this).attr('title', $this._tryTranslate($(this).attr('title'))); + }); + }, - _tryTranslate: function(word) { - return this._words[$.trim(word)] !== undefined ? this._words[$.trim(word)] : word; - }, + /** @function translate */ + _tryTranslate: function (word) { + return this._words[$.trim(word)] !== undefined ? this._words[$.trim(word)] : word; + }, - learn: function(wordsMap) { - this._words = wordsMap; - } -}; + /** @function learn */ + learn: function (wordsMap) { + this._words = wordsMap; + } + }; +})(); diff --git a/app/code/Magento/Swagger/view/frontend/web/swagger-ui/js/magento-swagger.js b/app/code/Magento/Swagger/view/frontend/web/swagger-ui/js/magento-swagger.js index 085e313068fba..957f564715751 100644 --- a/app/code/Magento/Swagger/view/frontend/web/swagger-ui/js/magento-swagger.js +++ b/app/code/Magento/Swagger/view/frontend/web/swagger-ui/js/magento-swagger.js @@ -3,65 +3,80 @@ * See COPYING.txt for license details. */ +/*global SwaggerClient SwaggerUi initOAuth hljs*/ + /** * @api */ $(function () { + 'use strict'; + var url = $('#input_baseUrl').val(); // Pre load translate... - if(window.SwaggerTranslator) { + if (window.SwaggerTranslator) { window.SwaggerTranslator.translate(); } + + /** @function addApiKeyAuthorization */ + function addApiKeyAuthorization() { + var key = encodeURIComponent($('#input_apiKey')[0].value); + + if (key && key.trim() !== '') { + window.swaggerUi.api.clientAuthorizations.add( + 'apiKeyAuth', + new SwaggerClient.ApiKeyAuthorization('Authorization', 'Bearer ' + key, 'header') + ); + } + } + + /** @function log */ + function log() { + if ('console' in window) { + console.log.apply(console, arguments); + } + } + window.swaggerUi = new SwaggerUi({ url: url, - dom_id: "swagger-ui-container", + // jscs:disable requireCamelCaseOrUpperCaseIdentifiers + dom_id: 'swagger-ui-container', + // jscs:enable requireCamelCaseOrUpperCaseIdentifiers supportedSubmitMethods: ['get', 'post', 'put', 'delete', 'patch'], - onComplete: function(swaggerApi, swaggerUi){ - if(typeof initOAuth == "function") { + + /** @function onComplete */ + onComplete: function () { + if (typeof initOAuth == 'function') { initOAuth({ - clientId: "your-client-id", - clientSecret: "your-client-secret", - realm: "your-realms", - appName: "your-app-name", - scopeSeparator: "," + clientId: 'your-client-id', + clientSecret: 'your-client-secret', + realm: 'your-realms', + appName: 'your-app-name', + scopeSeparator: ',' }); } - if(window.SwaggerTranslator) { + if (window.SwaggerTranslator) { window.SwaggerTranslator.translate(); } - $('pre code').each(function(i, e) { - hljs.highlightBlock(e) + $('pre code').each(function (i, e) { + hljs.highlightBlock(e); }); addApiKeyAuthorization(); }, - onFailure: function(data) { - log("Unable to Load SwaggerUI"); + + /** @function onFailure */ + onFailure: function () { + log('Unable to Load SwaggerUI'); }, - docExpansion: "none", - apisSorter: "alpha", + docExpansion: 'none', + apisSorter: 'alpha', showRequestHeaders: false }); - function addApiKeyAuthorization(){ - var key = encodeURIComponent($('#input_apiKey')[0].value); - if(key && key.trim() != "") { - var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization("Authorization", "Bearer " + key, "header"); - window.swaggerUi.api.clientAuthorizations.add("apiKeyAuth", apiKeyAuth); - } - } - $('#input_apiKey').change(addApiKeyAuthorization); - window.swaggerUi.load(); - - function log() { - if ('console' in window) { - console.log.apply(console, arguments); - } - } }); diff --git a/app/code/Magento/Swagger/view/frontend/web/swagger-ui/js/swagger-ui.js b/app/code/Magento/Swagger/view/frontend/web/swagger-ui/js/swagger-ui.js index f2406777b48fd..0871be58da64b 100644 --- a/app/code/Magento/Swagger/view/frontend/web/swagger-ui/js/swagger-ui.js +++ b/app/code/Magento/Swagger/view/frontend/web/swagger-ui/js/swagger-ui.js @@ -8,63 +8,106 @@ * * Modified by Magento, Modifications Copyright © Magento. */ -(function(){this["Handlebars"] = this["Handlebars"] || {}; - this["Handlebars"]["templates"] = this["Handlebars"]["templates"] || {}; - this["Handlebars"]["templates"]["apikey_button_view"] = Handlebars.template({"compiler":[6,">= 2.0.0-beta.1"],"main":function(depth0,helpers,partials,data) { - var helper, functionType="function", helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression; - return "\n\n \n " - + escapeExpression(((helper = (helper = helpers.keyName || (depth0 != null ? depth0.keyName : depth0)) != null ? helper : helperMissing),(typeof helper === functionType ? helper.call(depth0, {"name":"keyName","hash":{},"data":data}) : helper))) - + "\n \n apply\n \n\n"; - },"useData":true}); - this["Handlebars"]["templates"]["basic_auth_button_view"] = Handlebars.template({"compiler":[6,">= 2.0.0-beta.1"],"main":function(depth0,helpers,partials,data) { - return "\n\n \n Username\n \n Password\n \n apply\n \n\n\n"; - },"useData":true}); - this["Handlebars"]["templates"]["content_type"] = Handlebars.template({"1":function(depth0,helpers,partials,data) { - var stack1, buffer = ""; - stack1 = helpers.each.call(depth0, (depth0 != null ? depth0.produces : depth0), {"name":"each","hash":{},"fn":this.program(2, data),"inverse":this.noop,"data":data}); - if (stack1 != null) { buffer += stack1; } - return buffer; - },"2":function(depth0,helpers,partials,data) { - var stack1, lambda=this.lambda, buffer = " "; - stack1 = lambda(depth0, depth0); - if (stack1 != null) { buffer += stack1; } - return buffer + "\n"; - },"4":function(depth0,helpers,partials,data) { - return " application/json\n"; - },"compiler":[6,">= 2.0.0-beta.1"],"main":function(depth0,helpers,partials,data) { - var stack1, helper, functionType="function", helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression, buffer = "Response Content Type\n\n"; - stack1 = helpers['if'].call(depth0, (depth0 != null ? depth0.produces : depth0), {"name":"if","hash":{},"fn":this.program(1, data),"inverse":this.program(4, data),"data":data}); - if (stack1 != null) { buffer += stack1; } - return buffer + "\n"; - },"useData":true}); - 'use strict'; +(function () { + this['Handlebars'] = this['Handlebars'] || {}; + this['Handlebars']['templates'] = this['Handlebars']['templates'] || {}; + this['Handlebars']['templates']['apikey_button_view'] = Handlebars.template({ + 'compiler': [6,'>= 2.0.0-beta.1'],'main': function (depth0, helpers, partials, data) { + var helper, functionType = 'function', + helperMissing = helpers.helperMissing, + escapeExpression = this.escapeExpression; + + return '\n\n \n ' + + escapeExpression((helper = (helper = helpers.keyName || (depth0 != null ? depth0.keyName : depth0)) != null ? helper : helperMissing,typeof helper === functionType ? helper.call(depth0, { + 'name': 'keyName','hash': {},'data': data + }) : helper)) + + '\n \n apply\n \n\n'; + },'useData': true + }); + this['Handlebars']['templates']['basic_auth_button_view'] = Handlebars.template({ + 'compiler': [6,'>= 2.0.0-beta.1'],'main': function (depth0, helpers, partials, data) { + return '\n\n \n Username\n \n Password\n \n apply\n \n\n\n'; + },'useData': true + }); + this['Handlebars']['templates']['content_type'] = Handlebars.template({ + '1': function (depth0, helpers, partials, data) { + var stack1, buffer = ''; + + stack1 = helpers.each.call(depth0, depth0 != null ? depth0.produces : depth0, { + 'name': 'each','hash': {},'fn': this.program(2, data),'inverse': this.noop,'data': data + }); + + if (stack1 != null) { + buffer += stack1; + } + + return buffer; + },'2': function (depth0, helpers, partials, data) { + var stack1, lambda = this.lambda, + buffer = ' '; + stack1 = lambda(depth0, depth0); + + if (stack1 != null) { + buffer += stack1; + } + + return buffer + '\n'; + },'4': function (depth0, helpers, partials, data) { + return ' application/json\n'; + },'compiler': [6,'>= 2.0.0-beta.1'],'main': function (depth0, helpers, partials, data) { + var stack1, helper, functionType = 'function', + helperMissing = helpers.helperMissing, + escapeExpression = this.escapeExpression, + buffer = 'Response Content Type\n\n'; + + stack1 = helpers['if'].call(depth0, depth0 != null ? depth0.produces : depth0, { + 'name': 'if','hash': {},'fn': this.program(1, data),'inverse': this.program(4, data),'data': data + }); + if (stack1 != null) { + buffer += stack1; + } + + return buffer + '\n'; + },'useData': true + }); + 'use strict'; - $(function() { + $(function () { // Helper function for vertically aligning DOM elements // http://www.seodenver.com/simple-vertical-align-plugin-for-jquery/ - $.fn.vAlign = function() { - return this.each(function(){ + $.fn.vAlign = function () { + return this.each(function () { var ah = $(this).height(); var ph = $(this).parent().height(); var mh = (ph - ah) / 2; + $(this).css('margin-top', mh); }); }; - $.fn.stretchFormtasticInputWidthToParent = function() { - return this.each(function(){ - var p_width = $(this).closest("form").innerWidth(); - var p_padding = parseInt($(this).closest("form").css('padding-left') ,10) + parseInt($(this).closest('form').css('padding-right'), 10); + $.fn.stretchFormtasticInputWidthToParent = function () { + return this.each(function () { + var p_width = $(this).closest('form').innerWidth(); + var p_padding = parseInt($(this).closest('form').css('padding-left'), 10) + parseInt($(this).closest('form').css('padding-right'), 10); var this_padding = parseInt($(this).css('padding-left'), 10) + parseInt($(this).css('padding-right'), 10); + $(this).css('width', p_width - p_padding - this_padding); }); }; @@ -76,12 +119,12 @@ $('ul.downplayed li div.content p').vAlign(); // When a sandbox form is submitted.. - $("form.sandbox").submit(function(){ + $('form.sandbox').submit(function () { var error_free = true; // Cycle through the forms required inputs - $(this).find("input.required").each(function() { + $(this).find('input.required').each(function () { // Remove any existing error styles from the input $(this).removeClass('error'); @@ -110,19 +153,20 @@ // 500)) } -// Logging function that accounts for browsers that don't have window.console - function log(){ + // Logging function that accounts for browsers that don't have window.console + function log() { log.history = log.history || []; log.history.push(arguments); - if(this.console){ - console.log( Array.prototype.slice.call(arguments)[0] ); + + if (this.console) { + console.log(Array.prototype.slice.call(arguments)[0]); } } -// Handle browsers that do console incorrectly (IE9 and below, see http://stackoverflow.com/a/5539378/7913) - if (Function.prototype.bind && console && typeof console.log === "object") { + // Handle browsers that do console incorrectly (IE9 and below, see http://stackoverflow.com/a/5539378/7913) + if (Function.prototype.bind && console && typeof console.log === 'object') { [ - "log","info","warn","error","assert","dir","clear","profile","profileEnd" + 'log','info','warn','error','assert','dir','clear','profile','profileEnd' ].forEach(function (method) { console[method] = this.bind(console[method], console); }, Function.prototype.call); @@ -130,11 +174,12 @@ window.Docs = { - shebang: function() { + shebang: function () { // If shebang has an operation nickname in it.. // e.g. /docs/#!/words/get_search var fragments = $.param.fragment().split('/'); + fragments.shift(); // get rid of the bang switch (fragments.length) { @@ -144,30 +189,37 @@ var dom_id = 'resource_' + fragments[0]; Docs.expandEndpointListForResource(fragments[0]); - $("#"+dom_id).slideto({highlight: false}); + $('#' + dom_id).slideto({ + highlight: false + }); } break; + case 2: // Refer to the endpoint DOM element, e.g. #words_get_search // Expand Resource Docs.expandEndpointListForResource(fragments[0]); - $("#"+dom_id).slideto({highlight: false}); + $('#' + dom_id).slideto({ + highlight: false + }); // Expand operation var li_dom_id = fragments.join('_'); - var li_content_dom_id = li_dom_id + "_content"; - + var li_content_dom_id = li_dom_id + '_content'; - Docs.expandOperation($('#'+li_content_dom_id)); - $('#'+li_dom_id).slideto({highlight: false}); + Docs.expandOperation($('#' + li_content_dom_id)); + $('#' + li_dom_id).slideto({ + highlight: false + }); break; } }, - toggleEndpointListForResource: function(resource) { + toggleEndpointListForResource: function (resource) { var elem = $('li#resource_' + Docs.escapeResourceName(resource) + ' ul.endpoints'); + if (elem.is(':visible')) { Docs.collapseEndpointListForResource(resource); } else { @@ -176,91 +228,101 @@ }, // Expand resource - expandEndpointListForResource: function(resource) { + expandEndpointListForResource: function (resource) { var resource = Docs.escapeResourceName(resource); + if (resource == '') { $('.resource ul.endpoints').slideDown(); + return; } $('li#resource_' + resource).addClass('active'); var elem = $('li#resource_' + resource + ' ul.endpoints'); + elem.slideDown(); }, // Collapse resource and mark as explicitly closed - collapseEndpointListForResource: function(resource) { + collapseEndpointListForResource: function (resource) { var resource = Docs.escapeResourceName(resource); + if (resource == '') { $('.resource ul.endpoints').slideUp(); + return; } $('li#resource_' + resource).removeClass('active'); var elem = $('li#resource_' + resource + ' ul.endpoints'); + elem.slideUp(); }, - expandOperationsForResource: function(resource) { + expandOperationsForResource: function (resource) { // Make sure the resource container is open.. Docs.expandEndpointListForResource(resource); if (resource == '') { $('.resource ul.endpoints li.operation div.content').slideDown(); + return; } - $('li#resource_' + Docs.escapeResourceName(resource) + ' li.operation div.content').each(function() { + $('li#resource_' + Docs.escapeResourceName(resource) + ' li.operation div.content').each(function () { Docs.expandOperation($(this)); }); }, - collapseOperationsForResource: function(resource) { + collapseOperationsForResource: function (resource) { // Make sure the resource container is open.. Docs.expandEndpointListForResource(resource); if (resource == '') { $('.resource ul.endpoints li.operation div.content').slideUp(); + return; } - $('li#resource_' + Docs.escapeResourceName(resource) + ' li.operation div.content').each(function() { + $('li#resource_' + Docs.escapeResourceName(resource) + ' li.operation div.content').each(function () { Docs.collapseOperation($(this)); }); }, - escapeResourceName: function(resource) { - return resource.replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]\^`{|}~]/g, "\\$&"); + escapeResourceName: function (resource) { + return resource.replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]\^`{|}~]/g, '\\$&'); }, - expandOperation: function(elem) { + expandOperation: function (elem) { elem.slideDown(); }, - collapseOperation: function(elem) { + collapseOperation: function (elem) { elem.slideUp(); } }; 'use strict'; - Handlebars.registerHelper('sanitize', function(html) { + Handlebars.registerHelper('sanitize', function (html) { // Strip the script tags from the html, and return it as a Handlebars.SafeString html = html.replace(/