if(!window['Chomp']) var Chomp = {};

Chomp.init.home = function(){
	Chomp.carouselInit();
	$('#recent_reviews nav a').click(function(e){
		e.preventDefault();
		$('#recent_reviews nav li').removeClass('selected');
		var target = $(this);
		target.parent().addClass('selected');
		var type = _.last(target.attr('href').split('#'));
		var url = '/us/carousel_ajax?feed_type=' + encodeURIComponent(type);
		Chomp.carouselAjaxFeed(url);
	});
};

Chomp.carouselInit = function(){
	var carousel = $('#recent_reviews .overview');
	Chomp.carouselStart = carousel.find('li').first().attr('id');
	carousel.carouFredSel({visibleItems: 6, width: 900, scroll: {
			items: 6,
			speed:1500,
			pauseOnHover: true,
			effect:'easeOutSine',
			onAfter: function(old_items, new_items, direction){
				var new_start = new_items.first().attr('id');
				if(new_start == Chomp.carouselStart){
					carousel.trigger('pause');
					var next_set = $('#recent_reviews nav li.selected').next();
					if(next_set.length == 0)
						next_set = $('#recent_reviews nav li').first();
					
					_.delay(function(){next_set.find('a').trigger('click');
					}, 1500);
				}
			}
		},
		auto: {
			pauseDuration: 7000
		}
	});
};

Chomp.carousel_item_tmpl = '<li id="app_<%= app_id %>">\
	<% if(typeof(user_icon) != "undefined" && user_icon != null){ %><a href="<%= full_name %>" class="user_icon"><img src="<%= user_icon %>_small" alt="user icon"></a><% } %>\
	<a href="<%= app_url %>"><img src="<%= app_icon %>" class="app_icon" alt="icon for <%= app_name %>"></a><p>\
	<% if(typeof(user_name) != "undefined"){ %><a href="/<%= full_name %>" class="<%= rating %>"><%= user_name %></a><br><% } %>\
	<strong><a href="<%= app_url %>"><%= app_name %></a></strong></p></li>';

Chomp.carouselAjaxFeed = function(url){
	var callback = function(json){
		$('#recent_reviews .spinner').hide();
		var ul = [];
		_.each(json, function(item){
			var data = {
				app_id: item.app.id,
				app_icon: item.app.icon_url,
				app_name: item.app.name.substring(0, 15),
				app_url: item.app.short_url_web
			};
			if(item.app.name.length > 15)
				data.app_name += '...';
			if(item.user){
				data['full_name'] = encodeURIComponent(item.user.displayname);
				data['user_name'] = item.user.displayname.substring(0,10);
				if(item.user.displayname.length > 10)
					data['user_name'] += '...';
				data['user_icon'] = item.user.avatar_url || null;
			}

			if(item.rating)
	            data['rating'] = (item.rating.rating > 0) ? 'positive':'negative';
	        	
			var li = _.template(Chomp.carousel_item_tmpl, data);
			ul.push(li);
		});
		if(ul.length > 0){
			var carousel = $('#recent_reviews .overview');
			carousel.html(ul.join(''));
			Chomp.carouselStart = carousel.find('li').first().attr('id');
			carousel.trigger('play');
		}
	};
	$('#recent_reviews .spinner').show();
	//TODO: check for previously fetched data
	$('#recent_reviews .overview').trigger('pause');
	$.getJSON(url, callback);
};

