var _, selectedLocations, synchronousEach, myGameState, myPlantedSymbols, toast, quiz;
var showTutorial = function(steps, done){
  //Tries to prevent click-through bugs
  $(document).on('vmousedown', '.ui-popup-container', function(evt){
    evt.preventDefault();
  });
  var popupTemplate = _.template('<div data-role="popup"><%= message %><center><a class="ok-popup" data-role="button" data-inline="true" data-theme="e">O.K.</a></center></div>');
  synchronousEach(steps, function(step, next){
    if(!step.before) step.before = function(t){t();};
    if(!step.beforeNext) step.beforeNext = function(t){t();};
    step.before(function(){
      var $popup = $(popupTemplate(step));
      $popup.css('max-width', "400px");
      $.mobile.pageContainer.append($popup);
      $popup.trigger('create');
      $popup.popup({
        theme : 'e',
        history: false,
        dismissible: false,
        transition: myGameState.get('specialEffects') ? "slideup" : "none"
      });
      $popup.popup("open");
      $popup.one("popupafterclose", function( event, ui ) {
        //console.log('popup closed');
        $popup.remove();
        step.beforeNext(function(){
          window.setTimeout(next, 400);
        });
      });
    });
  }, done);
};


var mySteps = [{
  message: "<h3>Thanks for playing 中文 Garden!</h3><p>This tutorial will show you how it works.</p>"
}, {
  message: "<p>Let's begin by planting a character-flower.</p><p>Tap one of the dirt patches on the left side of the field.</p>",
  beforeNext: function(trigger) {
    selectedLocations.on('add', function self(loc){
      if(loc.get('x') < 4) {
        selectedLocations.off('add', self);
        trigger();
      }
    });
  }
}, {
  message: "<p>Now you need to choose a character to plant there. Start with <b>你</b>(Nǐ).</p>",
  beforeNext: function(trigger) {
    myPlantedSymbols.on('add', function self(symbol){
      if(symbol.get('spid') === "你") {
        myPlantedSymbols.off('add', self);
        trigger();
      }
    });
  }
}, {
  message: "<h3>Good job!</h3><p>Now plant <b>好</b>(hǎo) next to it.</p>",
  beforeNext: function(trigger) {
    myPlantedSymbols.on('add', function self(symbol){
      if(symbol.get('spid') === "好") {
        //TODO: Check the next-to-it part
        myPlantedSymbols.off('add', self);
        trigger();
      }
    });
  }
}, {
  message: "<h3>Way to go!</h3><p>You planted <b>你好</b>(Nǐ hǎo), which means hello. Remember that, there will be a quiz...</p>"
}, {
  message: "<p>In a few minutes your characters will bloom. When they do you can sell them to make money.</p>"
}, {
  //Picture of highlighted bouquet
  message: "<p>If you sell multiple characters at once you get a bouquet bonus.</p>" + 
    "<p>All the characters in a bouquet have to form words or phrases you bought from the shop.</p><p> Let's go to the shop now...</p>",
  beforeNext: function(trigger) {
    $('#shopPage').one('pageshow', function(){
      $('.pointer').remove();
      trigger();
    });
    $('#fieldPage').append('<div class="pointer"><div class="pointer-point"></div></div>');
  }
}, {
  message: "<p>Buy <b>你好</b> so you can get a bouquet bonus for the characters you just planted.</p>"
}, {
  message: "<p>It's time to sell your flowers. Select them both then press the sell button.</p>",
  before: function(trigger) {
    //Things could go wrong here
    var ival = setInterval(function(){
      if(myPlantedSymbols.findWhere({ spid : "好"}).isBlooming()) {
        trigger();
        clearInterval(ival);
        //Override onPluck to train the user to pluck the bouquet.
        var prevOnPluck = window.onPluck;
        window.onPluck = function(evt) {
          if(selectedLocations.length < 2) {
            toast("<p>Select both flowers at once so you get a bouquet bonus.</p>");
            return;
          }
          window.onPluck = prevOnPluck;
          prevOnPluck(evt);
        };
      }
    }, 1000);
  }
}, {
  message: "<p>In order to get paid you need to pass a quiz.</p>",
  before: function(trigger) {
    quiz.once('start', trigger);
  }
}, {
  message: "<p>Congratulations, you completed the tutorial! Try completing some of the challenges next...</p>",
  before: function(trigger) {
    $('#fieldPage').one('pageshow', trigger);
  },
  beforeNext: function(trigger) {
    var removePointer = _.once(function(){
      $('.ch-pointer').remove();
      trigger();
    });
    window.setTimeout(removePointer, 6000);
    $(document).one('panelbeforeopen', removePointer);
    $('.challenge-btn').append('<div class="pointer ch-pointer"><div class="pointer-point"></div></div>');
  }
}];

myGameState.on("ready", function(){
  console.log("game ready...");
  window.setTimeout(function(){
    if(myGameState.get("showTutorial")) {
      showTutorial(mySteps, function(){
        myGameState.set('showTutorial', false);
        myGameState.save();
      });
    }
  }, 2000);
});
