var Backbone, _, synchronousEach, mySeeds, myPhrasesOwned, myGameState, myTransactions, myPlantedSymbols, myChallenges, myWeeds;

var SettingsView = Backbone.View.extend({

  settings : [{
    label: "Special Effects",
    name: 'specialEffects'
  }, {
    label: "Character Type",
    name: 'useTraditional',
    options: ["Simplified", "Traditional"]
  }, {
    label: "Transcription Type",
    name: 'useZhuyin',
    options: ["Pīnyīn", "Zhuyin"]
  }, {
    label: "Debug",
    name: 'debug'
  }, {
    label: "Show Tutorial",
    name: 'showTutorial'
  }],

  template :  _.template($('#settings-template').html()),

  events: {
    "change":          "change",
    "click .save-btn":   "save",
    "click .wipe-data-btn":   "wipeData",
    "click .add-money-btn": "addMoney"
  },
  
  change: function(evt){
    var name = $(evt.target).prop('name');
    myGameState.set(name, parseInt($(evt.target).val(), 10) > 0);
  },
  
  save: function(){
    console.log("saving...");
    myGameState.set('initialized', true);
    myGameState.save(null, { 
      success : function(){
        //Could be smoother but users will probably do this like once.
        window.location.reload();
      }
    });
  },
  
  wipeData: function(){
    if(!confirm("Are you sure you want to clear the game data? You will lose all your seeds and money.")) return;
    myGameState.save({
      "showTutorial": true,
      'initialized': false
    });
    var allModels = myTransactions.models.concat(
      myPlantedSymbols.models,
      mySeeds.models,
      myPhrasesOwned.models,
      myChallenges.models,
      myWeeds.models);
    synchronousEach(allModels, function(val, next){
      val.destroy({ success: next });
    }, function(){
      window.location.reload();
    });
  },
  
  addMoney: function(){
    myTransactions.create({amount : 1000});
  },

  render: function() {
    this.$el.html(this.template({
      settings: _.map(this.settings, function(setting){
        return _.extend({
          label: setting.name,
          value: myGameState.get(setting.name),
          options: ['Off', 'On']
        }, setting);
      }),
      debug: myGameState.get('debug'),
      initialized: myGameState.get('initialized')
    })).trigger('create');
    return this;
  }
});