Router.configure({
  layoutTemplate:"layout",
  notFoundTemplate:"notFound",
  loadingTemplate:function () {
    if (Session.get('offline')) return null;
    return "loader";
  },
  waitOn:function () {
    if(Meteor.isServer){
        return [];
    } else {
      return [
        Meteor.subscribe('Items'),
        Meteor.subscribe('Userinfo'),
        Meteor.subscribe('Bills')
      ];
    }
  },
  onBeforeAction: function(){
    if ( Meteor.userId() ){
      this.next();
    } else this.render('login');
  }
});

Router.route('/', function () {
  this.render('home');
},{
  name:'home'
});

Router.route('/items/show/', function () {
  this.render('items',{data:{
    work:''
  }});
},{
  name:'items_show_all'
});


Router.route('/items/show/:_id', function () {
  var data = Items.findOne({_id:this.params._id})

  if (!data) {
    this.render('notFound',{
      data:"Die ID \"" + this.params._id + "\" weist auf keinen Datensatz."
    });
    return;
  }

  this.render('items_detail',{
    data
  });
},{
  name:'items_show'
});

Router.route('/items/add', function () {
  this.render('items_add');
},{
  name:'items_add'
});

Router.route('/items/edit/:_id', function () {
  this.render('items_add',{
    data:{
      data:Items.findOne({_id:this.params._id}),
      edit:true
    }
  });
},{
  name:'items_edit'
});

Router.route('/settings', function () {
  this.render('settings');
},{
  name:'settings'
});

Router.route('/bill/add', function () {
  this.render('bill_add',{data:{ids:[]}});
},{
  name:'bill_add'
});

Router.route('/bill/show', function () {
  this.render('bill_show');
},{
  name:'bill_show_all'
});

Router.route('/bill/show/:_id', function () {
  var data = Bills.findOne({_id:this.params._id});

  if (!data) {
    this.render('notFound',{
      data:"Die ID \"" + this.params._id + "\" weist auf keinen Datensatz."
    });
    return;
  }

  this.render('bill_detail',{
    data
  });
},{
  name:'bill_show'
});

Router.route('/bill/edit/:_id', function () {
  var data = Bills.findOne({_id:this.params._id});

  if (!data) {
    this.render('notFound',{
      data:"Die ID \"" + this.params._id + "\" weist auf keinen Datensatz."
    });
    return;
  }

  data.edit = true;

  this.render('bill_add',{
    data
  });
},{
  name:'bill_edit'
});
