Jaml.register('restaurant', function(container) {
  div({cls: 'tabs'},
    a({href: '#/menu', cls: 'menu sel', rel: container.restaurant.data._id}, Jaml.t("Menu")),
    a({href: '#/info', cls: 'info', rel: container.restaurant.data._id}, Jaml.t("Info")),
    a({href: '#/reviews', cls: 'reviews', rel: container.restaurant.data._id}, Jaml.t("Reviews"))
  );
  div({cls: 'restaurant_wrapper'},
    div({cls: 'info_wrapper', id: container.restaurant.data._id + '-info', style: 'display: none'},
      Jaml.render('restaurant_info', container.restaurant)
    ),
    div({cls: 'reviews_wrapper', id: container.restaurant.data._id + '-reviews', style: 'display: none'},
      Jaml.render('restaurant_reviews', container)
    ),
    div({cls: 'menu_wrapper', id: container.restaurant.data._id + '-menu'},
      Jaml.render('menu', container.restaurant)
    ),
    div({cls: 'deals_wrapper', id: container.restaurant.data._id + '-deals', style: 'display: none'},
      Jaml.render('restaurant_deals', container.restaurant)
    )
  )
});

Jaml.register('restaurant_review', function(review) {
  var rating = "";
  if(Number(review.doc.rating) == 1) rating = Jaml.t("Terrible!");
  if(Number(review.doc.rating) == 2) rating = Jaml.t("Sub-par");
  if(Number(review.doc.rating) == 3) rating = Jaml.t("Adequate");
  if(Number(review.doc.rating) == 4) rating = Jaml.t("Recommended");
  if(Number(review.doc.rating) == 5) rating = Jaml.t("Fantastic!");

  var truncated_name = function(full_name) {
    var split_name = full_name.split(" ");
    for(var i=0; i< split_name.length; i++) {
      split_name[i] = split_name[i].substr(0,1).toUpperCase() + split_name[i].substr(1);
    }
    if(split_name.length >= 2) {
      var ret = split_name[0];
      if(split_name[1] && split_name[1][0]) ret += " " + split_name[1][0];
      return ret;
    } else {
      return split_name.join(" ");
    }
  }

  div({cls: 'review'},
    div({cls: 'review_date'}, new Date(review.doc.confirmed_at).inWordsSinceNow + " "+ Jaml.t("ago")),
    div({cls: 'opinion'}, truncated_name(review.doc.customer_name) + " "+ Jaml.t("says"), span({cls: 'r'+review.doc.rating}, rating)),
    div({cls: 'review_txt'}, "\""+review.doc.review.replace(/\n/, '<br/>')+"\"")
  )
});

Jaml.register('restaurant_reviews', function(container) {
  div({cls: 'lft'},
    h1(Jaml.t("Recent reviews of") + " " + container.restaurant.data.title),
    div({cls: 'reviews'},
      (container.reviews.rows.length > 0) ? Jaml.render('restaurant_review', container.reviews.rows) : div({cls: 'no-reviews'}, Jaml.t("Sorry, no reviews yet!"))
    )
  );
  if(container.restaurant.data.ratings) {
    var max = _.max(container.restaurant.data.ratings, function(o){ return o });
    div({cls: 'right'},
      h1(Jaml.t("Overall rating") + ": " + container.restaurant.data.rating + "%"),
      div({cls: 'ratings'},
        div({cls: 'row'},
          div({cls: 'title'}, Jaml.t("Fantastic!")),
          div({cls: 'r r5', style: 'width: ' + (160*(container.restaurant.data.ratings[4]/max))+'px;'}, "&nbsp;"),
          div({cls: 'votes'}, String(container.restaurant.data.ratings[4]))
        ),
        div({cls: 'row'},
          div({cls: 'title'}, Jaml.t("Recommended")),
          div({cls: 'r r4', style: 'width: ' + (160*(container.restaurant.data.ratings[3]/max))+'px;'}, "&nbsp;"),
          div({cls: 'votes'}, String(container.restaurant.data.ratings[3]))
        ),
        div({cls: 'row'},
          div({cls: 'title'}, Jaml.t("Adequate")),
          div({cls: 'r r3', style: 'width: ' + (160*(container.restaurant.data.ratings[2]/max))+'px;'}, "&nbsp;"),
          div({cls: 'votes'}, String(container.restaurant.data.ratings[2]))
        ),
        div({cls: 'row'},
          div({cls: 'title'}, Jaml.t("Sub-par")),
          div({cls: 'r r2', style: 'width: ' + (160*(container.restaurant.data.ratings[1]/max))+'px;'}, "&nbsp;"),
          div({cls: 'votes'}, String(container.restaurant.data.ratings[1]))
        ),
        div({cls: 'row'},
          div({cls: 'title'}, Jaml.t("Terrible!")),
          div({cls: 'r r1', style: 'width: ' + (160*(container.restaurant.data.ratings[0]/max))+'px;'}, "&nbsp;"),
          div({cls: 'votes'}, String(container.restaurant.data.ratings[0]))
        )
      )
    );
  }
  div({style: 'clear: both'});
});

Jaml.register('restaurant_deals', function(restaurant) {
});

Jaml.register('restaurant_offers', function(restaurant) {
  if(restaurant.data.offers && restaurant.data.offers.length > 0) {
    div({cls: 'menu_section'},
      h3(Jaml.t('Special Offers')),
      Jaml.render('restaurant_offer', restaurant.data.offers)
    )
  }
});
Jaml.register('restaurant_offer', function(offer) {
  div({cls: 'offer'}, offer.description)
});

Jaml.register('div', function(content) {
  div(content)
});

Jaml.register('restaurant_info', function(restaurant) {
 div({cls: 'lft'},
    div({cls: 'top'},
      h1(restaurant.data.title),
      div({cls: 'address'}, (restaurant.data.address_1 + ", " + restaurant.data.town + ", " + restaurant.data.postcode))
    ),
    div({cls: 'detail'},
      div({cls: 'food_types'}, restaurant.data.food_type),
      div({cls: 'opening_times'},
        (Jaml.t("Delivers") + ": " + restaurant.todays_opening_times()),
        a({cls: 'see_all_times', href: '#'}, Jaml.t("See all times"))
      ),
      div({cls: 'all_opening_times', style: 'display: none'},
        Jaml.render('div', restaurant.all_opening_times())
      ),
      div({cls: 'description'}, restaurant.data.meta_description)
    ),
    div({cls: 'stats'},
      div({cls: 'row'},
        span({cls: 'def'}, Jaml.t("Rating")),
        span({cls: 'val'}, (restaurant.data.rating ? restaurant.data.rating + "%" : Jaml.t('new'))),
      div({cls: 'row'},
        span({cls: 'def'}, Jaml.t("Pay cash")),
        span({cls: 'tick'}, Jaml.t("Yes"))
      ),
      div({cls: 'row'},
        span({cls: 'def'}, Jaml.t("Order online")),
        span({cls: 'tick'}, Jaml.t("Yes"))
      ),
      div({cls: 'row'},
        span({cls: 'def'}, Jaml.t("Pay online")),
        span({cls: 'tick'}, Jaml.t("Yes"))
      ),
      div({cls: 'sep'}),
      div({cls: 'row'},
        span({cls: 'def'}, Jaml.t("Wait time")),
        span({cls: 'val'}, (restaurant.data.wait_delivery + " " + Jaml.t("mins")))
      ),
      div({cls: 'row'},
        span({cls: 'def'}, Jaml.t("Min spend")),
        span({cls: 'val'}, (restaurant.data.minimum_order_value == 0 ? Jaml.t('free') : Jaml.t("&pound;") + restaurant.data.minimum_order_value.toFixed(2)))
      ),
      (restaurant.data.delivery_zones && restaurant.data.delivery_zones.length > 1 ?
            div({cls: 'row'}, Jaml.t("Delivery areas") + ":") : ''
	),
      (restaurant.data.delivery_zones && restaurant.data.delivery_zones.length > 1 ?
        (
            Jaml.render('restaurant_delivery_zone', restaurant.data.delivery_zones)
        ) :
        div({cls: 'row'},
          span({cls: 'def'}, Jaml.t("Delivery fee")),
          span({cls: 'val'}, (restaurant.data.delivery_charge == 0 ? Jaml.t('free') : Jaml.t('&pound;') + restaurant.data.delivery_charge.toFixed(2)))
        )
      ),
      div({cls: 'sep'}),
      a({href: '/contact', cls: 'your_business'}, Jaml.t("Is this your business?"))
    )
   )
  );
  div({cls: 'rgt', id: 'restaurant-info-map', style: ''});
  div({style: 'clear: both'});

});

Jaml.register('restaurant_delivery_zone', function(zone, idx) {
    div({cls: 'row'},
      span({cls: 'def', style:'width: 90px; padding-left: 30px;'}, zone.postcode),
      span({cls: 'val'}, (zone.charge == 0 ? Jaml.t('free') : Jaml.t("&pound;") + zone.charge.toFixed(2)))
    )
})

Jaml.register('menu', function(restaurant) {
  div({cls: 'menu_table_wrap'},
    table({cls: 'fw'},
      tr(
        td({cls: 'menu_section_col'},
          div({cls: 'menu_sections', id: 'menu-sections-'+restaurant.data._id},
            h3(Jaml.t('Menu Sections')),
            Jaml.render('menu_section_link', restaurant.menu_sections)
          )
        ),
        td({id: restaurant.data._id + '-menu-td', cls: 'menu_col'},
          div({cls: 'dish_search'},
            div({cls: 'dish_search_pad'},
              span({cls: 'input_wrapper'},
                input({id: (restaurant.data._id + '-q'), type: 'text', value: 'Search the menu...'}),
                a({id:(restaurant.data._id + '-reset'), cls:'reset', style:'display:none;', href:'#'}, 'x')
              )
              // span({cls: 'advanced_search'}, 'Advanced')
              // div({cls: 'vegetarian_only'},
              //   "Vegetarian only",
              //   input({type: 'checkbox', id: (restaurant.data._id + '-veggie'), name: 'veg'})
              // )
            )
          ),
          div({id:restaurant.data._id + '-no-results', cls:'no_results', style:'display:none;'}, Jaml.t("Your search for") + "'", span(''), "' "+ Jaml.t("returned 0 results")),
          div({cls: 'dish_menu_sections'},
              Jaml.render('restaurant_offers', restaurant),
              Jaml.render('menu_section', restaurant.menu_sections)
          )
        ),
        td({cls: 'order_col'},
          div({cls: 'final_order', id: 'final-order-'+restaurant.data._id},
            h3(Jaml.t('Your Order')),
            div({id: 'final-order-'+restaurant.data._id+'-items'})
          )
        )
      )
    )
  )
});

Jaml.register('menu_section', function(ms) {

  div({cls: 'menu_section', id: 'menu_section_' + ms.path()},
    h3({cls: 'title'}, ms.data.title),
    (ms.data.description ? p({cls: 'description'}, ms.data.description) : ''),
    table({cls: 'dishes'},
      Jaml.render('dish', ms.dishes)
    )
  );
});

Jaml.register('menu_section_link', function(ms) {
  a({href: '#', rel: ms.path(), cls: 'menu_section_link'}, ms.data.title)
});

Jaml.register('dish', function(dish, idx) {
  var bg_col = ('bg_'+((idx%2)+1));
  var no_pad = (dish.optionGroups && dish.optionGroups.length > 0) ? ' no_pad' : '';

  tr({cls: bg_col + no_pad + ' dish', id: ('dish_'+dish.path())},
    td({cls: 'title'},
      div({cls: 'title_wrap'},
        dish.data.title,
        (dish.data.vegetarian ? img({src: '/images/v.gif', alt: 'Veg', title: 'Vegetarian'}) : ''),
        (dish.data.description ? p({cls: 'dish_description', style: 'display: block;'}, dish.data.description) : ''),
        (dish.data.comments ? div({cls: 'dish_comments', style: 'display: block;'}, Jaml.render('dish_comment', dish.data.comments)) : ''),
        Jaml.render('dish_rating', dish)
      )
    ),
    td({cls: 'quantity'}, '&nbsp;'),
    td({cls: 'price', id: (dish.path()+"_price")}, (Jaml.t("&pound;")+dish.price().toFixed(2))),
    td({cls: 'actions'},
      a({cls: 'add', href: '#', rel: dish.path(), title: Jaml.t('Add this dish to your order')}, '+'),
      a({cls: 'take inactive', href: '#', rel: dish.path(), title: Jaml.t('Remove this dish from your order')}, '-')
    )
  );

  if(dish.optionGroups && dish.optionGroups.length > 0) {
    // var opt_titles = _.map(dish.visible_groups(), function(g){ return g.data.title.toLowerCase(); }).join(", ");
    tr({cls: bg_col + ' dish_options', id: "dish_" + dish.path() + "_opts"},
      td({colspan: 4},
        a({cls: 'customise', id: ("dish_"+dish.path()+"_options_link"), href: '#', rel: dish.path()}, (Jaml.t('Customise dish')))
      )
    );
  }

});

Jaml.register('dish_info', function(dish){
  tr({cls: 'dish_info_wrap', id: ('dish_' + dish.path() + '_info')},
    td({colspan: 4},
      div({cls: 'dish_info', style: 'display: none;'},
        img({src: '/images/del/tikka.jpg'}),
        h2('Chicken Tikka Masala'),
        div({cls: 'l'}, strong('Cuisine:'), "Indian"),
        div({cls: 'l'}, strong('Vegetarian:'), Jaml.t("No")),
        div(strong('Spicy:'), "Medium"),
        div({cls: 'ingredients'}, strong('Main ingredients:'), "Chicken, Yoghurt, Cream, Tomato, Onion, Spices"),
        div({cls: 'description'},
          p("Chicken Tikka Masala is a curry dish in which roasted chicken chunks (tikka) are served in a rich red, creamy, lightly spiced, tomato-based sauce."),
          p("The sauce usually includes tomatoes, frequently as puree, and either/or both cream and/or coconut cream and various spices. The sauce or chicken pieces (or both) are sometimes coloured orange or red with food dyes or with red foodstuffs such as turmeric powder, paprika powder or tomato puree.")
        ),
        div(strong(Jaml.t('Customers also bought') + ':'),
          a({href: '#'}, "Rice"),
          a({href: '#'}, "Onion Baaji"),
          a({href: '#'}, "Keema Naan")
        )
      )
    )
  );
});

/**
 * Dish commments template
 */
Jaml.register('dish_comments', function(dish) {
  if (!dish.data.comments) return;

  tr({cls: 'dish_comments_wrap', id: ('dish_' + dish.path() + '_comments')},
    td({colspan: 4},
      div({cls: 'dish_comments', style: 'display: none;'},
        h3(Jaml.t('Comments') + ':'),
        Jaml.render('dish_comment', dish.data.comments)
      )
    )
  );
});

/**
 * Comment template
 */
Jaml.register('dish_comment', function(comment) {
  // div({cls: 'dish_comment'},
    // span({cls: "name"}, "Name: " + comment.author),
    // span({cls: "date"}, "Posted on: " + comment.created_at),
    div({cls: "comment"}, Jaml.t('Customer comment') + ': "' + comment + '"')
  // );
});

Jaml.register('dish_rating', function(dish) {
  if(dish.data.rating) {
    div({cls: 'dish_rating_wrap', title: Jaml.t('Customer rating')},
      div({cls: 'dish_rating', style: 'width: ' + dish.data.rating + '%;'},
        String(dish.data.rating)
      )
    );
  }

  //show comments icon if there are any comments on the dish
  if (dish.data.comments_count) a({cls: 'comments', rel: dish.path(), href: '#'}, String(dish.data.comments_count));
});

Jaml.register('dish_options', function(dish) {
  div({cls: 'customise_dish', id: ('dish_'+dish.path()+'_options'), style: 'display: none;'},
    div({cls: 'dish_option_group'},
      Jaml.render('option_group', dish.optionGroups)
    )
  );
});

Jaml.register('option_group', function(option_group) {
  var rendered_options;
  if(option_group.data.select_type == 'radio') {
    rendered_options = Jaml.render('options_radio', option_group.options);
  } else if(option_group.data.select_type == 'select') {
    rendered_options = label({cls: 'dish_option_label'},
      select({name: option_group.path(), id: option_group.path(), cls: 'dish_option_inp'},
        Jaml.render('options_select', option_group.options)
      )
    );
  } else if(option_group.data.select_type == 'checkbox') {
    if(option_group.options.length > option_group.number_of_columns()) {
      // Need to make a table with number_of_columns containing dish options...
      var rows = [];
      var cur_row = [];
      for(var i=0; i< option_group.options.length; i++) {
        cur_row.push(Jaml.render('options_checkbox', option_group.options[i]));
        if( i % option_group.number_of_columns() == (option_group.number_of_columns() - 1) ||
          i == option_group.options.length - 1) {
          rows.push(cur_row);
          cur_row = [];
        }
      }
      rendered_options = table(
        Jaml.render('option_table_rows', rows)
      );
    } else {
      rendered_options = Jaml.render('options_checkbox', option_group.options);
    }
  }
  if(option_group.data.price) {
    var price = Jaml.t("&pound;") + option_group.data.price.toFixed(2);
    if(option_group.options.length > 1) {
      price += " " + Jaml.t("each");
    }
  } else {
    var price = '';
  }
  var hidden = option_group.visible ? '' : 'display: none;';
  div({cls: 'dish_options', id: 'group_' + option_group.path(), style: hidden},
    div(
      span({cls: 'dish_option_group_title'}, option_group.data.title + ":"), price
    ),
    rendered_options
  );
});

Jaml.register('option_table_rows', function(row) {
  tr(
    Jaml.render('option_table_col', row)
  );
});

Jaml.register('option_table_col', function(col) {
  td(col);
});

Jaml.register('options_radio', function(option) {
  var imp_data = {
    type: 'radio',
    name: (option.prnt.path()),
    id: option.path(),
    cls: "dish_option_inp"
  };
  if(option.data.dish_option_collection) { imp_data.cls += " related_options"; }
  if(option.selected) { imp_data.checked = "checked"; }
  label({cls: 'dish_option_label'},
    input(imp_data),
    option.data.title + (option.data.price ? (": " + Jaml.t("&pound;") + option.price().toFixed(2)) : "")
  );
});

Jaml.register('options_select', function(opt) {
  var imp_data = {id: opt.path()};
  if(opt.selected) { imp_data.selected = "selected"; }
  option(imp_data,
    opt.data.title + (opt.data.price ? (": " + Jaml.t("&pound;") + opt.price().toFixed(2)) : "")
  );
});

Jaml.register('options_checkbox', function(option) {
  var imp_data = { type: 'checkbox', name: ("" + option.prnt.prnt.idx + "_" + option.prnt.idx), cls: "dish_option_inp", id: option.path() };
  if(option.data.by_default) { imp_data.checked = "checked"; }
  if(option.prnt.options.length == 1 && option.prnt.data.title == option.data.title) {
    var name_and_price = "Yes" + (option.data.price ? (": "+Jaml.t("&pound;") + option.price().toFixed(2)) : "");
  } else {
    var name_and_price = option.data.title + (option.data.price ? (": " + Jaml.t("&pound;") + option.price().toFixed(2)) : "");
  }
  label({cls: 'dish_option_label'},
    input(imp_data),
    name_and_price
  );
});

Jaml.register('order', function(order) {
  if(order.order_items.length == 0) {
    div({cls: 'no_order_items'}, Jaml.t("Please add some items to your order"));
  } else {
    div({cls: 'order_items'},
      Jaml.render('order_item', order.order_items)
    );
    div({cls: 'sub_total'}, (Jaml.t("Sub-total") + ": " + Jaml.t("&pound;") + order.sub_total().toFixed(2)));

    // div({cls:'right_links'}, a({href: '#', cls: 'special_instructions'}, "Add comments for the restaurant"));
    // div({style: 'display: none', cls: 'special_instructions_wrap'},
    //   div({cls:'row txt_label'}, "Any comments for the restaurant?"),
    //   textarea({cls: 'txt comment', name: 'special_instructions', rows: '3'}, order.data.special_instructions || '')
    // );

    if(order.sub_total() < order.restaurant.data.minimum_order_value) {
      if(order.sub_total() > 0) {
        var to_add = " (" + Jaml.t("add") + " " + Jaml.t("&pound;") + (order.restaurant.data.minimum_order_value - order.sub_total()).toFixed(2) + ")";
      } else {
        var to_add = '';
      }
      div({cls: 'minimum_order'}, (Jaml.t("Minimum") + ": " + Jaml.t("&pound;") + order.restaurant.data.minimum_order_value.toFixed(2)+to_add));
    } else {
      if(order.restaurant.accept_order_now()) {
        a({href: '#', cls: 'finalise'}, Jaml.t("Finalise Order"));
        div({cls: 'loading', style: 'display: none;'});
      } else {
        div({cls: 'minimum_order'}, Jaml.t("RESTAURANT CLOSED"))
      }
    }
  }
});

Jaml.register('order_item', function(order_item, idx){
  var new_item = _.include(order_item.order.new_items, order_item.path());
  div({cls: 'order_item ' + ('bg_'+((idx%2)+1)) + (new_item ? ' new_item' : ''), id: order_item.path(), style: (new_item ? 'display: none;' : '')},
    span({cls: 'price'},
      (Jaml.t('&pound;')+order_item.price().toFixed(2)),
      a({href: '#', cls: 'minus_1', rel: order_item.path()}, Jaml.t('remove')),
      a({href: '#', cls: 'plus_1', rel: order_item.path()}, Jaml.t('add'))
    ),
    ((order_item.data.quantity > 1 ? (order_item.data.quantity + " x ") : '') + order_item.data.title),
    Jaml.render('order_item_option', order_item.options)
  );
});

Jaml.register('order_item_option', function(order_item_option){
  if(order_item_option.data.options) {
    var options = _.pluck(order_item_option.data.options, 'title').join(", ");
  } else {
    var options = order_item_option.data.title;
  }
  div({cls: 'order_item_option'},
    (order_item_option.data.group == options) ? order_item_option.data.group : (order_item_option.data.group+": "+options)
  );
});


Jaml.register('activity_feed', function(activity) {
  div({cls: 'activity-wrap'},
    div({cls: 'activity-item'},
      div({cls: 'thumb t'+activity.thumb}),
      a({href: activity.link},
        (activity.name + " " + activity.action),
        span(activity.time)
      )
    )
  )
})





