// Register the whole list template
Jaml.register('restaurant_index', function(container){ 
  div({cls: 'restaurant_index'},
    div({cls: 'header'},
      div({cls: 'h1'}, "Restaurant"),
      div({cls: 'h2'}, Jaml.t("Customer Ratings")),
      div({cls: 'h3'}, Jaml.t("Delivery <br>Fee")),
      div({cls: 'h4'}, Jaml.t("Earliest <br>Delivery"))
    ),
    Jaml.render('restaurant_index_filter', container),
    Jaml.render('restaurant_index_item', container), 
    div({id:'restaurant-index-filter-no' }, Jaml.t('No restaurants found, please refine filter options')),
    div({cls:'clear'}, '&nbsp;')
  )
});


// register the filter for the restaurants 
Jaml.register('restaurant_index_filter', function(list){

	var all = Jaml.t('All');
	var restaurants = [{ name: all, value: 'res-all'}];
		
	var i=0;
	var e=0;
	
	var len = list.restaurants.length;
	
	for (i = 0; i < len; i++) {
		var ft = list.restaurants[i].data.food_type;
		var found = false;
		
		var reslen = restaurants.length;
		for(e = 0; e < reslen; e++) {
			if(restaurants[e].name == ft) { found = true; break;}
		}
		
		if(!found) { restaurants.push({ name : ft, value : 'res-' + ft });  } 
	}


	// Creates the options for the other filters
	var ratings = [{name : all, value : 'rat-all'}, {name: Jaml.t('New Restaurants'), value:'rat-0'}, {name: '1', value: 'rat-1'}, 
					{name: '2', value: 'rat-2'},  {name: '3', value: 'rat-3'}, {name: '4', value: 'rat-4'}, {name: '5', value: 'rat-5'}];
	var livrai = [{name : all, value : 'fee-all'}, {name: Jaml.t('Free'), value: 'fee-free'}];
	var ouvert = [{name : all, value : 'del-all'}, {name: Jaml.t('Open'), value: 'del-open'}];
	
	
	// renders the filter items, and sets the global variable to indicate to the scroll function that it should scroll the filter
 	div({id: 'restaurant_index_filter', cls: 'restaurant_index_filter'}, 
 	h2(Jaml.t('Food Types')), div({cls:'separator'}), ul({id: 'filter-res'}, Jaml.render('restaurant_index_filter_item', restaurants)),
 	h2(Jaml.t('Ratings')), div({cls:'separator'}), ul({id: 'filter-rat'}, Jaml.render('restaurant_index_filter_item_stars', ratings)),
 	h2(Jaml.t('Delivery Fee')), div({cls:'separator'}), ul({id: 'filter-fee'}, Jaml.render('restaurant_index_filter_item', livrai)),
 	h2(Jaml.t('Opening')), div({cls:'separator'}), ul({id: 'filter-del'}, Jaml.render('restaurant_index_filter_item_del', ouvert)), 
 	'<script>glob_restaurant_list = true;</script>' );
});


// fills the filters with items
Jaml.register('restaurant_index_filter_item', function(item, idx){
	if(item.value.split('-')[1] == 'all') li(a({href:'#', cls:'selected restaurant-filter-item', id:'filter-' + item.value},item.name));
	else li(a({href:'#', cls:'restaurant-filter-item', id:'filter-' + item.value}, item.name));
});


// fills the filters with items open
Jaml.register('restaurant_index_filter_item_del', function(item, idx){
	if(item.value.split('-')[1] == 'open') li(a({href:'#', cls:'selected restaurant-filter-item', id:'filter-' + item.value},item.name));
	else li(a({href:'#', cls:'restaurant-filter-item', id:'filter-' + item.value}, item.name));
});


// fills the filters with items
Jaml.register('restaurant_index_filter_item_stars', function(item, idx){
	
	var stars = item.value.split('-');
	if(stars[1] == 'all') 
		li(a({href:'#', cls:'selected restaurant-filter-item', id:'filter-' + item.value},item.name));
	else if(stars[1] == '0')
		li(a({href:'#', cls:'restaurant-filter-item', id:'filter-' + item.value},item.name));
	else 
		li({style: 'display:inline;'}, img({src:'/images/empty.gif', cls:'restaurant-filter-item', id:'filter-' + item.value}));
});


// resgister a restaurant index
Jaml.register('restaurant_index_item', function(list){
  
  var logo = function (id, name, foodtype) {
  	
  		if(!foodtype) foodtype = '';
  		
 		return name ? 
	 	img({alt:'logo', src: '/restaurants/' + id + '/download/' + name})
	 	:   img({alt:'logo', src: '/images/foodtypes/' + astral.appConfig.site.lang + '/' +  foodtype.toLowerCase() +'.jpg'});
  }
  
  var len = list.restaurants.length;
  var i= 0;
  var count = 0;
  var postcode = typeof (list.postcode) != 'undefined' ? list.postcode.split(" ")[0].toUpperCase() : '';

  for (i = 0; i < len; i++) {
  	  var zones = null;
	  for (k in list.restaurants[i].data.postcode_areas) {
			if (list.restaurants[i].data.postcode_areas[k].postcode == postcode)
				zones = list.restaurants[i].data.postcode_areas[k].zones;
				list.restaurants[i].data.charge = list.restaurants[i].data.postcode_areas[k].fee;
	  }

  	  // sets the default filters and earlist delivery 
  	  var filter = '0.0.0.0';
  	  var default_filter = 'display:block';
  	  var earliest_delivery = list.restaurants[i].data.earliest_delivery;
  
	  // if the restauratn is closed
	  if(list.restaurants[i].data.earliest_delivery == 'CLOSED' || list.restaurants[i].data.earliest_delivery == 'FERME') {
	  	 filter = '0.0.0.1';
	  	 default_filter = 'display:none';
	  	 earliest_delivery = span({cls: 'closed'}, list.restaurants[i].data.earliest_delivery);
	  }
	  else { count++; }
	  
	  div({cls: (count % 2 == 1 ? 'bg_1' : 'bg_2') + ' nrestaurant', style: default_filter },
	    a({href: list.restaurants[i].data.path, rel: (list.restaurants[i]._id || list.restaurants[i].data._id)},
	      div({cls:'logo'}, logo((list.restaurants[i]._id || list.restaurants[i].data._id), list.restaurants[i].data.logo, list.restaurants[i].data.food_type) )
	    ),
	    div({cls: 'title'},
	      div({cls: 'title'}, a({href: list.restaurants[i].data.path, rel: (list.restaurants[i]._id || list.restaurants[i].data._id)}, list.restaurants[i].data.title)),
	      div({cls: 'food_type'}, list.restaurants[i].data.food_type),
	      div({cls: 'hours'}, list.restaurants[i].data.open_time)
	    ),
	    Jaml.render('restaurant_index_summary_reviews', list.restaurants[i].data),
	    div({cls: 'links'},
	      a({href: list.restaurants[i].data.path+'#/menu', cls: 'order_online'}, Jaml.t("View Menu")),
	      a({href: list.restaurants[i].data.path+'#/info', cls: 'info'}, Jaml.t("Info & Map")),
	      div({cls: 'deals'}, Jaml.render('restaurant_index_deal', list.restaurants[i].data.offers))
	    ),
	    div({cls: 'info'},
	      div({cls: 'delivery'}, Jaml.render('delivery-container', list.restaurants[i].data.fees || list.restaurants[i].data.charge)),
	      div({cls: 'earliest'}, earliest_delivery)
	    ),
	    div({cls: 'filters', style:'display:none;'}, filter),
	    div({cls: 'coverage-areas-container', style: 'display: none;'}, JSON.stringify(zones))
	  )
	
  } // end of for each
});

Jaml.register('delivery-container', function(fees){

	if (fees.min && fees.max) {
		
		if (fees.min == fees.max) {
			fees.min == 0 ? span({id: 'gratuit-container'}, Jaml.t("Free")) : span(Jaml.t("&pound;") + (fees.min || 0).toFixed(2))
		} else {
			span({cls: 'fees-range'}, Jaml.t("&pound;") + fees.min + ' .. ' + Jaml.t("&pound;") + fees.max)
		}
		
	} else {
		fee = isNaN(Number(fees)) ? 0 : Number(fees);
		fee == 0 ? span({id: 'gratuit-container'}, Jaml.t("Free")) : span(Jaml.t("&pound;") + (fee || 0).toFixed(2))
	}
	
});

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

Jaml.register('restaurant_index_summary', function(restaurant){
  div({cls: 'restaurant_summary clearfix'},
    div({cls: 'left'},
      div({cls: 'hours'}, restaurant.open_time),
      div({cls: 'map_streetview', style: 'background: url(http://maps.google.com/maps/api/staticmap?markers=color:red|' + restaurant.lat + ',' + restaurant.lng + '&zoom=15&size=225x170&sensor=false) no-repeat'})
    ),
    div({cls: 'center_wrap'},
      div({cls: 'links'},
        a({href: restaurant.path+'#/info', cls: 'info'}, "Restaurant<br> Info"),
        a({href: restaurant.path+'#/menu', cls: 'order_online'}, "Order<br> Online <span>from "+restaurant.title+"</span>"),
        a({href: restaurant.path+'#/reviews', cls: 'feedback'}, "Customer<br> Feedback")
      ),
      Jaml.render('restaurant_index_summary_reviews', restaurant)
    ),
    div({cls: 'right'},
      h4("Types of food served"),
      p(restaurant.food_types ? restaurant.food_types.join(", ") : restaurant.food_type)
    )
  )
});

Jaml.register('restaurant_index_summary_reviews', function(restaurant){
  var maxStars = 5;
  if(restaurant.ratings && restaurant.ratings.length == maxStars) {
    var absRate = 0, votesNum = 0, value, fullStars, halfStar,emptyStars, width = 15 ;
    for (var i = 0 ; i < restaurant.ratings.length; i++){
    	value = restaurant.ratings[i];
    	absRate += (i + 1) * value;
    	votesNum += value;
    }
    rate = votesNum > 0 ? Math.round(((absRate / votesNum) * 2) * 100)/100 / 2 : 0;
    fullStars = Math.round(rate);
    halfStar = ((rate - fullStars) > 0) ? 1 : 0;
    emptyStars = maxStars - fullStars - halfStar;
    div({cls: 'nratings'},
          div({cls: 'row'},
            div({cls: 'full rate', style: 'width: '+(width * fullStars)+'px;'}, ""),
            div({cls: 'half rate', style: 'width: '+ ( width * halfStar) +'px;'}, ""),
            div({cls: 'empty rate', style: 'width: '+(width * emptyStars)+'px;'}, ""),
            div({cls: 'votes'}, a({href: restaurant.path+'#/reviews'},
            	 String(votesNum) + ' ' + Jaml.t('ratings') + ' (' + Math.round(absRate * 20 / votesNum) + '%)')),
            div({cls: 'votes-count', style: 'display:none'}, '' + (fullStars))
          )
    );
  } else {
    var width = 15;
  	div({cls: 'nratings'},
  	      div({cls: 'row'},
  	        div({cls: 'empty rate', style: 'width: '+(width * 5)+'px;'}, ""),
  	        div({cls: 'votes'}, Jaml.t('New Restaurant'))
  	      )
  	);
  }
});

// area selection related templates
Jaml.register('select-zone-warning', function(container){
	div( { id: 'select-zone-warning-box'},
		h3(Jaml.t("Some restaurants only deliver to parts of") + " " + container.postcode),
		h3(Jaml.t("Please select your area to show the most accurate results.")),
		select({ id: 'coverage-zone-filter' },
			option({ value: "", selected: "selected" }, Jaml.t('Select...')),
			Jaml.render('select-zone-row', container.areas)
		)
	);
	div({id: 'zone-selected-box', style: 'display: none;'}, 
		h3(Jaml.t('Your coverage area is selected'),
			a({href: 'javascript:void(0);', cls: 'change-area-link'}, Jaml.t('(click to change)'))
		)
	)
})

Jaml.register('select-zone-row', function(zone){
	option({ value: zone }, zone);
})


