// function onYouTubePlayerAPIReady() { }
$(function(){
var workspace = null,
page = null,
navigation = null,
homePage = null,
playlistPage = null,
campaignsPage = null,
videoDetailPage = null,
searchPage = null,
videoPlayerView = null,
videoListView = null,
commentListView = null,
searchResultView = null,
navigationView = null,
productCarouselView = null,
ytplayer = null;
var config = {
user_id : 'jXULVp4K-jH3_mnCxw0QlA',
defaultVideo: '0U6NACGxGpc',
defaultPlaylist: 'E50374490B19A652',
pagination: 12,
commentNumber: 5,
noResultString: 'No results found',
noCommentString: 'No comments found',
baseShareUrl: {
facebook: 'http://www.facebook.com/sharer.php?u=URL_PLACE' ,
gplus: 'https://plus.google.com/share?url=URL_PLACE',
twitter: 'http://twitter.com/share?url=URL_PLACE&via=DIESEL&text=MESSAGE_PLACE'
}
};
// ![ MODEL ] - Video Products
var VideoModel = Backbone.Model.extend();
// ![ COLLECTION ] - Videos Products
var CommentCollection = Backbone.Collection.extend({
model: VideoModel,
url: "data/data.json"
});
// ![ VIEW ] - Video Player
var VideoPlayerView = Backbone.View.extend({
el: $('#video_box').extend({
ytplayer : null
}),
events: {
'mouseenter' : 'showControls',
'mouseleave' : 'hideControls',
'click button.prev' : 'prevVideo',
'click button.next' : 'nextVideo'
},
model: new CommentCollection,
initialize: function(opts){
_.bindAll(this, 'render');
this.carousel = opts.carousel;
this.quickLinks = opts.quickLinks;
this.model.on('reset', this.render);
},
render: function() {
$(window).load($.proxy(function(){
this.$el.ytplayer = new YT.Player('ytplayer', {
height: '553',
width: '930',
wmode : 'transparent',
// videoId: config.defaultVideo, // Starting video
playerVars: {
wmode: "transparent",
'controls': 1,
'autohide': 1
},
events: {
'onReady' : $.proxy(function(){ // $.PROXY INCEPTION!
this.$el.ytplayer.loadPlaylist( config.defaultVideo, 0, 0, 'large' ); // Starting playlist
this.$el.ytplayer.stopVideo();
}, this)
}
}).addEventListener('onStateChange', _.bind(function(e){
var vid = e.target.getVideoUrl().split('v=')[1].substr(0,11);
if (e.data == 3 || e.data == 5) {
// render carousel and quick links
this.renderCarousel(vid);
this.renderLinks(vid);
}
if( e.data === 3 && workspace.currentSection == videoDetailPage){
var newVideoTitle = '';
$.ajax({
url: 'https://gdata.youtube.com/feeds/api/videos/' + vid + '?alt=json-in-script&v=2',
dataType: 'jsonp',
success: function(response){
newVideoTitle = response['entry']['title']['$t'];
videoDetailPage.changeTitle( newVideoTitle );
videoDetailPage.changeCommentLinks( vid );
videoDetailPage.changeShareLinks( vid, newVideoTitle );
videoDetailPage.changeTracking( vid );
},
error: function(err){
}
});
if(commentListView != null){
commentListView.destroyView()
}
commentListView = new CommentListView( vid );
}
}, this));
}, this));
},
renderCarousel: function(vid) {
this.carousel.empty();
var products = vid && this.model.get(vid) ? this.model.get(vid).toJSON().products : [];
if (!products.length) {
this.carousel.hide();
return;
}
this.carousel.render(products);
/* integrazione con store
var url = "http://www.diesel.localhost/get-price?&yooxcode[]=" + products.join('&yooxcode[]=');
$.get(url, _.bind(function(response) {
if (response) this.carousel.render(response);
else this.carousel.hide();
}, this), 'json');*/
},
renderLinks: function(vid) {
var link = vid && this.model.get(vid) ? this.model.get(vid).toJSON().link : false;
if (!link) {
this.quickLinks.hide();
return;
}
this.quickLinks.render(link);
},
showControls: function(force){
force = force ? true : false;
if( !(workspace.currentSection == videoDetailPage) || force ){
// this.$el.find('button').show();
}
},
hideControls: function(){
if( !(workspace.currentSection == videoDetailPage) ){
this.$el.find('button').hide();
}
},
prevVideo: function(){
this.$el.ytplayer.nextVideo();
},
nextVideo: function(){
this.$el.ytplayer.previousVideo();
}
});
// ![ MODEL ] - Video
var VideoModel = Backbone.Model.extend({
defaults: {
'id' : '',
'url' : '',
'playlist' : '',
'playlistPos' : 0,
'title' : 'Diesel - ',
'thumb_small': '',
'thumb_medium': '',
'thumb_large': ''
},
getThumb: function() {
return {
's' : this.get('thumb_small'),
'm' : this.get('thumb_medium'),
'l' : this.get('thumb_large')
}
}
});
// ![ MODEL ] - Video comments
var CommentModel = Backbone.Model.extend({
defaults: {
'user' : '',
'user_link' : '',
'text' : '',
'lapsed_time': ''
},
getText: function() {
return this.get('text');
}
});
// ![ VIEW ] - Video Item
var VideoView = Backbone.View.extend({
tagName: 'div',
className: 'video',
template: _.template( $('#tempVideo_tmpl').html() ),
events: {
'mouseenter' : 'showTitle',
'mouseleave' : 'hideTitle'
},
initialize: function(model) {
this.model = model;
_.bindAll(this, 'render');
},
render: function() {
this.$el.html( this.template(this.model.toJSON()) ).css({'opacity':0});
return this;
},
showTitle: function(){
this.$el.find('a').stop(true,true).animate({'opacity':0.99});
},
hideTitle: function(){
this.$el.find('a').stop(true,true).animate({'opacity':0});
}
});
// ![ VIEW ] - Video List
var VideoListView = Backbone.View.extend({
el: $('#videos').extend({
$videoList : $('#videos #videoList'),
$categoryTitle : $('#videos .categoryTitle'),
currentPlaylist: '',
currentQuery: '',
$pagination: $('#pagination'),
currentPage: 1,
isAlreadyPaginated: false
}),
events: {
'click #pagination .pages a' : 'handlePageNumber',
'click #pagination a.prev' : 'prevPage',
'click #pagination a.next' : 'nextPage'
},
initialize: function(plid, startIndex){
this.$el.currentPlaylist = plid;
this.$el.currentPage = 1;
this.$el.currentQuery = '';
this.collection = new VideoCollection();
this.collection.url = 'http://gdata.youtube.com/feeds/api/playlists/' + this.$el.currentPlaylist + '?alt=json-in-script&start-index=' + startIndex + '&max-results=' + config.pagination + '&v=2&orderby=published&callback=?',
this.collection.on('reset', this.render, this);
this.collection.fetch();
this.$el.$categoryTitle.find('span').hide().filter('[data-playlist='+plid+']').show();
},
empty: function(){
this.$el.$videoList.empty();
},
render: function(){
this.empty();
if(this.collection.length === 0){
this.$el.$videoList.append('
' + config.noResultString + '
')
} else {
this.collection.each(
$.proxy(function(v,k){
var video = new VideoView(v);
var videoEl = video.render().$el;
if((k)%4===0) {
videoEl.addClass('noMarginLeft');
}
this.$el.$videoList.append(videoEl);
videoEl.animate({
'opacity' : 0.99
}, 'slow' );
},this)
);
if(!this.$el.isAlreadyPaginated){
this.createPagination();
}
}
},
createPagination: function(){
var $pagesWrapper = this.$el.$pagination.find('.pages');
$pagesWrapper.empty();
for(var i=0; i' + (i+1) + '')
}
this.$el.isAlreadyPaginated = true;
},
changeContentByPage: function(){
this.collection.url = 'http://gdata.youtube.com/feeds/api/playlists/' + this.$el.currentPlaylist + '?alt=json-in-script&start-index=' + (((this.$el.currentPage-1)*config.pagination)+1) + '&max-results=' + config.pagination + '&orderby=published&v=2&callback=?'
this.collection.fetch();
},
handlePageNumber: function(e){
e.preventDefault();
var clicked = $(e.currentTarget);
if(!clicked.hasClass('current')){
this.empty();
this.$el.find('#pagination .pages a').removeClass('current');
clicked.addClass('current');
this.$el.currentPage = clicked.data('page');
this.changeContentByPage();
}
},
prevPage: function(e){
e.preventDefault();
var clicked = $(e.currentTarget);
if(this.$el.currentPage > 1){
this.empty();
this.$el.currentPage--;
this.$el.$pagination.find('.pages a').removeClass('current').eq(this.$el.currentPage-1).addClass('current');
this.changeContentByPage();
}
},
nextPage: function(e){
e.preventDefault();
var clicked = $(e.currentTarget);
if(this.$el.currentPage < this.$el.$pagination.find('.pages a').size()){
this.empty();
this.$el.currentPage++;
this.$el.$pagination.find('.pages a').removeClass('current').eq(this.$el.currentPage-1).addClass('current');
this.changeContentByPage();
}
},
destroyView: function() {
// COMPLETELY UNBIND THE VIEW
this.undelegateEvents();
this.$el.removeData().unbind();
this.$el.isAlreadyPaginated = false;
// Remove view from DOM
// this.remove();
// Backbone.View.prototype.remove.call(this);
}
});
var SearchResultListView = VideoListView.extend({
initialize: function(query, startIndex){
this.$el.currentQuery = query;
this.$el.currentPlaylist = '';
this.$el.currentPage = 1;
this.collection = new VideoCollection();
this.collection.url = 'https://gdata.youtube.com/feeds/api/videos/?&alt=json-in-script&q=' + this.$el.currentQuery + '&start-index=' + startIndex + '&max-results=' + config.pagination + '&author=' + config.user_id + '&v=2&callback=?',
this.collection.on('reset', this.render, this);
this.collection.fetch();
},
changeContentByPage: function(){
this.collection.url = 'https://gdata.youtube.com/feeds/api/videos/?&alt=json-in-script&q=' + this.$el.currentQuery + '&start-index=' + (((this.$el.currentPage-1)*config.pagination)+1) + '&max-results=' + config.pagination + '&author=' + config.user_id + '&v=2&callback=?',
this.collection.fetch();
}
});
// ![ COLLECTION ] - Video Collection
var VideoCollection = Backbone.Collection.extend({
model: VideoModel,
totalResults : 0,
parse: function(response) {
var data = response.feed.entry,
videoList = [];
this.totalResults = response.feed['openSearch$totalResults']['$t'];
if(this.totalResults <= config.pagination){
videoListView.$el.$pagination.hide();
} else {
videoListView.$el.$pagination.show();
}
if( data && this.totalResults > 0 ){
for(var i=0; i 0){
for(var i=0; i' + config.noCommentString + '')
} else {
this.collection.each(
$.proxy(function(v,k){
var comment = new CommentView(v);
var commentEl = comment.render().$el;
if((k)%4===0) {
commentEl.addClass('noMarginLeft');
}
this.$el.$commentList.append(commentEl);
commentEl.animate({
'opacity' : 0.99
}, 'slow' );
},this)
);
}
},
destroyView: function() {
this.undelegateEvents();
this.$el.removeData().unbind();
}
});
// ![ VIEW ] - Carousel
var ProductCarouselView = Backbone.View.extend({
el: $('#product_carousel_wrapper'),
template: _.template( $('#product_carousel_tmpl').html() ),
events: {
},
initialize: function(){
},
render: function(data) {
var html = this.template({products: data});
this.$el.html(html);
if (this.$('#product_carousel li').length > 0) this.start();
else this.hide();
},
start: function() {
this.$el.css({
opacity: 0
}).show().animate({
opacity: 1
}, 200);
this.$('#product_carousel').jcarousel();
this.$('.prev.navigation')
.on('inactive.jcarouselcontrol', function() {
$(this).addClass('inactive');
})
.on('active.jcarouselcontrol', function() {
$(this).removeClass('inactive');
})
.jcarouselControl({
target: '-=8'
});
this.$('.next.navigation')
.on('inactive.jcarouselcontrol', function() {
$(this).addClass('inactive');
})
.on('active.jcarouselcontrol', function() {
$(this).removeClass('inactive');
})
.jcarouselControl({
target: '+=8'
});
},
empty: function() {
this.$el.empty();
},
hide: function() {
this.$el.hide().empty();
}
});
// ![ VIEW ] - Quick Links
var QuickLinksView = Backbone.View.extend({
el: $('#quick_links'),
template: _.template( $('#quick_links_tmpl').html() ),
render: function(link) {
var html = this.template({link: link});
this.$el.html(html).show();
},
hide: function() {
this.$el.hide().empty();
},
});
// ![ VIEW ] - Navigation
var NavigationView = Backbone.View.extend({
el: $('#sub_bar'),
events: {
'click a' : 'resetPlaylistCollection'
},
resetPlaylistCollection: function(){
videoListView.$el.$videoList.empty();
}
});
// ![ VIEW ] - Container
var GlobalView = Backbone.View.extend({
el: $('#page-container'),
changeEffect: function(){
this.$el.hide().delay(200).fadeIn('slow');
$(window).scrollTop(0);
}
});
// Home Page View
var HomeView = GlobalView.extend({
initialize: function(){
this.$el.removeClass().addClass('home-page');
this.productCarouselView = new ProductCarouselView();
this.quickLinks = new QuickLinksView();
if(videoPlayerView === null){
videoPlayerView = new VideoPlayerView({carousel: this.productCarouselView, quickLinks: this.quickLinks});
videoPlayerView.model.fetch();
} else {
videoPlayerView.$el.ytplayer.stopVideo();
videoPlayerView.$el.ytplayer.loadPlaylist(config.defaultVideo, 0, 'large');
}
},
hideElms: function(){
this.productCarouselView.hide();
this.quickLinks.hide();
}
});
// Playlist Page View
var PlaylistView = GlobalView.extend({
initialize: function(plid){
this.$el.removeClass().addClass('playlist-page');
if(videoListView != null){
videoListView.destroyView();
}
videoListView = new VideoListView(plid, 1);
}
});
// Playlist Page View
var VideoDetailView = GlobalView.extend({
initialize: function(plid, vid, vpos){
this.$el.extend({
$videoTitle : $('#video_title'),
$postCommentLink: $('#link_post_a_comment'),
$allCommentLink : $('#link_to_all_comments'),
$shareBox: $('#video_box .share_box')
});
this.$el.removeClass().addClass('video-detail-page');
this.$el.$videoTitle.animate({'margin-left':'-100%'},'slow');
if(plid !== 'none' && vpos !== 0){
videoPlayerView.$el.ytplayer.loadPlaylist(plid, vpos, 0, 'large');
} else {
// Remove playlist from player if single video is loaded after a search
videoPlayerView.$el.ytplayer.loadPlaylist('');
videoPlayerView.$el.ytplayer.loadVideoById(vid, 0, 'large');
this.$el.addClass('no-playlist');
}
},
changeTitle: function(title){
this.$el.$videoTitle.animate({'margin-left':'-100%'},'slow',function(){
$(this).html(title).animate({'margin-left': '0px'},'slow');
});
},
changeCommentLinks: function(vid){
this.$el.$postCommentLink.attr('href','http://www.youtube.com/watch?v=' + vid);
this.$el.$allCommentLink.attr('href','http://www.youtube.com/all_comments?v=' + vid);
},
changeShareLinks: function(vid, title){
var video_url = 'http://www.youtube.com/watch?v=' + vid,
video_title = title ? title : '';
this.$el.$shareBox.find('a').each(function(k,v){
$v = $(v);
var rel = $v.data('rel');
switch(rel){
case 'facebook' :
$v.attr('href',config.baseShareUrl.facebook.replace('URL_PLACE',encodeURIComponent(video_url)));
break;
case 'gplus' :
$v.attr('href',config.baseShareUrl.gplus.replace('URL_PLACE',encodeURIComponent(video_url)));
break;
case 'twitter' :
$v.attr('href',config.baseShareUrl.twitter.replace('URL_PLACE',encodeURIComponent(video_url)).replace('MESSAGE_PLACE',encodeURIComponent(video_title)));
break;
default:
break;
}
});
},
changeTracking: function(vid){
this.$el.$shareBox.find('a').each(function(k,v){
$v = $(v);
// console.log($v.attr('onclick'))
});
}
});
// Campaign Page View
var CampaignListView = GlobalView.extend({
initialize: function(){
this.$el.removeClass().addClass('campaigns-page');
}
});
// Campaign Page View
var SearchResultView = GlobalView.extend({
initialize: function(query){
this.$el.removeClass().addClass('search-page');
$('#pagination a.next, #pagination a.prev').off('click');
if(videoListView != null){
videoListView.destroyView();
}
videoListView = new SearchResultListView(query,1);
}
});
// ![ VIEW ] - Search
var SearchFormView = Backbone.View.extend({
el: $('form.search_box').extend({
$text: $('form.search_box input[type=text]'),
$submit: $('form.search_box input[type=submit]')
}),
events: {
'click input[type=submit]' : 'searchVideos'
},
initialize: function() {
},
searchVideos: function(e) {
e.preventDefault();
window.location.hash = 'search/'+this.$el.$text.val();
}
});
// ![ ROUTER ]
var Workspace = Backbone.Router.extend({
routes: {
"" : "home", //default
"playlist/:plid" : "playlist",
"playlist/:plid/:vid/:vpos" : "playlist",
"campaigns/" : "campaigns",
"search/:query" : "search"
},
currentSection : null,
home: function() {
if(this.currentSection != null){
this.currentSection.changeEffect();
}
this.homePage = new HomeView();
this.currentSection = this.homePage;
},
playlist: function(plid, vid, vpos) {
// hide carousel and quick links
this.homePage.hideElms();
videoPlayerView.$el.ytplayer.pauseVideo();
if(this.currentSection != null){
this.currentSection.changeEffect();
}
if(vpos){
// videoDetailPage
videoPlayerView.$el.ytplayer.stopVideo();
videoDetailPage = new VideoDetailView( plid, vid, vpos );
this.currentSection = videoDetailPage;
} else {
// playlistPage
playlistPage = new PlaylistView( plid );
this.currentSection = playlistPage;
}
},
campaigns: function(){
// hide carousel and quick links
this.homePage.hideElms();
videoPlayerView.$el.ytplayer.pauseVideo();
if(this.currentSection != null){
this.currentSection.changeEffect();
}
//campaignsPage
campaignsPage = new CampaignListView();
this.currentSection = campaignsPage;
},
search: function(query) {
// hide carousel and quick links
this.homePage.hideElms();
// searchPage
videoPlayerView.$el.ytplayer.pauseVideo();
if(this.currentSection != null){
this.currentSection.changeEffect();
}
searchResultView = new SearchResultView(query);
this.currentSection = searchResultView;
}
});
$(document).ready(function(){
if(navigator.platform.indexOf("Win") != -1){
$('body').addClass('winz')
};
page = new GlobalView();
navigation = new NavigationView();
searchPage = new SearchFormView();
workspace = new Workspace();
Backbone.history.start();
// TODO: refactor into a view
$('.share_box a').on('click', function(e){
e.preventDefault();
var url = $(this).attr('href');
var popup = window.open( url , 'Share', 'height=540,width=720' );
if ( window.focus ){
popup.focus();
}
return false;
});
if(!Modernizr.csstransitions){
$('a.playlist').on('mouseenter', function(e){
var $this = $(this),
$curtain = $this.find('.curtain');
$curtain.stop(true,true).animate({
'width' : '130%'
},300);
});
$('a.playlist').on('mouseleave', function(e){
var $this = $(this),
$curtain = $this.find('.curtain');
$curtain.stop(true,true).animate({
'width' : 1
},300);
});
}
});
});
// Convert a given string with a date format to a pretty date that explain how much time is passed from that date
function prettyDate(date_str){
var time_formats = [
[60, 'just now', 1], // 60
[120, '1 minute ago', '1 minute from now'], // 60*2
[3600, 'minutes', 60], // 60*60, 60
[7200, '1 hour ago', '1 hour from now'], // 60*60*2
[86400, 'hours', 3600], // 60*60*24, 60*60
[172800, 'yesterday', 'tomorrow'], // 60*60*24*2
[604800, 'days', 86400], // 60*60*24*7, 60*60*24
[1209600, 'last week', 'next week'], // 60*60*24*7*4*2
[2419200, 'weeks', 604800], // 60*60*24*7*4, 60*60*24*7
[4838400, 'last month', 'next month'], // 60*60*24*7*4*2
[29030400, 'months', 2419200], // 60*60*24*7*4*12, 60*60*24*7*4
[58060800, 'last year', 'next year'], // 60*60*24*7*4*12*2
[2903040000, 'years', 29030400], // 60*60*24*7*4*12*100, 60*60*24*7*4*12
[5806080000, 'last century', 'next century'], // 60*60*24*7*4*12*100*2
[58060800000, 'centuries', 2903040000] // 60*60*24*7*4*12*100*20, 60*60*24*7*4*12*100
];
var time = ('' + date_str).replace(/-/g,"/").replace(/[TZ]/g," ").replace(/^\s\s*/, '').replace(/\s\s*$/, '');
if(time.substr(time.length-4,1)==".") time =time.substr(0,time.length-4);
var seconds = (new Date - new Date(time)) / 1000;
var token = 'ago', list_choice = 1;
if (seconds < 0) {
seconds = Math.abs(seconds);
token = 'from now';
list_choice = 2;
}
var i = 0, format;
while (format = time_formats[i++])
if (seconds < format[0]) {
if (typeof format[2] == 'string')
return format[list_choice];
else
return Math.floor(seconds / format[2]) + ' ' + format[1] + ' ' + token;
}
return time;
};