(function(ns) { "use strict"; /** * @alias app.company.admin.Form * @constructor */ ns.Form = function () { this.construct.apply(this, arguments); }; ns.Form.prototype.construct = function (options) { this.eventNS = 'companyAdmin'; this.options = $.extend({ typeField: '', utilityCategoryField: '', associateCategoryField: '', districtDataUrl: '', districtFields: [], districtAutocompleteOptions: { } }, options); this.form = $('#' + this.options.formId); if (!this.form.length) { return false; } this.form.defaultHint(this.options.hintOptions); this.typeFields = $('[name=' + this.options.typeField + ']', this.form); this.associateCategoryLabel = $('#' + this.options.associateCategoryField + '-label label'); this.initDistrictFields(); this.initTypeField(); return true; }; ns.Form.prototype.initDistrictFields = function () { if (!this.options.districtFields.length || !this.options.districtDataUrl) { return false; } var obj = this; for (var i in this.options.districtFields) { $('#' + this.options.districtFields[i]) .bind('keydown.' + this.eventNS, function (event) { /* don't navigate away from the field on tab when selecting an item */ if ( event.keyCode === $.ui.keyCode.TAB && $(this).data("ui-autocomplete" ).menu.active ) { event.preventDefault(); } }) .bind('focus.' + this.eventNS, function (event) { var val = $(this).val(); if (val) { $(this).val(_.str.trim(val, ', ') + ', '); } $(this).autocomplete('search', $(this).val()); }) .bind('blur.' + this.eventNS, function (event) { $(this).val(_.str.trim($(this).val(), ', ')); }) .autocomplete({ minLength: 0, source: function (request, response) { $.ajax(obj.options.districtDataUrl, { dataType: "json", data: { term: request.term, districtType: this.element.data('type') } }).done(response); }, focus: function () { /* prevent value inserted on focus */ return false; }, select: function(event, ui) { var terms = this.value.split( /[,\s]+/ ); /* remove the current input */ terms.pop(); /* add the selected item */ terms.push(ui.item.value); this.value = terms.join(', '); return false; } }); } return true; }; ns.Form.prototype.initTypeField = function () { this.typeFields.bind('click.' + this.eventNS, _.bind(this.onTypeChanged, this)); this.onTypeChanged(); }; ns.Form.prototype.onTypeChanged = function () { this.associateCategoryLabel.removeClass('required'); var positionLabel = $('#position-label > label'); switch (this.typeFields.filter(':checked').val()) { case 'vendor': this.associateCategoryLabel.addClass('required'); break; case 'associate': positionLabel.switchClass('required', 'optional'); break; default: positionLabel.switchClass('optional', 'required'); break; } }; })(qs.defineNS('app.company.admin'));