(function (ns) { ns.Form = qs.createObject(); ns.Form.prototype = { initialize: function (options) { this.options = options; this.className = 'app.user.form'; this.namespace = 'userForm'; if (this.initElements()) { this.initEvents(); } return this; }, initElements: function () { this.form = $('#' + this.options.formId); if (!$(this.form).size()) { this.showError('Form "' + this.options.formId + '" not found.'); return false; } this.element = {}; for (var name in {'firstName': '', 'lastName': '', 'email': ''}) { this.element[name] = $('[name=' + name + ']', this.form); if (!$(this.form).size()) { this.showError('Element "' + name + '" not found'); return false; } } return true; }, initEvents: function () { this.element.firstName.bind('blur.' + this.namespace, _.bind(this.onBlur, this, 'firstName')); this.element.lastName.bind('blur.' + this.namespace, _.bind(this.onBlur, this, 'lastName')); this.element.email.bind('blur.' + this.namespace, _.bind(this.onBlur, this, 'email')); for (var i = 0; i < this.options.addressTypes.length; i++) { var type = this.options.addressTypes[i]; var asBilling = $('[name="' + type + '[asBilling]"]', this.form); if (asBilling.size()) { asBilling.bind('change.' + this.namespace, _.bind(this.onAsBillingClick, this, asBilling, type)); this.onAsBillingClick(asBilling, type); } } return this; }, onAsBillingClick: function (asBilling, type, event) { for (var i = 0; i < this.options.addressFields.length; i++) { var name = this.options.addressFields[i]; var idTpl = type + '-' + name + '-'; var selector = '#' + idTpl + 'label, #' + idTpl + 'element'; if ($(asBilling).is(':checked')) { $(selector).addClass('hidden'); } else { $(selector).removeClass('hidden'); if (undefined != event && 'change' == event.type && !this.getElementValue(type, name)) { this.setElementValue(type, name, this.getElementValue(this.options.inheritedAddress, name)); } } } return true; }, onBlur: function (name) { var value = $(this.element[name]).val(); if (value && !this.getElementValue(this.options.inheritedAddress, name)) { this.setElementValue(this.options.inheritedAddress, name, value); } return this; }, getElementValue: function (type, name) { return $('#' + type + '-' + name, this.form).val(); }, setElementValue: function (type, name, value) { $('#' + type + '-' + name, this.form).val(value); }, showError: function (error) { alert(this.className + ' can not be initialized. ' + error); return this; } }; })(qs.defineNS('app.user'));