var App_User_Form = qs.createObject(); App_User_Form.prototype = { initialize: function (options) { this.className = 'App_User_Form'; this.namespace = 'userForm'; this.options = $.extend({}, options); 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) { 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 (!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; } };