<commit_before>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var App = require('app');

module.exports = App.WizardRoute.extend({
  route: '/service/reassign',

  leaveWizard: function (router, context) {
    var reassignMasterController = router.get('reassignMasterController');
    App.router.get('updateController').set('isWorking', true);
    reassignMasterController.finish();
    App.clusterStatus.setClusterStatus({
      clusterName: App.router.get('content.cluster.name'),
      clusterState: 'DEFAULT',
      localdb: App.db.data
    }, {alwaysCallback: function () {
      context.hide();
      router.transitionTo('main.index');
      location.reload();
    }});
  },

  enter: function (router) {
    console.log('in /service/reassign:enter');
    var context = this;
    var reassignMasterController = router.get('reassignMasterController');

    reassignMasterController.dataLoading().done(function () {
      if (App.router.get('mainHostController.hostsCountMap.TOTAL') > 1) {
        Em.run.next(function () {
          App.router.get('updateController').set('isWorking', false);
          var popup = App.ModalPopup.show({
            classNames: ['full-width-modal'],
            header: Em.I18n.t('services.reassign.header'),
            bodyClass: App.ReassignMasterView.extend({
              controller: reassignMasterController
            }),
            primary: Em.I18n.t('form.cancel'),
            showFooter: false,
            secondary: null,

            onPrimary: function () {
              this.hide();
              App.router.get('updateController').set('isWorking', true);
              App.router.transitionTo('main.services.index');
            },
            onClose: function () {
              var currStep = reassignMasterController.get('currentStep');
              if (parseInt(currStep) > 3) {
                var self = this;

                var step4Controller = router.get('reassignMasterWizardStep4Controller');
                var testDBTaskId = step4Controller.get('tasks').filterProperty('command', 'testDBConnection').get('firstObject.id');

                if(currStep !== "7"
                   && testDBTaskId
                   && reassignMasterController.get('content.tasksStatuses').get(testDBTaskId) === "FAILED")
                {
                  App.showConfirmationPopup(function () {
                    App.router.transitionTo('step7');
                  }, Em.I18n.t('services.reassign.rollback.confirm'));
                } else {
                  App.showConfirmationPopup(function () {
                    router.get('reassignMasterWizardStep' + currStep + 'Controller').removeObserver('tasks.@each.status', this, 'onTaskStatusChange');
                    context.leaveWizard(router, self);
                  }, Em.I18n.t('services.reassign.closePopup').format(reassignMasterController.get('content.reassign.display_name')));
                }
              } else {
                context.leaveWizard(router, this);
              }
            },
            didInsertElement: function () {
              this.fitHeight();
            }
          });
          reassignMasterController.set('popup', popup);
          reassignMasterController.loadSecurityEnabled();
          reassignMasterController.loadComponentToReassign();
          var currStep = reassignMasterController.get('currentStep');
          var currentClusterStatus = App.clusterStatus.get('value');
          if (currentClusterStatus) {
            switch (currentClusterStatus.clusterState) {
              case 'REASSIGN_MASTER_INSTALLING' :
                if (currentClusterStatus.localdb.ReassignMaster.currentStep !== currStep) {
                  reassignMasterController.setCurrentStep(currentClusterStatus.localdb.ReassignMaster.currentStep);
                }
                break;
            }
          }
          router.transitionTo('step' + currStep);
        });
      } else {
        App.showAlertPopup(Em.I18n.t('common.error'), Em.I18n.t('services.reassign.error.fewHosts'), function () {
          router.transitionTo('main.services.index');
        })
      }
    });
  },

  step1: Em.Route.extend({
    route: '/step1',
    connectOutlets: function (router) {
      console.log('in reassignMaster.step1:connectOutlets');
      var controller = router.get('reassignMasterController');
      var step1Controller = router.get('reassignMasterWizardStep1Controller');
      controller.setCurrentStep('1');
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('reassignMasterWizardStep1', controller.get('content'));
        step1Controller.loadConfigsTags();
      })
    },
    next: function (router) {
      var controller = router.get('reassignMasterController');
      App.db.setMasterComponentHosts(undefined);
      controller.clearMasterComponentHosts();
      router.transitionTo('step2');
    },

    unroutePath: function () {
      return false;
    }
  }),

  step2: Em.Route.extend({
    route: '/step2',
    connectOutlets: function (router) {
      console.log('in reassignMaster.step2:connectOutlets');
      var controller = router.get('reassignMasterController');
      controller.setCurrentStep('2');
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('reassignMasterWizardStep2', controller.get('content'));
      })

    },
    back: Em.Router.transitionTo('step1'),
    next: function (router) {
      var controller = router.get('reassignMasterController');
      var reassignMasterWizardStep2 = router.get('reassignMasterWizardStep2Controller');
      controller.saveMasterComponentHosts(reassignMasterWizardStep2);
      var reassignHosts = {};
      var componentName = reassignMasterWizardStep2.get('content.reassign.component_name');
      var masterAssignmentsHosts = reassignMasterWizardStep2.get('selectedServicesMasters').filterProperty('component_name', componentName).mapProperty('selectedHost');
      var currentMasterHosts = App.HostComponent.find().filterProperty('componentName', componentName).mapProperty('hostName');
      masterAssignmentsHosts.forEach(function (host) {
        if (!currentMasterHosts.contains(host)) {
          reassignHosts.target = host;
        }
      }, this);
      currentMasterHosts.forEach(function (host) {
        if (!masterAssignmentsHosts.contains(host)) {
          reassignHosts.source = host;
        }
      }, this);
      controller.saveReassignHosts(reassignHosts);
      router.transitionTo('step3');
    },

    unroutePath: function () {
      return false;
    }
  }),

  step3: Em.Route.extend({
    route: '/step3',
    connectOutlets: function (router) {
      console.log('in reassignMaster.step3:connectOutlets');
      var controller = router.get('reassignMasterController');
      controller.setCurrentStep('3');
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('reassignMasterWizardStep3', controller.get('content'));
      })
    },
    back: Em.Router.transitionTo('step2'),
    next: function (router) {
      App.db.setReassignTasksStatuses(undefined);
      App.db.setReassignTasksRequestIds(undefined);
      App.clusterStatus.setClusterStatus({
        clusterName: router.get('reassignMasterController.content.cluster.name'),
        clusterState: 'REASSIGN_MASTER_INSTALLING',
        wizardControllerName: 'reassignMasterController',
        localdb: App.db.data
      });
      router.transitionTo('step4');
    },

    unroutePath: function () {
      return false;
    }
  }),

  step4: Em.Route.extend({
    route: '/step4',
    connectOutlets: function (router) {
      console.log('in reassignMaster.step4:connectOutlets');
      var controller = router.get('reassignMasterController');
      controller.setCurrentStep('4');
      controller.setLowerStepsDisable(4);
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('reassignMasterWizardStep4', controller.get('content'));
      })
    },
    next: function (router) {
      router.get('reassignMasterController').setCurrentStep('5');

      App.clusterStatus.setClusterStatus({
        clusterName: router.get('reassignMasterController.content.cluster.name'),
        clusterState: 'REASSIGN_MASTER_INSTALLING',
        wizardControllerName: 'reassignMasterController',
        localdb: App.db.data
      });

      router.transitionTo('step5');
    },

    complete: function (router) {
      var controller = router.get('reassignMasterController');
      var reassignMasterWizardStep4 = router.get('reassignMasterWizardStep4Controller');
      if (!reassignMasterWizardStep4.get('isSubmitDisabled')) {
        controller.finish();
        controller.get('popup').hide();
        App.clusterStatus.setClusterStatus({
          clusterName: router.get('reassignMasterController.content.cluster.name'),
          clusterState: 'DEFAULT',
          localdb: App.db.data
        }, {alwaysCallback: function () {
          controller.get('popup').hide();
          router.transitionTo('main.index');
          location.reload();
        }});
      }
    },

    unroutePath: function () {
      return false;
    }
  }),

  step5: Em.Route.extend({
    route: '/step5',
    connectOutlets: function (router) {
      console.log('in reassignMaster.step5:connectOutlets');
      var controller = router.get('reassignMasterController');
      controller.setCurrentStep('5');
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.setLowerStepsDisable(5);
        if ((controller.get('content.reassign.component_name') === 'NAMENODE') || controller.get('content.reassign.component_name') === 'SECONDARY_NAMENODE') {
          controller.usersLoading().done(function () {
            controller.connectOutlet('reassignMasterWizardStep5', controller.get('content'));
          })
        } else {
          controller.connectOutlet('reassignMasterWizardStep5', controller.get('content'));
        }
      })
    },
    next: function (router) {
      App.showConfirmationPopup(function () {
        router.transitionTo('step6');
      }, Em.I18n.t('services.reassign.step5.confirmPopup.body'));
    },

    unroutePath: function () {
      return false;
    }
  }),

  step6: Em.Route.extend({
    route: '/step6',
    connectOutlets: function (router) {
      console.log('in reassignMaster.step6:connectOutlets');
      var controller = router.get('reassignMasterController');
      controller.setCurrentStep('6');
      controller.setLowerStepsDisable(6);
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('reassignMasterWizardStep6', controller.get('content'));
      })
    },

    next: function (router) {
      var controller = router.get('reassignMasterController');
      var reassignMasterWizardStep6 = router.get('reassignMasterWizardStep6Controller');
      if (!reassignMasterWizardStep6.get('isSubmitDisabled')) {
        controller.finish();
        controller.get('popup').hide();
        App.clusterStatus.setClusterStatus({
          clusterName: router.get('reassignMasterController.content.cluster.name'),
          clusterState: 'DEFAULT',
          localdb: App.db.data
        }, {alwaysCallback: function () {
          controller.get('popup').hide();
          router.transitionTo('main.index');
          location.reload();
        }});
      }
    },

    unroutePath: function () {
      return false;
    }
  }),

  step7: Em.Route.extend({
    route: '/step7',
    connectOutlets: function (router) {
      console.log('in reassignMaster.step7:connectOutlets');
      var controller = router.get('reassignMasterController');
      controller.setCurrentStep('7');
      controller.setLowerStepsDisable(7);
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('reassignMasterWizardStep7', controller.get('content'));
      });
    },

    next: function (router) {
      var controller = router.get('reassignMasterController');
      var reassignMasterWizardStep7 = router.get('reassignMasterWizardStep7Controller');
      if (!reassignMasterWizardStep7.get('isSubmitDisabled')) {
        controller.finish();
        controller.get('popup').hide();
        App.clusterStatus.setClusterStatus({
          clusterName: router.get('reassignMasterController.content.cluster.name'),
          clusterState: 'DEFAULT',
          localdb: App.db.data
        }, {alwaysCallback: function () {
          controller.get('popup').hide();
          router.transitionTo('main.index');
          location.reload();
        }});
      }
    },

    complete: function (router) {
      var controller = router.get('reassignMasterController');
      var reassignMasterWizardStep7 = router.get('reassignMasterWizardStep7Controller');
      if (!reassignMasterWizardStep7.get('isSubmitDisabled')) {
        controller.finish();
        controller.get('popup').hide();
        App.clusterStatus.setClusterStatus({
          clusterName: router.get('reassignMasterController.content.cluster.name'),
          clusterState: 'DEFAULT',
          localdb: App.db.data
        }, {alwaysCallback: function () {
          controller.get('popup').hide();
          router.transitionTo('main.index');
          location.reload();
        }});
      }
    },

    unroutePath: function () {
      return false;
    }
  }),

  gotoStep7: Em.Router.transitionTo('step7'),

  backToServices: function (router) {
    App.router.get('updateController').set('isWorking', true);
    router.transitionTo('services');
  }

});
<commit_msg>AMBARI-12509. Move Wizard is not working due to JS error. (jaimin)<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var App = require('app');

module.exports = App.WizardRoute.extend({
  route: '/service/reassign',

  leaveWizard: function (router, context) {
    var reassignMasterController = router.get('reassignMasterController');
    App.router.get('updateController').set('isWorking', true);
    reassignMasterController.finish();
    App.clusterStatus.setClusterStatus({
      clusterName: App.router.get('content.cluster.name'),
      clusterState: 'DEFAULT',
      localdb: App.db.data
    }, {alwaysCallback: function () {
      context.hide();
      router.transitionTo('main.index');
      location.reload();
    }});
  },

  enter: function (router) {
    console.log('in /service/reassign:enter');
    var context = this;
    var reassignMasterController = router.get('reassignMasterController');

    reassignMasterController.dataLoading().done(function () {
      if (App.router.get('mainHostController.hostsCountMap.TOTAL') > 1) {
        Em.run.next(function () {
          App.router.get('updateController').set('isWorking', false);
          var popup = App.ModalPopup.show({
            classNames: ['full-width-modal'],
            header: Em.I18n.t('services.reassign.header'),
            bodyClass: App.ReassignMasterView.extend({
              controller: reassignMasterController
            }),
            primary: Em.I18n.t('form.cancel'),
            showFooter: false,
            secondary: null,

            onPrimary: function () {
              this.hide();
              App.router.get('updateController').set('isWorking', true);
              App.router.transitionTo('main.services.index');
            },
            onClose: function () {
              var currStep = reassignMasterController.get('currentStep');
              if (parseInt(currStep) > 3) {
                var self = this;

                var step4Controller = router.get('reassignMasterWizardStep4Controller');
                var testDBTaskId = step4Controller.get('tasks').filterProperty('command', 'testDBConnection').get('firstObject.id');

                if(currStep !== "7"
                   && testDBTaskId
                   && reassignMasterController.get('content.tasksStatuses').get(testDBTaskId) === "FAILED")
                {
                  App.showConfirmationPopup(function () {
                    App.router.transitionTo('step7');
                  }, Em.I18n.t('services.reassign.rollback.confirm'));
                } else {
                  App.showConfirmationPopup(function () {
                    router.get('reassignMasterWizardStep' + currStep + 'Controller').removeObserver('tasks.@each.status', this, 'onTaskStatusChange');
                    context.leaveWizard(router, self);
                  }, Em.I18n.t('services.reassign.closePopup').format(reassignMasterController.get('content.reassign.display_name')));
                }
              } else {
                context.leaveWizard(router, this);
              }
            },
            didInsertElement: function () {
              this.fitHeight();
            }
          });
          reassignMasterController.set('popup', popup);
          reassignMasterController.loadComponentToReassign();
          var currStep = reassignMasterController.get('currentStep');
          var currentClusterStatus = App.clusterStatus.get('value');
          if (currentClusterStatus) {
            switch (currentClusterStatus.clusterState) {
              case 'REASSIGN_MASTER_INSTALLING' :
                if (currentClusterStatus.localdb.ReassignMaster.currentStep !== currStep) {
                  reassignMasterController.setCurrentStep(currentClusterStatus.localdb.ReassignMaster.currentStep);
                }
                break;
            }
          }
          router.transitionTo('step' + currStep);
        });
      } else {
        App.showAlertPopup(Em.I18n.t('common.error'), Em.I18n.t('services.reassign.error.fewHosts'), function () {
          router.transitionTo('main.services.index');
        })
      }
    });
  },

  step1: Em.Route.extend({
    route: '/step1',
    connectOutlets: function (router) {
      console.log('in reassignMaster.step1:connectOutlets');
      var controller = router.get('reassignMasterController');
      var step1Controller = router.get('reassignMasterWizardStep1Controller');
      controller.setCurrentStep('1');
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('reassignMasterWizardStep1', controller.get('content'));
        step1Controller.loadConfigsTags();
      })
    },
    next: function (router) {
      var controller = router.get('reassignMasterController');
      App.db.setMasterComponentHosts(undefined);
      controller.clearMasterComponentHosts();
      router.transitionTo('step2');
    },

    unroutePath: function () {
      return false;
    }
  }),

  step2: Em.Route.extend({
    route: '/step2',
    connectOutlets: function (router) {
      console.log('in reassignMaster.step2:connectOutlets');
      var controller = router.get('reassignMasterController');
      controller.setCurrentStep('2');
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('reassignMasterWizardStep2', controller.get('content'));
      })

    },
    back: Em.Router.transitionTo('step1'),
    next: function (router) {
      var controller = router.get('reassignMasterController');
      var reassignMasterWizardStep2 = router.get('reassignMasterWizardStep2Controller');
      controller.saveMasterComponentHosts(reassignMasterWizardStep2);
      var reassignHosts = {};
      var componentName = reassignMasterWizardStep2.get('content.reassign.component_name');
      var masterAssignmentsHosts = reassignMasterWizardStep2.get('selectedServicesMasters').filterProperty('component_name', componentName).mapProperty('selectedHost');
      var currentMasterHosts = App.HostComponent.find().filterProperty('componentName', componentName).mapProperty('hostName');
      masterAssignmentsHosts.forEach(function (host) {
        if (!currentMasterHosts.contains(host)) {
          reassignHosts.target = host;
        }
      }, this);
      currentMasterHosts.forEach(function (host) {
        if (!masterAssignmentsHosts.contains(host)) {
          reassignHosts.source = host;
        }
      }, this);
      controller.saveReassignHosts(reassignHosts);
      router.transitionTo('step3');
    },

    unroutePath: function () {
      return false;
    }
  }),

  step3: Em.Route.extend({
    route: '/step3',
    connectOutlets: function (router) {
      console.log('in reassignMaster.step3:connectOutlets');
      var controller = router.get('reassignMasterController');
      controller.setCurrentStep('3');
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('reassignMasterWizardStep3', controller.get('content'));
      })
    },
    back: Em.Router.transitionTo('step2'),
    next: function (router) {
      App.db.setReassignTasksStatuses(undefined);
      App.db.setReassignTasksRequestIds(undefined);
      App.clusterStatus.setClusterStatus({
        clusterName: router.get('reassignMasterController.content.cluster.name'),
        clusterState: 'REASSIGN_MASTER_INSTALLING',
        wizardControllerName: 'reassignMasterController',
        localdb: App.db.data
      });
      router.transitionTo('step4');
    },

    unroutePath: function () {
      return false;
    }
  }),

  step4: Em.Route.extend({
    route: '/step4',
    connectOutlets: function (router) {
      console.log('in reassignMaster.step4:connectOutlets');
      var controller = router.get('reassignMasterController');
      controller.setCurrentStep('4');
      controller.setLowerStepsDisable(4);
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('reassignMasterWizardStep4', controller.get('content'));
      })
    },
    next: function (router) {
      router.get('reassignMasterController').setCurrentStep('5');

      App.clusterStatus.setClusterStatus({
        clusterName: router.get('reassignMasterController.content.cluster.name'),
        clusterState: 'REASSIGN_MASTER_INSTALLING',
        wizardControllerName: 'reassignMasterController',
        localdb: App.db.data
      });

      router.transitionTo('step5');
    },

    complete: function (router) {
      var controller = router.get('reassignMasterController');
      var reassignMasterWizardStep4 = router.get('reassignMasterWizardStep4Controller');
      if (!reassignMasterWizardStep4.get('isSubmitDisabled')) {
        controller.finish();
        controller.get('popup').hide();
        App.clusterStatus.setClusterStatus({
          clusterName: router.get('reassignMasterController.content.cluster.name'),
          clusterState: 'DEFAULT',
          localdb: App.db.data
        }, {alwaysCallback: function () {
          controller.get('popup').hide();
          router.transitionTo('main.index');
          location.reload();
        }});
      }
    },

    unroutePath: function () {
      return false;
    }
  }),

  step5: Em.Route.extend({
    route: '/step5',
    connectOutlets: function (router) {
      console.log('in reassignMaster.step5:connectOutlets');
      var controller = router.get('reassignMasterController');
      controller.setCurrentStep('5');
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.setLowerStepsDisable(5);
        if ((controller.get('content.reassign.component_name') === 'NAMENODE') || controller.get('content.reassign.component_name') === 'SECONDARY_NAMENODE') {
          controller.usersLoading().done(function () {
            controller.connectOutlet('reassignMasterWizardStep5', controller.get('content'));
          })
        } else {
          controller.connectOutlet('reassignMasterWizardStep5', controller.get('content'));
        }
      })
    },
    next: function (router) {
      App.showConfirmationPopup(function () {
        router.transitionTo('step6');
      }, Em.I18n.t('services.reassign.step5.confirmPopup.body'));
    },

    unroutePath: function () {
      return false;
    }
  }),

  step6: Em.Route.extend({
    route: '/step6',
    connectOutlets: function (router) {
      console.log('in reassignMaster.step6:connectOutlets');
      var controller = router.get('reassignMasterController');
      controller.setCurrentStep('6');
      controller.setLowerStepsDisable(6);
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('reassignMasterWizardStep6', controller.get('content'));
      })
    },

    next: function (router) {
      var controller = router.get('reassignMasterController');
      var reassignMasterWizardStep6 = router.get('reassignMasterWizardStep6Controller');
      if (!reassignMasterWizardStep6.get('isSubmitDisabled')) {
        controller.finish();
        controller.get('popup').hide();
        App.clusterStatus.setClusterStatus({
          clusterName: router.get('reassignMasterController.content.cluster.name'),
          clusterState: 'DEFAULT',
          localdb: App.db.data
        }, {alwaysCallback: function () {
          controller.get('popup').hide();
          router.transitionTo('main.index');
          location.reload();
        }});
      }
    },

    unroutePath: function () {
      return false;
    }
  }),

  step7: Em.Route.extend({
    route: '/step7',
    connectOutlets: function (router) {
      console.log('in reassignMaster.step7:connectOutlets');
      var controller = router.get('reassignMasterController');
      controller.setCurrentStep('7');
      controller.setLowerStepsDisable(7);
      controller.dataLoading().done(function () {
        controller.loadAllPriorSteps();
        controller.connectOutlet('reassignMasterWizardStep7', controller.get('content'));
      });
    },

    next: function (router) {
      var controller = router.get('reassignMasterController');
      var reassignMasterWizardStep7 = router.get('reassignMasterWizardStep7Controller');
      if (!reassignMasterWizardStep7.get('isSubmitDisabled')) {
        controller.finish();
        controller.get('popup').hide();
        App.clusterStatus.setClusterStatus({
          clusterName: router.get('reassignMasterController.content.cluster.name'),
          clusterState: 'DEFAULT',
          localdb: App.db.data
        }, {alwaysCallback: function () {
          controller.get('popup').hide();
          router.transitionTo('main.index');
          location.reload();
        }});
      }
    },

    complete: function (router) {
      var controller = router.get('reassignMasterController');
      var reassignMasterWizardStep7 = router.get('reassignMasterWizardStep7Controller');
      if (!reassignMasterWizardStep7.get('isSubmitDisabled')) {
        controller.finish();
        controller.get('popup').hide();
        App.clusterStatus.setClusterStatus({
          clusterName: router.get('reassignMasterController.content.cluster.name'),
          clusterState: 'DEFAULT',
          localdb: App.db.data
        }, {alwaysCallback: function () {
          controller.get('popup').hide();
          router.transitionTo('main.index');
          location.reload();
        }});
      }
    },

    unroutePath: function () {
      return false;
    }
  }),

  gotoStep7: Em.Router.transitionTo('step7'),

  backToServices: function (router) {
    App.router.get('updateController').set('isWorking', true);
    router.transitionTo('services');
  }

});
<|endoftext|>


<commit_before>/*
 * BookLibraryBase
 */
define(function () {
    console.log('CORE: bookLibraryBase called');
    function bookLibraryBase(id, configs) {
        this.id = id;
        this.configs = configs;
		var BookView = CORE.main.view.Main.View.extend({
			tagName:"div",
			className:"bookContainer",
			template:$("#bookTemplate").html(),
			render:function () {
				console.log('BookView render called');
				var tmpl = _.template(this.template);//tmpl is a function that takes a JSON and returns html
				this.$el.html(tmpl(this.model.toJSON()));//this.el is what we defined in tagName.
				//use $el to get access to jQuery html() function
				return this;
			},
			events: {
				"click .delete": "deleteBook"
			},
			deleteBook:function () {
				//Delete model
				this.model.destroy();
				//Delete view
				this.remove();
			}
		});
		var LibraryView = CORE.main.view.Main.View.extend({
			//A view can take either a tagName, as we saw in our BookView, or an el.
			//When we use tagName, the view will create the element for us, but we are responsible for inserting it into the page.
			//When we use el we specify an existing element in the page and the view will write directly into the page, into the specified element.
			//In this case we select the div with id=”books”.
			el:$("#books"),
			//This is a special (but optional) property that must contain a function.
			//This function will be called by Backbone when the view constructor is called
			initialize:function(){
				//Create a new Library (collection of Book models) and store it in a local property called “collection”.
				this.collection = new Library(books);
				//It call its own render function, which means that as soon as we call the LibraryView constructor it will get rendered, so this is a self rendering view.
				//We don’t have to make it self rendered but it is common practice.
				this.render();
				//When a model is added to a collection, the collection will fire an add event.
				//If we listen to this event we will be able to call our renderBook function.
				this.collection.on("add", this.renderBook, this);
				this.collection.on("remove", this.removeBook, this);
			},
			render: function(){
				//We store a reference to the current object in a variable “that”
				var that = this;
				//Use the each function of underscore to iterate over all the models (Books) in our collection.
				//The first argument to “each” is the array that will be iterated over.
				//The second argument is the function that will be applied to each member of the array.
				//The function in our case calls the renderBook function with the current model as argument.
				//We need to use “that” to get this right since if we would have used “this” it would have referenced the function itself.
				//The third argument (this) is the context that each is executing in.
				_.each(this.collection.models, function(item){
					that.renderBook(item);
				}, this);
			},
			addBook: function(e){
				//Prevent the form from actually submit and reloading the page.
				e.preventDefault();
				//Here I select all the input elements the form and iterate over them using jQuerys each.
				//Since we used the same names for ids in our form as the keys on our Book model we can simply store them directly in the formData object and the add it to the books array.
				var formData = {};
				$("#addBook div").children("input").each(function(i, el){
					//Check to see if the field value is empty, in which case we do not add it to the model data.
					if ($(el).val() !== "") {
						formData[el.id] = $(el).val();
					}
				});
				books.push(formData);
				//We then create a new Book model and add it to our collection.
				this.collection.add(new Book(formData));
			},
			removeBook: function(removedBook){
				var removedBookData = removedBook.attributes;
				//Since the default values was not saved in the books array we need to remove them in order to find an match.
				//We use underscores each function to iterate over the properties of the removed Book model and delete any property that is equal to the default value.
				//Since the underscore each function also is capable of iterating over objects in an array we use it again to iterate over the objects in our books array to find the data of the removed Book.
				//To get a match we use the isEqual function of underscore that performs a deep comparison of objects.
				//Similarly the indexOf can find complex objects, which we use when we remove the book data using splice.
				_.each(removedBookData, function(val, key){
					if(removedBookData[key] === removedBook.defaults[key]){
						delete removedBookData[key];
					}
				});
				_.each(books, function(book){
					if(_.isEqual(book, removedBookData)){
						books.splice(_.indexOf(books, book), 1);
					}
				});
			},
			events:{
				"click #add":"addBook"
			},
			//This function takes a model (a Book) as argument and uses it to create a BookView.
			renderBook:function(item){
				var bookView = new BookView({
					model: item
				});
				//The bookView is then rendered and appended to the view container as specified in our el property
				this.$el.append(bookView.render().el);
			}
		});

		alert("Hello from BookLibraryBase: BookView = "); // FOR TESTING ONLY
		alert(BookView);
		alert("Hello from BookLibraryBase: LibraryView = "); // FOR TESTING ONLY
		alert(LibraryView);

    };
    bookLibraryBase.prototype = {
        getConfigs: function () {
            console.log('CORE: bookLibraryBase getConfigs() called');
            return this.configs;
        }
    };
    return bookLibraryBase;
});
<commit_msg>Updated<commit_after>/*
 * BookLibraryBase
 */
define(function () {
    console.log('CORE: bookLibraryBase called');
    function bookLibraryBase(id, configs) {
        this.id = id;
        this.configs = configs;
		var BookView = CORE.main.view.Main.View.extend({
			tagName:"div",
			className:"bookContainer",
			template:$("#bookTemplate").html(),
			render:function () {
				console.log('BookView render called');
				var tmpl = _.template(this.template);//tmpl is a function that takes a JSON and returns html
				this.$el.html(tmpl(this.model.toJSON()));//this.el is what we defined in tagName.
				//use $el to get access to jQuery html() function
				return this;
			},
			events: {
				"click .delete": "deleteBook"
			},
			deleteBook:function () {
				//Delete model
				this.model.destroy();
				//Delete view
				this.remove();
			}
		});
		var LibraryView = CORE.main.view.Main.View.extend({
			//A view can take either a tagName, as we saw in our BookView, or an el.
			//When we use tagName, the view will create the element for us, but we are responsible for inserting it into the page.
			//When we use el we specify an existing element in the page and the view will write directly into the page, into the specified element.
			//In this case we select the div with id=”books”.
			el:$("#books"),
			//This is a special (but optional) property that must contain a function.
			//This function will be called by Backbone when the view constructor is called
			initialize:function(){
				//Create a new Library (collection of Book models) and store it in a local property called “collection”.
				this.collection = new Library(books);
				//It call its own render function, which means that as soon as we call the LibraryView constructor it will get rendered, so this is a self rendering view.
				//We don’t have to make it self rendered but it is common practice.
				this.render();
				//When a model is added to a collection, the collection will fire an add event.
				//If we listen to this event we will be able to call our renderBook function.
				this.collection.on("add", this.renderBook, this);
				this.collection.on("remove", this.removeBook, this);
			},
			render: function(){
				//We store a reference to the current object in a variable “that”
				var that = this;
				//Use the each function of underscore to iterate over all the models (Books) in our collection.
				//The first argument to “each” is the array that will be iterated over.
				//The second argument is the function that will be applied to each member of the array.
				//The function in our case calls the renderBook function with the current model as argument.
				//We need to use “that” to get this right since if we would have used “this” it would have referenced the function itself.
				//The third argument (this) is the context that each is executing in.
				_.each(this.collection.models, function(item){
					that.renderBook(item);
				}, this);
			},
			addBook: function(e){
				//Prevent the form from actually submit and reloading the page.
				e.preventDefault();
				//Here I select all the input elements the form and iterate over them using jQuerys each.
				//Since we used the same names for ids in our form as the keys on our Book model we can simply store them directly in the formData object and the add it to the books array.
				var formData = {};
				$("#addBook div").children("input").each(function(i, el){
					//Check to see if the field value is empty, in which case we do not add it to the model data.
					if ($(el).val() !== "") {
						formData[el.id] = $(el).val();
					}
				});
				books.push(formData);
				//We then create a new Book model and add it to our collection.
				this.collection.add(new Book(formData));
			},
			removeBook: function(removedBook){
				var removedBookData = removedBook.attributes;
				//Since the default values was not saved in the books array we need to remove them in order to find an match.
				//We use underscores each function to iterate over the properties of the removed Book model and delete any property that is equal to the default value.
				//Since the underscore each function also is capable of iterating over objects in an array we use it again to iterate over the objects in our books array to find the data of the removed Book.
				//To get a match we use the isEqual function of underscore that performs a deep comparison of objects.
				//Similarly the indexOf can find complex objects, which we use when we remove the book data using splice.
				_.each(removedBookData, function(val, key){
					if(removedBookData[key] === removedBook.defaults[key]){
						delete removedBookData[key];
					}
				});
				_.each(books, function(book){
					if(_.isEqual(book, removedBookData)){
						books.splice(_.indexOf(books, book), 1);
					}
				});
			},
			events:{
				"click #add":"addBook"
			},
			//This function takes a model (a Book) as argument and uses it to create a BookView.
			renderBook:function(item){
				var bookView = new BookView({
					model: item
				});
				//The bookView is then rendered and appended to the view container as specified in our el property
				this.$el.append(bookView.render().el);
			}
		});

		alert("Hello from BookLibraryBase: BookView = "); // FOR TESTING ONLY
		alert(BookView);
		alert("Hello from BookLibraryBase: LibraryView = "); // FOR TESTING ONLY
		alert(LibraryView);

		// NOTE: books are data and should probably be kept in a module other than this. TO DO: move
		var books = [{title:"JS the good parts", author:"John Doe", releaseDate:"2012", keywords:"JavaScript Programming"},
        {title:"CS the better parts", author:"John Doe", releaseDate:"2012", keywords:"CoffeeScript Programming"},
        {title:"Scala for the impatient", author:"John Doe", releaseDate:"2012", keywords:"Scala Programming"},
        {title:"American Psyco", author:"Bret Easton Ellis", releaseDate:"2012", keywords:"Novel Splatter"},
        {title:"Eloquent JavaScript", author:"John Doe", releaseDate:"2012", keywords:"JavaScript Programming"}];

		var libraryView = new LibraryView(); // Can only work if book and library model are known

    };
    bookLibraryBase.prototype = {
        getConfigs: function () {
            console.log('CORE: bookLibraryBase getConfigs() called');
            return this.configs;
        }
    };
    return bookLibraryBase;
});
<|endoftext|>


<commit_before>$(document).ready(function() {
   // 身份证号码验证
    jQuery.validator.addMethod("idCardNo", function(value, element) {
        if(jQuery("#identityType").val()=="0"){
            return this.optional(element) || idCardNoUtil.checkIdCardNo(value);
        }else{
            return true;
        }
    });

    // 手机号码验证
    jQuery.validator.addMethod("cellPhone", function(value, element) {
      var length = value.length;
      return this.optional(element) || (length == 11 && /^(1[3|5|8|4][0-9])\d{8}$/.test(value));
    });
});

var idCardNoUtil = {    provinceAndCitys : {
        11 : "北京",
        12 : "天津",
        13 : "河北",
        14 : "山西",
        15 : "内蒙古",
        21 : "辽宁",
        22 : "吉林",
        23 : "黑龙江",
        31 : "上海",
        32 : "江苏",
        33 : "浙江",
        34 : "安徽",
        35 : "福建",
        36 : "江西",
        37 : "山东",
        41 : "河南",
        42 : "湖北",
        43 : "湖南",
        44 : "广东",
        45 : "广西",
        46 : "海南",
        50 : "重庆",
        51 : "四川",
        52 : "贵州",
        53 : "云南",
        54 : "西藏",
        61 : "陕西",
        62 : "甘肃",
        63 : "青海",
        64 : "宁夏",
        65 : "新疆",
        71 : "台湾",
        81 : "香港",
        82 : "澳门",
        91 : "国外"
    },

    powers : [ "7", "9", "10", "5", "8", "4", "2", "1", "6", "3", "7", "9",
            "10", "5", "8", "4", "2" ],

    parityBit : [ "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2" ],

    genders : {
        male : "男",
        female : "女"
    },

    checkAddressCode : function(addressCode) {
        var check = /^[1-9]\d{5}$/.test(addressCode);
        if (!check)
            return false;
        if (idCardNoUtil.provinceAndCitys[parseInt(addressCode.substring(0, 2))]) {
            return true;
        } else {
            return false;
        }
    },

    checkBirthDayCode : function(birDayCode) {
        var check = /^[1-9]\d{3}((0[1-9])|(1[0-2]))((0[1-9])|([1-2][0-9])|(3[0-1]))$/
                .test(birDayCode);
        if (!check)
            return false;
        var yyyy = parseInt(birDayCode.substring(0, 4), 10);
        var mm = parseInt(birDayCode.substring(4, 6), 10);
        var dd = parseInt(birDayCode.substring(6), 10);
        var xdata = new Date(yyyy, mm - 1, dd);
        if (xdata > new Date()) {
            return false;// 生日不能大于当前日期
        } else if ((xdata.getFullYear() == yyyy)
                && (xdata.getMonth() == mm - 1) && (xdata.getDate() == dd)) {
            return true;
        } else {
            return false;
        }
    },

    getParityBit : function(idCardNo) {
        var id17 = idCardNo.substring(0, 17);
        var power = 0;
        for (var i = 0; i < 17; i++) {
            power += parseInt(id17.charAt(i), 10)
                    * parseInt(idCardNoUtil.powers[i]);
        }
        var mod = power % 11;
        return idCardNoUtil.parityBit[mod];
    },

    checkParityBit : function(idCardNo) {
        var parityBit = idCardNo.charAt(17).toUpperCase();
        if (idCardNoUtil.getParityBit(idCardNo) == parityBit) {
            return true;
        } else {
            return false;
        }
    },

    checkIdCardNo : function(idCardNo) {
        // 15位和18位身份证号码的基本校验
        var check = /^\d{15}|(\d{17}(\d|x|X))$/.test(idCardNo);
        if (!check)
            return false;
        // 判断长度为15位或18位
        if (idCardNo.length == 15) {
            return idCardNoUtil.check15IdCardNo(idCardNo);
        } else if (idCardNo.length == 18) {
            return idCardNoUtil.check18IdCardNo(idCardNo);
        } else {
            return false;
        }
    },
    // 校验15位的身份证号码
    check15IdCardNo : function(idCardNo) {
        // 15位身份证号码的基本校验
        var check = /^[1-9]\d{7}((0[1-9])|(1[0-2]))((0[1-9])|([1-2][0-9])|(3[0-1]))\d{3}$/
                .test(idCardNo);
        if (!check)
            return false;
        // 校验地址码
        var addressCode = idCardNo.substring(0, 6);
        check = idCardNoUtil.checkAddressCode(addressCode);
        if (!check)
            return false;
        var birDayCode = '19' + idCardNo.substring(6, 12);
        // 校验日期码
        return idCardNoUtil.checkBirthDayCode(birDayCode);
    },
    // 校验18位的身份证号码
    check18IdCardNo : function(idCardNo) {
        // 18位身份证号码的基本格式校验
        var check = /^[1-9]\d{5}[1-9]\d{3}((0[1-9])|(1[0-2]))((0[1-9])|([1-2][0-9])|(3[0-1]))\d{3}(\d|x|X)$/
                .test(idCardNo);
        if (!check)
            return false;
        // 校验地址码
        var addressCode = idCardNo.substring(0, 6);
        check = idCardNoUtil.checkAddressCode(addressCode);
        if (!check)
            return false;
        // 校验日期码
        var birDayCode = idCardNo.substring(6, 14);
        check = idCardNoUtil.checkBirthDayCode(birDayCode);
        if (!check)
            return false;
        // 验证校检码
        return idCardNoUtil.checkParityBit(idCardNo);
    },
    formateDateCN : function(day) {
        var yyyy = day.substring(0, 4);
        var mm = day.substring(4, 6);
        var dd = day.substring(6);
        return yyyy + '-' + mm + '-' + dd;
    },
    // 获取信息
    getIdCardInfo : function(idCardNo) {
        var idCardInfo = {
            gender : "", // 性别
            birthday : "" // 出生日期(yyyy-mm-dd)
        };
        if (idCardNo.length == 15) {
            var aday = '19' + idCardNo.substring(6, 12);
            idCardInfo.birthday = idCardNoUtil.formateDateCN(aday);
            if (parseInt(idCardNo.charAt(14)) % 2 == 0) {
                idCardInfo.gender = idCardNoUtil.genders.female;
            } else {
                idCardInfo.gender = idCardNoUtil.genders.male;
            }
        } else if (idCardNo.length == 18) {
            var aday = idCardNo.substring(6, 14);
            idCardInfo.birthday = idCardNoUtil.formateDateCN(aday);
            if (parseInt(idCardNo.charAt(16)) % 2 == 0) {
                idCardInfo.gender = idCardNoUtil.genders.female;
            } else {
                idCardInfo.gender = idCardNoUtil.genders.male;
            }
        }
        return idCardInfo;
    },

    getId15 : function(idCardNo) {
        if (idCardNo.length == 15) {
            return idCardNo;
        } else if (idCardNo.length == 18) {
            return idCardNo.substring(0, 6) + idCardNo.substring(8, 17);
        } else {
            return null;
        }
    },

    getId18 : function(idCardNo) {
        if (idCardNo.length == 15) {
            var id17 = idCardNo.substring(0, 6) + '19' + idCardNo.substring(6);
            var parityBit = idCardNoUtil.getParityBit(id17);
            return id17 + parityBit;
        } else if (idCardNo.length == 18) {
            return idCardNo;
        } else {
            return null;
        }
    }
};
// 验证护照是否正确
function checkPassport(number) {
    var str = number;
    // 在JavaScript中，正则表达式只能使用"/"开头和结束，不能使用双引号
    var Expression = /(P\d{7})|(G\d{8})/;
    var objExp = new RegExp(Expression);
    if (objExp.test(str) == true) {
        return true;
    } else {
        return false;
    }
};<commit_msg>Update checkUtil.js<commit_after>$(document).ready(function() {
   // 身份证号码验证
    jQuery.validator.addMethod("idCardNo", function(value, element) {
        if(jQuery("#identityType").val()=="0"){
            return this.optional(element) || idCardNoUtil.checkIdCardNo(value);
        }else{
            return true;
        }
    });

    // 手机号码验证
    jQuery.validator.addMethod("cellPhone", function(value, element) {
      var length = value.length;
      return this.optional(element) || (length == 11 && /^(1[3|5|8|4|7][0-9])\d{8}$/.test(value));
    });
});

var idCardNoUtil = {    provinceAndCitys : {
        11 : "北京",
        12 : "天津",
        13 : "河北",
        14 : "山西",
        15 : "内蒙古",
        21 : "辽宁",
        22 : "吉林",
        23 : "黑龙江",
        31 : "上海",
        32 : "江苏",
        33 : "浙江",
        34 : "安徽",
        35 : "福建",
        36 : "江西",
        37 : "山东",
        41 : "河南",
        42 : "湖北",
        43 : "湖南",
        44 : "广东",
        45 : "广西",
        46 : "海南",
        50 : "重庆",
        51 : "四川",
        52 : "贵州",
        53 : "云南",
        54 : "西藏",
        61 : "陕西",
        62 : "甘肃",
        63 : "青海",
        64 : "宁夏",
        65 : "新疆",
        71 : "台湾",
        81 : "香港",
        82 : "澳门",
        91 : "国外"
    },

    powers : [ "7", "9", "10", "5", "8", "4", "2", "1", "6", "3", "7", "9",
            "10", "5", "8", "4", "2" ],

    parityBit : [ "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2" ],

    genders : {
        male : "男",
        female : "女"
    },

    checkAddressCode : function(addressCode) {
        var check = /^[1-9]\d{5}$/.test(addressCode);
        if (!check)
            return false;
        if (idCardNoUtil.provinceAndCitys[parseInt(addressCode.substring(0, 2))]) {
            return true;
        } else {
            return false;
        }
    },

    checkBirthDayCode : function(birDayCode) {
        var check = /^[1-9]\d{3}((0[1-9])|(1[0-2]))((0[1-9])|([1-2][0-9])|(3[0-1]))$/
                .test(birDayCode);
        if (!check)
            return false;
        var yyyy = parseInt(birDayCode.substring(0, 4), 10);
        var mm = parseInt(birDayCode.substring(4, 6), 10);
        var dd = parseInt(birDayCode.substring(6), 10);
        var xdata = new Date(yyyy, mm - 1, dd);
        if (xdata > new Date()) {
            return false;// 生日不能大于当前日期
        } else if ((xdata.getFullYear() == yyyy)
                && (xdata.getMonth() == mm - 1) && (xdata.getDate() == dd)) {
            return true;
        } else {
            return false;
        }
    },

    getParityBit : function(idCardNo) {
        var id17 = idCardNo.substring(0, 17);
        var power = 0;
        for (var i = 0; i < 17; i++) {
            power += parseInt(id17.charAt(i), 10)
                    * parseInt(idCardNoUtil.powers[i]);
        }
        var mod = power % 11;
        return idCardNoUtil.parityBit[mod];
    },

    checkParityBit : function(idCardNo) {
        var parityBit = idCardNo.charAt(17).toUpperCase();
        if (idCardNoUtil.getParityBit(idCardNo) == parityBit) {
            return true;
        } else {
            return false;
        }
    },

    checkIdCardNo : function(idCardNo) {
        // 15位和18位身份证号码的基本校验
        var check = /^\d{15}|(\d{17}(\d|x|X))$/.test(idCardNo);
        if (!check)
            return false;
        // 判断长度为15位或18位
        if (idCardNo.length == 15) {
            return idCardNoUtil.check15IdCardNo(idCardNo);
        } else if (idCardNo.length == 18) {
            return idCardNoUtil.check18IdCardNo(idCardNo);
        } else {
            return false;
        }
    },
    // 校验15位的身份证号码
    check15IdCardNo : function(idCardNo) {
        // 15位身份证号码的基本校验
        var check = /^[1-9]\d{7}((0[1-9])|(1[0-2]))((0[1-9])|([1-2][0-9])|(3[0-1]))\d{3}$/
                .test(idCardNo);
        if (!check)
            return false;
        // 校验地址码
        var addressCode = idCardNo.substring(0, 6);
        check = idCardNoUtil.checkAddressCode(addressCode);
        if (!check)
            return false;
        var birDayCode = '19' + idCardNo.substring(6, 12);
        // 校验日期码
        return idCardNoUtil.checkBirthDayCode(birDayCode);
    },
    // 校验18位的身份证号码
    check18IdCardNo : function(idCardNo) {
        // 18位身份证号码的基本格式校验
        var check = /^[1-9]\d{5}[1-9]\d{3}((0[1-9])|(1[0-2]))((0[1-9])|([1-2][0-9])|(3[0-1]))\d{3}(\d|x|X)$/
                .test(idCardNo);
        if (!check)
            return false;
        // 校验地址码
        var addressCode = idCardNo.substring(0, 6);
        check = idCardNoUtil.checkAddressCode(addressCode);
        if (!check)
            return false;
        // 校验日期码
        var birDayCode = idCardNo.substring(6, 14);
        check = idCardNoUtil.checkBirthDayCode(birDayCode);
        if (!check)
            return false;
        // 验证校检码
        return idCardNoUtil.checkParityBit(idCardNo);
    },
    formateDateCN : function(day) {
        var yyyy = day.substring(0, 4);
        var mm = day.substring(4, 6);
        var dd = day.substring(6);
        return yyyy + '-' + mm + '-' + dd;
    },
    // 获取信息
    getIdCardInfo : function(idCardNo) {
        var idCardInfo = {
            gender : "", // 性别
            birthday : "" // 出生日期(yyyy-mm-dd)
        };
        if (idCardNo.length == 15) {
            var aday = '19' + idCardNo.substring(6, 12);
            idCardInfo.birthday = idCardNoUtil.formateDateCN(aday);
            if (parseInt(idCardNo.charAt(14)) % 2 == 0) {
                idCardInfo.gender = idCardNoUtil.genders.female;
            } else {
                idCardInfo.gender = idCardNoUtil.genders.male;
            }
        } else if (idCardNo.length == 18) {
            var aday = idCardNo.substring(6, 14);
            idCardInfo.birthday = idCardNoUtil.formateDateCN(aday);
            if (parseInt(idCardNo.charAt(16)) % 2 == 0) {
                idCardInfo.gender = idCardNoUtil.genders.female;
            } else {
                idCardInfo.gender = idCardNoUtil.genders.male;
            }
        }
        return idCardInfo;
    },

    getId15 : function(idCardNo) {
        if (idCardNo.length == 15) {
            return idCardNo;
        } else if (idCardNo.length == 18) {
            return idCardNo.substring(0, 6) + idCardNo.substring(8, 17);
        } else {
            return null;
        }
    },

    getId18 : function(idCardNo) {
        if (idCardNo.length == 15) {
            var id17 = idCardNo.substring(0, 6) + '19' + idCardNo.substring(6);
            var parityBit = idCardNoUtil.getParityBit(id17);
            return id17 + parityBit;
        } else if (idCardNo.length == 18) {
            return idCardNo;
        } else {
            return null;
        }
    }
};
// 验证护照是否正确
function checkPassport(number) {
    var str = number;
    // 在JavaScript中，正则表达式只能使用"/"开头和结束，不能使用双引号
    var Expression = /(P\d{7})|(G\d{8})/;
    var objExp = new RegExp(Expression);
    if (objExp.test(str) == true) {
        return true;
    } else {
        return false;
    }
};
<|endoftext|>


<commit_before>/*jslint browser: true, nomen: false, devel: true*/

/*
 Copyright (c) 2013 Georg Paul

 MIT License

 Permission is hereby granted, free of charge, to any person obtaining
 a copy of this software and associated documentation files (the
 "Software"), to deal in the Software without restriction, including
 without limitation the rights to use, copy, modify, merge, publish,
 distribute, sublicense, and/or sell copies of the Software, and to
 permit persons to whom the Software is furnished to do so, subject to
 the following conditions:

 The above copyright notice and this permission notice shall be
 included in all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

function ElementQueries() {
	"use strict";

	var self = this;

	var megaponySelectorRegExp = new RegExp(/\.(megapony)\-(max|min)\-(width|height)\-(\d*)/);

	self.maxWSelector = '.megapony-max-width-';
	self.minWSelector = '.megapony-min-width-';
	self.maxHSelector = '.megapony-max-height-';
	self.minHSelector = '.megapony-min-height-';

	this.init = function () {
		self.parseStylesheets();
	};

	this.parseStylesheets = function () {
		var selectorTextString = '',
			megaponyStylesheets = self.getMegaponyStyleSheets(document.styleSheets),
			crossRules,
			crossRulesLength,
			rule = '';

		megaponyStylesheets.forEach(function (stylesheet) {
			crossRules = stylesheet.rules || stylesheet.cssRules;
			crossRulesLength = crossRules.length;

			for (var x = 0; x < crossRulesLength; x++) {
				rule = crossRules[x].selectorText;
				selectorTextString += rule + ';';
			}
			self.checkSelectorsForElementQuery(selectorTextString);
		});
	};

	this.getMegaponyStyleSheets = function (stylesheets) {
		var megaponyStylesheets = [],
			stylesheetsLength = stylesheets.length;

		for (var i = 0; i < stylesheetsLength; i++) {
			if (stylesheets[i].title === 'megapony') {
				megaponyStylesheets.push(stylesheets[i]);
			}
		}
		return megaponyStylesheets;
	};

	this.checkSelectorsForElementQuery = function (selectorTextString) {
		var elementsArray = selectorTextString.split(';'),
			selectorText = '';

		for (var i = 0; i < elementsArray.length; i++) {
			selectorText = (elementsArray[i] !== undefined) ? (elementsArray[i]) : '';

			if (megaponySelectorRegExp.test(selectorText)) {
				var values = {
						maxW: self.getLengthFromSelector(self.maxWSelector, selectorText),
						minW: self.getLengthFromSelector(self.minWSelector, selectorText),
						maxH: self.getLengthFromSelector(self.maxHSelector, selectorText),
						minH: self.getLengthFromSelector(self.minHSelector, selectorText)
					},
					targetSelectorArray = selectorText.split(','),
					targetSelectorArrayLength = targetSelectorArray.length,
					storedTargetSelector = '';

				if (targetSelectorArrayLength > 1) {
					// multiple expressions (.foo .bar, .foo2 .bar 2, .lorem-ipsum)
					for (var x = 0; x < targetSelectorArrayLength; x++) {
						if (storedTargetSelector !== self.getTargetSelector(targetSelectorArray[x])) {
							self.applyElementQueries(document.querySelectorAll(self.getTargetSelector(targetSelectorArray[x])), values);
						}
						storedTargetSelector = self.getTargetSelector(targetSelectorArray[x]);
					}
				} else {
					// single expression (.foo .bar)
					self.applyElementQueries(document.querySelectorAll(self.getTargetSelector(targetSelectorArray[0])), values);
				}
			}
		}
	};

	this.getTargetSelector = function (selectorText) {
		var selectorPosition = selectorText.match(megaponySelectorRegExp);

		selectorText = selectorText.replace(megaponySelectorRegExp, '');

		if (selectorText.indexOf(' ', selectorPosition.index) !== -1) {
			return selectorText.substring(0, selectorText.indexOf(' ', selectorPosition.index));
		} else {
			return selectorText;
		}
	};

	this.getLengthFromSelector = function (selector, selectorText) {
		var indexOfText = selectorText.indexOf(selector),
			maxWidth = parseInt(selectorText.slice(indexOfText + selector.length, indexOfText + selector.length + 4), 10);

		return (maxWidth > 0) ? maxWidth : false;
	};

	this.applyElementQueries = function (elements, values) {
		var elementWidth,
			elementHeight,
			elementsLength = elements.length;

		if (elementsLength === 0) {
			return;
		}

		for (var i = 0; i < elementsLength; i++) {
			elementWidth = elements[i].offsetWidth;
			elementHeight = elements[i].offsetHeight;

			// max width
			if ((values.maxW > 0) && (elementWidth < values.maxW)) {
				elements[i].classList.add(self.maxWSelector.split('.')[1] + values.maxW);
			}
			// min width
			if ((values.minW > 0) && (elementWidth >= values.minW)) {
				elements[i].classList.add(self.minWSelector.split('.')[1] + values.minW);
			}
			// max height
			if ((values.maxH > 0) && (elementHeight < values.maxH)) {
				elements[i].classList.add(self.maxHSelector.split('.')[1] + values.maxH);
			}
			// min height
			if ((values.minH > 0) && (elementHeight > values.minH)) {
				elements[i].classList.add(self.minHSelector.split('.')[1] + values.minH);
			}
		}
	};

	this.hideLoadingView = function () {
		document.querySelector('html').classList.remove('megapony-loading');
	};
}<commit_msg>[TASK] Refactoring<commit_after>/*jslint browser: true, nomen: false, devel: true*/

/*
 Copyright (c) 2013 Georg Paul

 MIT License

 Permission is hereby granted, free of charge, to any person obtaining
 a copy of this software and associated documentation files (the
 "Software"), to deal in the Software without restriction, including
 without limitation the rights to use, copy, modify, merge, publish,
 distribute, sublicense, and/or sell copies of the Software, and to
 permit persons to whom the Software is furnished to do so, subject to
 the following conditions:

 The above copyright notice and this permission notice shall be
 included in all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

function ElementQueries() {
	"use strict";

	var self = this,
		megaponySelectorRegExp = new RegExp(/\.(megapony)\-(max|min)\-(width|height)\-(\d*)/),
		maxWSelector = 'megapony-max-width-',
		minWSelector = 'megapony-min-width-',
		maxHSelector = 'megapony-max-height-',
		minHSelector = 'megapony-min-height-';

	this.init = function () {
		self.parseStylesheets();
	};

	this.parseStylesheets = function () {
		var selectorTextString = '',
			crossRules,
			crossRulesLength,
			rule = '';

		self.getMegaponyStyleSheets(document.styleSheets).forEach(function (stylesheet) {
			crossRules = stylesheet.rules || stylesheet.cssRules;
			crossRulesLength = crossRules.length;

			for (var x = 0; x < crossRulesLength; x++) {
				rule = crossRules[x].selectorText;
				selectorTextString += rule + ';';
			}
			self.checkSelectorsForElementQuery(selectorTextString);
		});
	};

	this.getMegaponyStyleSheets = function (stylesheets) {
		var megaponyStylesheets = [],
			stylesheetsLength = stylesheets.length;

		for (var i = 0; i < stylesheetsLength; i++) {
			if (stylesheets[i].title === 'megapony') {
				megaponyStylesheets.push(stylesheets[i]);
			}
		}
		return megaponyStylesheets;
	};

	this.checkSelectorsForElementQuery = function (selectorTextString) {
		var elements = selectorTextString.split(';'),
			elementsLength = elements.length,
			selectorText = '';

		for (var i = 0; i < elementsLength; i++) {
			selectorText = (elements[i] !== undefined) ? (elements[i]) : '';
			if (megaponySelectorRegExp.test(selectorText)) {
				self.selectorContainsElementQueries(selectorText);
			}
		}
	};

	this.selectorContainsElementQueries = function (selectorText) {
		var targets = selectorText.split(','),
			targetsLength = targets.length,
			storedTargetSelector = '';

		for (var x = 0; x < targetsLength; x++) {
			if (storedTargetSelector !== self.getTargetSelector(targets[x])) {
				self.applyElementQueries(document.querySelectorAll(self.getTargetSelector(targets[x])), self.getWidthAndHeightFromSelector(selectorText));
			}
			storedTargetSelector = self.getTargetSelector(targets[x]);
		}
	};

	this.getWidthAndHeightFromSelector = function (selectorText) {
		return {
			maxW: self.getLengthFromSelector(maxWSelector, selectorText),
			minW: self.getLengthFromSelector(minWSelector, selectorText),
			maxH: self.getLengthFromSelector(maxHSelector, selectorText),
			minH: self.getLengthFromSelector(minHSelector, selectorText)
		};
	};

	this.getTargetSelector = function (selectorText) {
		var selectorPosition = selectorText.match(megaponySelectorRegExp);

		selectorText = selectorText.replace(megaponySelectorRegExp, '');

		if (selectorText.indexOf(' ', selectorPosition.index) !== -1) {
			return selectorText.substring(0, selectorText.indexOf(' ', selectorPosition.index));
		} else {
			return selectorText;
		}
	};

	this.getLengthFromSelector = function (selector, selectorText) {
		var indexOfText = selectorText.indexOf(selector),
			value = parseInt(selectorText.slice(indexOfText + selector.length, indexOfText + selector.length + 4), 10);

		return (value > 0) ? value : false;
	};

	this.applyElementQueries = function (elements, values) {
		var elementWidth,
			elementHeight,
			elementsLength = elements.length;

		if (elementsLength === 0) {
			return;
		}

		for (var i = 0; i < elementsLength; i++) {
			elementWidth = elements[i].offsetWidth;
			elementHeight = elements[i].offsetHeight;

			if ((values.maxW > 0) && (elementWidth < values.maxW)) {
				elements[i].classList.add(maxWSelector + values.maxW); // max width
			}
			if ((values.minW > 0) && (elementWidth >= values.minW)) {
				elements[i].classList.add(minWSelector + values.minW); // min width
			}
			if ((values.maxH > 0) && (elementHeight < values.maxH)) {
				elements[i].classList.add(maxHSelector + values.maxH); // max height
			}
			if ((values.minH > 0) && (elementHeight > values.minH)) {
				elements[i].classList.add(minHSelector + values.minH); // min height
			}
		}
	};

	this.hideLoadingView = function () {
		document.querySelector('html').classList.remove('megapony-loading');
	};
}<|endoftext|>


<commit_before>/* globals jQuery */

/******************************************************************
 * Author: Dipcode
 *
 * Django forms ajax submission
 * Example:
 *   <form data-ajax-submit>
 *****************************************************************/

(function($) {
    "use strict";

    function CacheFile(name, filename, file) {
        this.name = name;
        this.filename = filename;
        this.file = new Blob([file]);
    }

    function ManageCacheFile($form) {
        this.$form = $form;
        this.$inputFiles = this.$form.find("input[type='file']");
        this.cachedFiles = {};
        this.bindEvents();
    }

    ManageCacheFile.prototype = {

        getFormData: function getFormData()
        {
            this.$inputFiles.prop('disabled', true);

            var data = new FormData(this.$form.get(0));

            for (var i in this.cachedFiles) {
                var cachedFile = this.cachedFiles[i];
                data.append(cachedFile.name, cachedFile.file, cachedFile.filename);
            }

            this.$inputFiles.prop('disabled', false);

            return data;
        },

        bindEvents: function bindEvents()
        {
            var self = this;

            this.$form.find("input[type='file']").on('change', function(e)
            {
                var name = $(this).attr('name'),
                    file = e.target.files[0],
                    reader = new FileReader();

                if (file !== undefined) {
                    reader.onload = function(evt) {
                        self.cachedFiles[name] = new CacheFile(name, file.name, evt.target.result);
                    };

                    reader.readAsBinaryString(file);
                }
                else if (name in self.cachedFiles) {
                    delete self.cachedFiles[name];
                }
            });
        }
    };

    var methods = {
        submit: function (data) {
            var daf = this.data('daf-data')
            if (daf) {
                daf.submit(data);
            }
        }
    };

    $.fn.djangoAjaxForms = function(options)
    {
        var opts = $.extend({
            fieldIdSelector: "div_id_",
            fieldErrorClass: "form-control-feedback",
            errorClass: "has-danger",
            cacheFilesAttr: "[data-ajax-submit-cachefiles]",
            canSubmitFn: null,
            onRenderErrorFn: null,
        }, $.fn.djangoAjaxForms.defaults, options);

        function DjangoAjaxForms($form)
        {

            $form.data('daf-data', this);

            var self = this,
                canSubmit = true;

            this.$form = $form;
            this.$form.on('submit', function(e) {
                e.preventDefault();

                if ( $.isFunction( opts.canSubmitFn ) ) {
                    canSubmit = opts.canSubmitFn(self.$form);
                }

                if (self.$form.length > 0 && canSubmit) {
                    self.submit();
                }
            });

            if (this.$form.filter(opts.cacheFilesAttr).length) {
                this.cachedFiles = new ManageCacheFile(this.$form);
            }
        }

        DjangoAjaxForms.prototype = {

            request: function request(url, data, isCustomData)
            {
                var options = {
                    data: data,
                    method: 'POST',
                    dataType: 'json'
                }

                if ( !isCustomData ) {
                    options.contentType = false;
                    options.processData = false;
                }

                return $.ajax(url, options);
            },

            submit: function submit(customData)
            {
                var self = this;

                this.$form.trigger("ajaxforms:beforesubmit");

                var url = this.$form.attr("action") || window.location.href;
                var disabled_fields = this.$form.find(":input:disabled");
                var data = customData;
                var isCustomData = true;

                if (customData === undefined) {
                    data = new FormData(this.$form.get(0));
                    isCustomData = false;
                }

                if (this.$form.filter(opts.cacheFilesAttr).length) {
                    data = this.cachedFiles.getFormData();
                }

                this.$form.find(':input').prop('disabled', true);
                this.$form.trigger("ajaxforms:submit");

                return this.request(url, data, isCustomData)

                    .done(function(response) {
                        self.$form.trigger("ajaxforms:submitsuccess");
                        self.$form.trigger('form:submit:success');

                        if( response.action ){
                            self.processResponse(response.action, response.action_url);
                        }
                    })

                    .fail(function ($xhr) {
                        var response = $xhr.responseJSON;

                        if (response && response.hasOwnProperty('extra_data')) {
                            var errors_list = response.extra_data.errors_list;

                            self.processFormErrors(self.$form, errors_list);
                        } else {
                            self.$form.trigger("ajaxforms:fail");
                        }

                        self.$form.find(':input').not(disabled_fields).prop('disabled', false);
                    })

                    .always(function() {
                        self.$form.trigger("ajaxforms:submitdone");
                    });
            },

            processFormErrors: function processFormErrors($form, errors_list)
            {
                var $wrappers = $form.find("[id^='" + opts.fieldIdSelector + "']");
                var nonfielderror = false;

                $wrappers.removeClass(opts.errorClass).find("." + opts.fieldErrorClass).remove();

                for (var fieldName in errors_list) {
                    var errors = errors_list[fieldName];

                    if (fieldName.search("__all__") >= 0) {
                        $form.trigger("ajaxforms:nonfielderror", [errors]);
                        nonfielderror = true;
                    } else {
                        var $field = $form.find("#" + opts.fieldIdSelector + fieldName);
                        var onChange = function () {
                            $field.removeClass('error', 200).find('.errorlist').fadeOut(200, function () {
                                $(this).remove();
                            });
                        };

                        $field.addClass(opts.errorClass).append(this.renderErrorList(errors));
                        $field.one('change', onChange);
                    }
                }
                if ( !nonfielderror ){
                    $form.trigger("ajaxforms:fielderror");
                }
            },

            processResponse: function processResponse(action, value)
            {
                switch (action) {
                    case 'refresh':
                        window.location.reload(true);
                        break;
                    case 'redirect':
                        window.location.href = value;
                        break;
                    default:
                        return;
                }
            },

            renderErrorList: function renderErrorList(errorsList)
            {
                var $elem = $("<div>").addClass(opts.fieldErrorClass).text(errorsList.join(', '));

                if ( $.isFunction( opts.onRenderErrorFn ) ) {
                    $elem = opts.onRenderErrorFn( $elem, errorsList );
                }

                return $elem;
            }
        };

        if ( methods[options] ) {
            return methods[ options ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof options === 'object' || ! options ) {
            return this.each(function()
            {
                new DjangoAjaxForms($(this));
            });
        } else {
            $.error( 'Method ' +  options + ' does not exist.' );
        }
    };

    $.fn.djangoAjaxForms.defaults = {};

})(jQuery);
<commit_msg>Fixed multiple instatiation of forms class.<commit_after>/* globals jQuery */

/******************************************************************
 * Author: Dipcode
 *
 * Django forms ajax submission
 * Example:
 *   <form data-ajax-submit>
 *****************************************************************/

(function($) {
    "use strict";

    function CacheFile(name, filename, file) {
        this.name = name;
        this.filename = filename;
        this.file = new Blob([file]);
    }

    function ManageCacheFile($form) {
        this.$form = $form;
        this.$inputFiles = this.$form.find("input[type='file']");
        this.cachedFiles = {};
        this.bindEvents();
    }

    ManageCacheFile.prototype = {

        getFormData: function getFormData()
        {
            this.$inputFiles.prop('disabled', true);

            var data = new FormData(this.$form.get(0));

            for (var i in this.cachedFiles) {
                var cachedFile = this.cachedFiles[i];
                data.append(cachedFile.name, cachedFile.file, cachedFile.filename);
            }

            this.$inputFiles.prop('disabled', false);

            return data;
        },

        bindEvents: function bindEvents()
        {
            var self = this;

            this.$form.find("input[type='file']").on('change', function(e)
            {
                var name = $(this).attr('name'),
                    file = e.target.files[0],
                    reader = new FileReader();

                if (file !== undefined) {
                    reader.onload = function(evt) {
                        self.cachedFiles[name] = new CacheFile(name, file.name, evt.target.result);
                    };

                    reader.readAsBinaryString(file);
                }
                else if (name in self.cachedFiles) {
                    delete self.cachedFiles[name];
                }
            });
        }
    };

    var methods = {
        submit: function (data) {
            var daf = this.data('daf-data');
            if (daf) {
                daf.submit(data);
            }
        }
    };

    $.fn.djangoAjaxForms = function(options)
    {
        var opts = $.extend({
            fieldIdSelector: "div_id_",
            fieldErrorClass: "form-control-feedback",
            errorClass: "has-danger",
            cacheFilesAttr: "[data-ajax-submit-cachefiles]",
            canSubmitFn: null,
            onRenderErrorFn: null,
            handleSubmitEvent: true,
        }, $.fn.djangoAjaxForms.defaults, options);

        function DjangoAjaxForms($form)
        {
            this.$form = $form;
            this.$form.data('daf-data', this);

            if (opts.handleSubmitEvent) {
                var self = this,
                    canSubmit = true;

                this.$form.on('submit', function(e) {
                    e.preventDefault();

                    if ( $.isFunction( opts.canSubmitFn ) ) {
                        canSubmit = opts.canSubmitFn(self.$form);
                    }

                    if (self.$form.length > 0 && canSubmit) {
                        self.submit();
                    }
                });
            }

            if (this.$form.filter(opts.cacheFilesAttr).length) {
                this.cachedFiles = new ManageCacheFile(this.$form);
            }
        }

        DjangoAjaxForms.prototype = {

            request: function request(url, data, isCustomData)
            {
                var options = {
                    data: data,
                    method: 'POST',
                    dataType: 'json'
                };

                if ( !isCustomData ) {
                    options.contentType = false;
                    options.processData = false;
                }

                return $.ajax(url, options);
            },

            submit: function submit(customData)
            {
                var self = this;

                this.$form.trigger("ajaxforms:beforesubmit");

                var url = this.$form.attr("action") || window.location.href;
                var disabled_fields = this.$form.find(":input:disabled");
                var data = customData;
                var isCustomData = true;

                if (customData === undefined) {
                    data = new FormData(this.$form.get(0));
                    isCustomData = false;
                }

                if (this.$form.filter(opts.cacheFilesAttr).length) {
                    data = this.cachedFiles.getFormData();
                }

                this.$form.find(':input').prop('disabled', true);
                this.$form.trigger("ajaxforms:submit");

                return this.request(url, data, isCustomData)

                    .done(function(response) {
                        self.$form.trigger("ajaxforms:submitsuccess");
                        self.$form.trigger('form:submit:success');

                        if( response.action ){
                            self.processResponse(response.action, response.action_url);
                        }
                    })

                    .fail(function ($xhr) {
                        var response = $xhr.responseJSON;

                        if (response && response.hasOwnProperty('extra_data')) {
                            var errors_list = response.extra_data.errors_list;

                            self.processFormErrors(self.$form, errors_list);
                        } else {
                            self.$form.trigger("ajaxforms:fail");
                        }

                        self.$form.find(':input').not(disabled_fields).prop('disabled', false);
                    })

                    .always(function() {
                        self.$form.trigger("ajaxforms:submitdone");
                    });
            },

            processFormErrors: function processFormErrors($form, errors_list)
            {
                var $wrappers = $form.find("[id^='" + opts.fieldIdSelector + "']");
                var nonfielderror = false;

                $wrappers.removeClass(opts.errorClass).find("." + opts.fieldErrorClass).remove();

                for (var fieldName in errors_list) {
                    var errors = errors_list[fieldName];

                    if (fieldName.search("__all__") >= 0) {
                        $form.trigger("ajaxforms:nonfielderror", [errors]);
                        nonfielderror = true;
                    } else {
                        var $field = $form.find("#" + opts.fieldIdSelector + fieldName);

                        var onChange = function () {
                            $field.removeClass('error', 200).find('.errorlist').fadeOut(200, function () {
                                $(this).remove();
                            });
                        };

                        $field.addClass(opts.errorClass).append(this.renderErrorList(errors));
                        $field.one('change', onChange);
                    }
                }
                if ( !nonfielderror ){
                    $form.trigger("ajaxforms:fielderror");
                }
            },

            processResponse: function processResponse(action, value)
            {
                switch (action) {
                    case 'refresh':
                        window.location.reload(true);
                        break;
                    case 'redirect':
                        window.location.href = value;
                        break;
                    default:
                        return;
                }
            },

            renderErrorList: function renderErrorList(errorsList)
            {
                var $elem = $("<div>").addClass(opts.fieldErrorClass).text(errorsList.join(', '));

                if ( $.isFunction( opts.onRenderErrorFn ) ) {
                    $elem = opts.onRenderErrorFn( $elem, errorsList );
                }

                return $elem;
            }
        };

        if ( methods[options] ) {
            return methods[ options ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof options === 'object' || ! options ) {
            return this.each(function()
            {
                var $this = $(this);
                var daf = $this.data('daf-data');

                if (!daf) {
                    new DjangoAjaxForms($this);
                }
            });
        } else {
            $.error( 'Method ' +  options + ' does not exist.' );
        }
    };

    $.fn.djangoAjaxForms.defaults = {};

})(jQuery);
<|endoftext|>