User = function(data) {
  this.data = {};
  this.errors = [];
  this.validations = [];
  
  for (var key in data) {
    this.data[key] = data[key];
  }
  
  this.validates_presence_of('first_name');
  this.validates_presence_of('last_name');
  this.validates_presence_of('email');
  this.validates_presence_of('password');
  
  this.validates_confirmation_of('email');
  this.validates_confirmation_of('password');
  
}

User.prototype = {
  validates_presence_of: function(field, opts) {
    var self = this;
    this.validations.push(function(){
      if(!self.data[field] || self.data[field] == '') {
        self.errors.push(field + " should not be blank")
      }
    })
  },
  validates_confirmation_of: function(field, opts) {
    var self = this;
    this.validations.push(function(){
      if(self.data[field] != self.data[field+'_confirmation']) {
        self.errors.push(field + " should match confirmation")
      }
    })    
  },
  valid: function() {
    var self = this;
    _.each(this.validations, function(f) {
      f.call()
    })
    return this.errors.length == 0;
  },
    
  field_wrapper: '.user_edit',
  fields: [
    { name: 'first_name',            sel: 'input:text[name=first_name]',  validations: 'cannot be blank' },
    { name: 'last_name',             sel: 'input:text[name=last_name]',   validations: 'cannot be blank' },
    { name: 'email',                 sel: 'input:text[name=email]',       validations: 'cannot be blank' },
    { name: 'email_confirmation',    sel: 'input:text[name=email_confirmation]', dont_save: true },
    { name: 'phone',                 sel: 'input:text[name=phone]' },
    { name: 'password',              sel: 'input:text[name=password]',              dont_save: true },
    { name: 'password_confirmation', sel: 'input:text[name=password_confirmation]', dont_save: true },
    { name: 'addresses',             container: '.address_row', fields: [
      { name: 'nickname',            sel: "select[name$='\[nickname\]']" },
      { name: 'address_1',           sel: "input:text[name$='\[address_1\]']" },
      { name: 'address_2',           sel: "input:text[name$='\[address_2\]']" },
      { name: 'town',                sel: "input:text[name$='\[town\]']" },
      { name: 'postcode',            sel: "input:text[name$='\[postcode\]']" },
    ]},
    { name: 'notifications_special_offers_email', sel: 'input:checkbox[name=notifications_special_offers_email]', checkbox: true },
    { name: 'notifications_special_offers_sms',   sel: 'input:checkbox[name=notifications_special_offers_sms]',   checkbox: true },
    { name: 'notifications_order_conf_email',     sel: 'input:checkbox[name=notifications_order_conf_email]',     checkbox: true },
    { name: 'notifications_order_conf_sms',       sel: 'input:checkbox[name=notifications_order_conf_sms]',       checkbox: true },
    { name: 'notifications_news_updates_email',   sel: 'input:checkbox[name=notifications_news_updates_email]',   checkbox: true },
    { name: 'notifications_news_updates_sms',     sel: 'input:checkbox[name=notifications_news_updates_sms]',     checkbox: true }
  ],
  
  fetch_attributes: function() {
    for (field in this.fields) {
      // If there are subfields...
      if(this.fields[field].fields && this.fields[field].fields.length > 0) {
        this.data[this.fields[field].name] = [];
        var ctx = this;
        
        $(this.field_wrapper + ' ' + this.fields[field].container).each(function(idx, el){
          var row = {};
          for(subfield in ctx.fields[field].fields) {
            var sel = ctx.fields[field].fields[subfield].sel;
            var val = $(el).find(sel).val();
            row[ctx.fields[field].fields[subfield].name] = val;
          }
          if(!_.all(_.values(row), function(v){ return v == '' || v == null || v == undefined})) {
            ctx.data[ctx.fields[field].name].push(row);              
          }          
        });
      } else {
        if(this.fields[field].checkbox) {
          var val = $(this.field_wrapper + ' ' + this.fields[field].sel).is(':checked');
        } else {
          var val = $(this.field_wrapper + ' ' + this.fields[field].sel).val();          
        }
        this.data[this.fields[field].name] = val;
      }
    }
  },
  
  validate: function() {
    var valid = true;
    for (field_idx in this.fields) {
      var field = $('.user_edit' + this.fields[field_idx].sel);

      if(this.fields[field_idx].validations) {
        if(this.fields[field_idx].validations == "cannot be blank" && field.val() == '') {
          valid = false;
          field.parent().removeClass('ok').addClass('err');
          if(field.next().length == 0) {
            field.parent().append(Jaml.render('under_err', "Please type in your full name"));
            field.next().slideDown();
          }
        } else {
          field.parent().removeClass('err').addClass('ok');
          if(field.next().length != 0) {
            field.next().slideUp(300, function(){ $(this).remove() })
          }
        }
      }
    }
    return valid;
  },
  
  postcode: function() {
    if(!this.data.addresses || this.data.addresses.length == 0) return null;
    return this.data.addresses[0].postcode;
  },
  
  customer_name: function() {
    return this.data.first_name + " " + this.data.last_name;
  }
}
