/*  bring the link from the <a> element to the parent block, making it clickable
	Adding also a rollover effect
*/


$.fn.extend({
	clickBlock: function() {
		$(this).each(function() {
			$(this)
				.hover(
					function() { $(this).css('cursor', 'pointer').find('a').addClass('over'); },
					function() { $(this).find('a').removeClass('over'); }
					)
				.click(function() {
       				var link = $(this).find('a');// Act on the event
       				if (link.attr('href') == '#')
       					link.click();
       				else window.location = link.attr('href');
       				//console.log('Cosa',link);       				 
       				return false;
       				})			
			
			});
		
		return this;
		}
	
	})

$.extend({
	// deprecated
	clickBlock: function(data) {
	   $(data)
	   	.hover(function() {
			// Stuff to do when the mouse enters the element;
	       	$(this)
			//.css('background', '#f3f3f3')
			.css('cursor', 'pointer')		
			.find('a')
			.addClass('over')		
			}, function() {
	       	$(this)
			.find('a')
			.removeClass('over')		
	       })
	    .click(function() {
	    	//console.log($(this).find('a').attr('href'));
       		$(this).find('a').click(); // Act on the event
       	});

	},
	
	truncateString: function(str,maxLength) {
		
		if (str.length < maxLength)
			return str;
		else {
			return str.substr(0,maxLength)+'...';			
			}
		}	
	
});

// **
// Babelgum API Flash Player
//


// !todo
// default as blank
// order param
(function($) {
	
	var defaults = {
		order: 'featured',		
		view: 'play',
		context: 'similar',
		channelId: null,
		searchMask: null,
		clipPosition: 0,
		hint_no_featured: false
		};
	
	function getMixedParams(params) {
		var mixed_params = $.extend({},defaults,params);

		// check if the views and order are correct
		if ($.inArray(mixed_params.order,['alphabetical','featured','most_popular','most_recent','top_rated']) == -1)
			mixed_params.order = defaults.order;
		if ($.inArray(mixed_params.view,['play','list','grid']) == -1)
			mixed_params.view = defaults.view;			
		if ($.inArray(mixed_params.context,['similar','channel','search']) == -1)
			mixed_params.context = defaults.context;		

		// check if the context are correct, otherwise switch to the default one
		if (mixed_params.context == 'channel' && mixed_params.channelId == null)
			mixed_params.context = defaults.context;
		if (mixed_params.context == 'search' && mixed_params.searchMask != null)
			mixed_params.context = defaults.context;			

		return mixed_params;
		}
	
	
	$.extend({
		
		babelgum_clip: function(clipId,params) {
			params = getMixedParams(params);
			
			// not sure it works
			//$('body').append('<div style="display:none;"><iframe width="0" height="0" src="/themes/babelgum/conversion.htm" ></iframe></div>');
			
			var contextString = '';
			switch(params.context) {
				case 'channel':
					contextString = 'SEARCH,channelID:'+params.channelId+',order:'+params.order.toUpperCase();	
					break;
				case 'search':
					contextString = 'SEARCH,queryString:'+escape(params.queryString)+',order:'+params.order.toUpperCase();
					break;
				case 'similar':
					// play/SEARCH_SIMILAR,clipID:141582,includeClip:true,order:MOST_RELEVANT/0,141582
					contextString = 'SEARCH_SIMILAR,clipID:'+clipId+',includeClip:true,order:MOST_RELEVANT';
					break;	
				}
	
			var qs = 'http://www.babelgum.com//browser.php#'+params.view+'|'+contextString+'|'+params.clipPosition+','+clipId;

			window.location = qs;
			
			},
			
		babelgum_channel: function(channelId,params) {
			params = getMixedParams(params);
			var qs = 'http://www.babelgum.com//browser.php#grid|SEARCH,channelID:'+channelId+',order:'+params.order.toUpperCase();
			qs += (params.hint_no_featured ? ',hint_no_featured:1' : '');
			window.location = qs;		
			},
			
		babelgum_search: function(searchMask,params) {
			params = getMixedParams(params);
			var qs = 'http://www.babelgum.com/browser.php#grid|SEARCH,queryString:'+searchMask;
			window.location = qs;
			}		
		
	
		});
	
	
	})(jQuery);






var bbg_is_animating = false;






$.extend({
	
	// **
	// Decode a channelId into a label, it's wrong
	// shouldn't be done like that, we're in a hurry
	//
	decodeChannelId: function(channelId) {
		var section = 'home';
		if (channelId == '172994' || channelId == '179807') section = 'film';
		else if (channelId == '172995' || channelId == '179808') section = 'music';
		else if (channelId == '172996' || channelId == '179809') section = 'comedy';
		else if (channelId == '172997' || channelId == '179811') section = 'ourearth';
		else if (channelId == '172998' || channelId == '179810') section = 'metropolis';		
		return section;
		},
		
	decodeSection: function(section) {
		if (section == 'highlights')
			return 'featured';
		else if (section == 'mostPopular') return 'mostviewed';
		else if (section == 'mostRecent') return 'mostrecent';
		else return 'featured';
		},	
	
	// ** 
	// Mix the elements of the array
	//
	arrayShuffle: function(arr) {
		for(
			var j, x, i = arr.length; i;
			j = parseInt(Math.random() * i),
			x = arr[--i], arr[i] = arr[j], arr[j] = x
	    	);
	    return arr;
		},

	// **
	// Truncate a string
	//
	truncate: function(text,maxLength,separator) {
		
		var result = text;
		var minimumLength = 30;
		
		if (result.length > maxLength) {
			result = text.substr(0,maxLength);
			
			while (result.length > minimumLength && result.substr(result.length-1,1) != ' ') {
				result = result.substr(0,result.length-1);	
				}

			result = $.trim(result);
			result = result + separator;
			}
		
		
		return result;
		
		},


	// **
	// Returns size fo thumbs
	//
	bbg_thumb: function(size,clipId) {
		
		switch(size) {
			
			case 'small':
				return 'http://www.babelgum.com/thumbnails/clips/'+clipId+'_160x90.jpg';
				break;
			case 'medium':
				return 'http://www.babelgum.com/thumbnails/clips/'+clipId+'_155x96.jpg';
				break;				
			case 'large':
				return 'http://www.babelgum.com/thumbnails/clips/'+clipId+'_448x252.jpg';
				break;	
				
			}
		return null;
		},

	// **
	// Check is there's an animation going on
	//
	bbg_is_animating: function() {
		
		// no, this below it's too slow
		//return $(':animated').length != 0;
		if (arguments.length > 0)
			bbg_is_animating = !!arguments[0];

		return bbg_is_animating;
		
		},

	// **
	// Extract random 5 clip objects from a list of clip object
	//
	bbg_shuffle_clips: function(clips,excludedIds) {
	
		var result = [];
		var result_ids = [];
		
		while (result.length < 5) {
			var rnd = Math.floor(Math.random()*clips.length);
			var proposed_clipId = clips[rnd];
			//console.log(proposed_clipId.clip_id,' not in ',excludedIds,result_ids);
			if ($.inArray(proposed_clipId.clip_id,excludedIds) == -1 && $.inArray(proposed_clipId.clip_id,result_ids) == -1) {
				result_ids.push(proposed_clipId.clip_id);
				result.push(proposed_clipId);			
				}
			} // end while 
		
		return result;
		
		}

	
	
	});



$.fn.extend({
	
	// **
	// Load a jquery stack using firebug
	//
	log: function(title) {
		if (window.console) {
			if (title != '')
				console.log(title,this);
			else console.log(this);
			}
		return this;	
		}
	});


$.fn.extend({
	
	stripParagraph: function(what){
	
		//$('.bbg_channel .title strong,.bbg_channel .title span').each(function(){

		var aa = $(what,this).html();

		var start = aa.substr(0,3);
		var end = aa.substr(aa.length-3,aa.length);

		if (start == "<p>"){
			aa = aa.substr(3,aa.length);
			if (end == "</p>") aa = aa.substr(0,aa.length-3);
		}
		$(what,this).html(aa);
	
	},

	bbg_clip: function() {
		
		$(' a',this).click(function(){
			var clip = $(this).parents('.bbg_clip').attr('clipId');
			$.babelgum_clip(clip);
			return false;
		});

		$(this).clickBlock();
		
		},
		
	bbg_channel: function(channelId) {
		

		$('a',this).click(function(){
			var what = $(this).parents('.bbg_channel').attr('channelId');
			$.babelgum_channel(what);
			return false;
			});
		
		$(this).clickBlock();
		
		//$(this).stripParagraph('.title strong');
		
		//$(this).stripParagraph('.title span');

		
		
		},
		
	// **
	// Shuffle a single card
	//
	shuffle: function(pauseFunction) {
		
		var max_left_displacement = 400;
		var max_top_displacement = 200;
		var easing = 'swing'; // easeInBack
		var duration = 700;
		var container = $(this).parents('.hider');
		
		// Take the set of cards that must be shuffled and se a flag to loading = true
		// then hide and start loading the new thumb image, when the image is loaded remove
		// the flag and test how many other images still have the flag, if zero trigger the unshuffle
		// event to the container, but just once in case more images come to zero at the same moment
		
		$.bbg_is_animating(true);
				
		$(this)
			.parent()
				.one('unshuffle.ui',function(evt) {					
					// attach just a single event to the unshuffle, so only one clip can cast this
					$('.clip',this)
						.animate({ top: 0, left: 0 },duration,easing,function() { 
							//console.log('finito'); 
							$.bbg_is_animating(false);
							// hide the laoder
							$.broadcast('hideLoader.ui');
							});						
					})
				.end()
			.each(function() {
				
				var obj = $(this);
				
				// get the current position and store inline for revealing
				var offset = obj.offset();
				var offset_container = container.offset();
				
				var top_displacement = offset_container.top - offset.top + container.height() + 10;
				var left_displacement = offset_container.left - offset.left + Math.floor(container.width()/2) - Math.floor(obj.width() / 2) - 10;
				
				var left_random=Math.floor(Math.random()*(max_left_displacement+1)-(max_left_displacement/2));
				var top_random=Math.floor(Math.random()*(max_top_displacement+1));
				
				left_displacement += left_random;
				top_displacement += top_random;
				
				$(this)
					.attr('loading','true')
					.animate({
						top: top_displacement,
						left: left_displacement
						},
						duration,
						easing,
						function() {
							// if exists, prepare the cards while hidden
							if (pauseFunction != null)
								pauseFunction.call(obj);							
							// animate back the cards
							var clip = $(this);
							// set the image as loading
							$('a.thumb',obj).css('background-image','url(/themes/babelgum/images/clip/loading_thumb.jpg)');
							// preaload the image and listen
							$('<img src="'+$(this).attr('toLoad')+'" style="display:none;">')
								.one('load',clip,function(evt) {
									var imageURL = $(this).attr('src');
									// set loading as false
									evt.data.attr('loading','false'); 
									// remaining
									var toLoad = evt.data.parent().find('.clip[loading=true]').length;
									// change the image while hidden
									evt.data
										.find('a.thumb img.imageThumb',obj)
											.attr('src',$.bbg_thumb('small',evt.data.attr('clipId')));
									
									// finally if the images to be loaded are zero, trigger the unshuffle
									if (toLoad == 0)
										evt.data.parent().trigger('unshuffle.ui');
										
									}); 
														
							});
			
				}); // end each
		
		return this;
		
		}


	});

var flagNavDataIsLoaded = false;

$.fn.extend({

	// **
	// Update the label of a clip id using the information of the navigation menu
	// and the navIds from babelfish
	//
	bbg_updateLabel: function() {
				
		$(this)
			.each(function() {	
				
				if (!flagNavDataIsLoaded) {
					flagNavDataIsLoaded = true;
					loadNavData();
					}

				// Activate the smart system just on the home page
				var active_menu = $('#menuChannels a.active');
				var original_label = active_menu.attr('rel');
				
				// If none "rel" is found, then use the navigation data algorithm 
				// to find the right label for a clip
				if (original_label == null || original_label == '') {
	
					var clipId = $(this).attr('clipId');
					
					if (clipId != null) {
						
						// get navIDs for the clip
						var i = 0;
						var navIDs = null;
						for (i = 0; i < bbg_channel.length; i++)
							if (bbg_channel[i].clip_id == clipId)
								navIDs = bbg_channel[i].navs;	
					
						if (navIDs != null) {
							var obj = findTopNavItem({ navChannelsIDs: navIDs } );
							
							//console.log('ooo',obj);
							$('.category',this)
								.html(obj.label)
								.attr('class','category '+obj.color);
							} // end navids not null	
						} // end clipid not null
						
					} // end original label
				else {
					// if a rel value is present (tipically just in the home page)
					// use the value inside a and the class in rel	
					$('.category',this)
						.html(active_menu.html())
						.attr('class','category '+original_label);
					
					
					}							
				
				}); // end each
		
		return this;
		},
	
	// !TODO fix clipInfo and clipShare
	bbg_sliding_info: function() {	
		$(this)
			.bind('clipInfo.ui',function(evt,clip) {

				var obj = $(this);
				//$(this).find('#videoshare').hide();
				//$(this).find('#videoinfo').hide();
				// if empty then load
					$.get('/dialog.html',function(data) {
						obj
							.html(data)
							.show()
							.find('.title').html(clip.editorial_title).end()
							.find('.description').html(clip.editorial_description).end()
							.find('.duration').html(clip.duration).end()
							.find('.rating').addClass('rated'+clip.userRating).addClass('fixPng').end()
							.find('.voting').hide().end()
							.find('#icon').attr('src',clip.smallThumb).end()
							.find('#playbutton img').each(function(){
								
								var path = $(this).attr('src');
								var endCut = path.indexOf("/img");
								path = path.substr(endCut,path.length);	
								$(this).attr('src',path);
								$(this).log(this).ifixpng().css({cursor:'pointer'});					
							 } ).end()
							.find('.imgbox').each(function(){ 
								if (clip.blocked == true) 
									$(this)
										.find('a').css('cursor','default')
										.click(function(){ return false; })
										.find('#playbutton').hide()
										.parents('.imgbox').find('.geoblocked').show();
								else 
									$(this).find('a').css('cursor','pointer').click(function(){									
										var channelId = $('.bbg_grid').attr('channelId');
										// must call this
										// http://www.babelgum.com/browser.php#play/SEARCH_SIMILAR,clipID:141582,includeClip:true,order:MOST_RELEVANT/0,14158
										$.babelgum_clip(clip.clipId,
											{ 
												context: 'similar' 
											});									
									})	
							}).end()							
							.find('#videoinfo').slideDown().end()			
							.find('#closetitle,#close #closebox').click(function(){
								$(this).parents('#videoinfo').slideUp(); // hide all div, need it for balloon
								$('#header').find('#mainMenu').css('background','url(/themes/babelgum/images/menu/background.png)').css('background-repeat','repeat-x');
								if ($.browser.msie && $.browser.version < 7) $('#header').find('#mainMenu').css('background','url(/themes/babelgum/images/menu/backgroundIE6.jpg)');

							})
						$('.fixPng').ifixpng();
						});
						


				
				})
			.bind('clipShare.ui',function(evt,clip) {
				var obj = $(this);
				//$(this).find('#videoshare').hide();
				//$(this).find('#videoinfo').hide();
				// if empty then load
				var link = escape('http://www.babelgum.com/html/clip.php?clipId=' + clip.clipId );
				var title = encodeURIComponent(clip.title);
				var description = encodeURIComponent(clip.editorial_description);
				
				// don't edit this or will break on outlook express+ie7
				staticText = encodeURIComponent(
                'I enjoyed watching "' + clip.title + '" on Babelgum and would like to share it with you.\n\n' 
                + 'To watch this video on your computer go to: \n\nhttp://www.babelgum.com/html/clip.php?clipId=' + clip.clipId + '\n\n'
                + 'If you have already downloaded Babelgum Mobile to your iPhone, go to:\n\n'
                + 'babelgum://clip=' + clip.clipId + '\n\n'
                + 'If you haven\'t downloaded Babelgum Mobile to your iPhone yet, you can download the application here:\n\n'
                + 'http://www.itunes.com/app/Babelgum\n\n'
                + 'Babelgum is also available on selected Symbian phones. To find out more about Babelgum Mobile, go to:\n\n'
                + 'http://www.babelgum.com/mobile\n'
            	);
				
										
					$.get('/dialog.html',function(data) {
						obj
							.html(data)
							.show()
							.find('#digg').attr('href','http://digg.com/submit?phase=2&url=http://www.babelgum.com/html/clip.php?clipId='+ clip.clipId +'&topic=videos&bodytext='+ clip.editorial_description + '&title=' + clip.title ).end()
							
							.find('#delicious').attr('href','http://del.icio.us/post?noui&jump=close&url=http://www.babelgum.com/html/clip.php?clipId='+ clip.clipId +'&title=' + clip.title + '&partner=babelgum&v=4').end()
							
							.find('#reddit').attr('href','http://reddit.com/submit?url=http://www.babelgum.com/html/clip.php?clipId='+ clip.clipId +'&title=' + clip.title ).end()

							.find('#stumbleupon').attr('href','http://www.stumbleupon.com/submit?url=http://www.babelgum.com/html/clip.php?clipId='+ clip.clipId +'&title=' + clip.title ).end()							

							.find('#myspace').attr('href','http://www.myspace.com/Modules/PostTo/Pages/?u=http://www.babelgum.com/html/clip.php?clipId='+ clip.clipId +'&t=' + clip.title ).end()	
													
							.find('#facebook').attr('href','http://www.facebook.com/share.php?src=bm&v=4&i=1229338490&u=http://www.babelgum.com/html/clip.php?clipId='+ clip.clipId +'&t=' + clip.title ).end()
							
							.find('#copylinktext').attr('value','http://www.babelgum.com/html/clip.php?clipId='+ clip.clipId)
							.click(function(){
								$(this).focus();$(this).select();
							}).end()			
							.find('#mailto').attr('href','mailto:?subject='+ clip.title + '&body=' + staticText ).end()
													
							.find('#mailtogmail').attr('target', '_blank').attr('href','https://mail.google.com/mail/?extsrc=mailto&url=' 
							 + encodeURIComponent('mailto:?subject=' + title + '&body=' + staticText)).end()
							.find('#icons img,#mailto img,#mailtogmail img,#mailtoyahoo img').each(function(){
								var path = $(this).attr('src');
								var endCut = path.indexOf("/img");
								path = path.substr(endCut,path.length);	
								$(this).attr('src',path);
								$(this).addClass('fixPng');						
							 }).end()
							.find('#videoshare').slideDown()
							.find('#closetitle,#close #closebox').click(function(){
								$(this).parents('#videoshare').slideUp(); // hide all div, need it for balloon
								$('#header').find('#mainMenu').css('background','url(/themes/babelgum/images/menu/background.png)').css('background-repeat','repeat-x');
								if ($.browser.msie && $.browser.version < 7) $('#header').find('#mainMenu').css('background','url(/themes/babelgum/images/menu/backgroundIE6.jpg)');


							})
					$('img.fixPng').ifixpng();
						});
				
				});
		return this;
		},	
	

	// **
	// Extract info about a clip inside the html markup
	//
	extractClipInfo: function() {
		
		var result = {};
		var obj = $(this);
		
		
		result.clipId = obj.attr('clipId');
		result.smallThumb = $.bbg_thumb('small',result.clipId);
		result.mediumThumb = $.bbg_thumb('medium',result.clipId);
		result.largeThumb = $.bbg_thumb('large',result.clipId);
		result.category = $('span.category',obj).html();
		result.title = $('span.title',obj).html();
		result.userRating = $('span.rating img',obj).attr('class').replace('stars_','');
		result.editorial_title = $('div.editorial_title',obj).html();
		result.editorial_description = $('div.editorial_description',obj).html();	
		result.duration = $('span.duration span',obj).map(function () { return $(this).html(); }).get().join('');	
		result.blocked = obj.attr('blocked') == 'true';
		
		return result;
		
		},
	
	// **
	// Inject a clip object inside a card (div), the second parameter
	// postpone the injection to the thumb in order to be loaded later
	//		
	injectClipInfo: function(clip,updateThumb) {
		
		var obj = $(this);
		if (updateThumb == null) updateThumb = false;
				
		obj.attr('toLoad',$.bbg_thumb('small',clip.clip_id));
		obj.attr('position',clip.position);
		obj.attr('clipId',clip.clip_id);
		obj.attr('blocked',clip.isGeoblocked);
		$('span.title',obj).html(clip.title);
		if (updateThumb)
			$('a.thumb img.imageThumb',obj).attr('src',$.bbg_thumb('small',clip.clip_id));
		$('.meta img',obj).attr('class','stars_'+clip.userRating);
		$('.meta .durationFormatted',obj).html(clip.durationFormatted);
		$('div.editorial_title',obj).html(clip.editorial_title);
		$('div.editorial_description',obj).html(clip.editorial_description);
		if (clip.isGeoblocked)
			$('a.thumb',obj).addClass('blocked');
		else $('a.thumb',obj).removeClass('blocked');	
		
		return this;
		},	
	
	// **
	// Init the grid and the shuffle
	//
	bbg_grid: function(channelId) {
		
		var currentOffset = 0;
		
		// init players
		var mainSlider = $(this);
		var channelId = mainSlider.attr('channelId');
		var section = mainSlider.attr('section');
		
		// shuffle the array execept the first 10
		// only if the array is bigger that 10
		if (bbg_channel.length > 10) {
			var temp1 = bbg_channel.slice(0,10);
			var temp2 = $.arrayShuffle(bbg_channel.slice(10));
			bbg_channel = [];
			bbg_channel = temp1;
			$.merge(temp1,temp2);			
			}

		// the loader
		$('.sliderFooter a.shuffle',this)
			.bind('showLoader.ui',function() {
				$(this).addClass('shuffle_loading');
				})
			.bind('hideLoader.ui',function() {
				$(this).removeClass('shuffle_loading');
				});
		
		// if resize hide balloon
		$(window)
			.resize(function(evt) {
				$.broadcast('hide.balloon');
				$.broadcast('clipHide.ui');
				})
			
		// shuffle animation	
		$('body')
			.mousemove( function(evt) {			
				// check dimension
				var obj = $('.bbg_grid');				
				var offset = obj.offset();
				if ( evt.pageX < offset.left || evt.pageX > (offset.left+obj.width()) || 
					evt.pageY < offset.top || evt.pageY > (offset.top+obj.height())
					) {
					$.broadcast('clipHide.ui');
					$.broadcast('hide.balloon');
					}
	
				})
		
		
		$(this)		
			.bind('shuffle.ui',function(evt) {
				
				// hide (again) any selected card
				$.broadcast('clipHide.ui');
				// shuffle the cards
				$('.hider .clip')
					.show() 
					.shuffle(function() {
						var obj = $(this);
						var currentIdx = parseInt(obj.attr('tabIdx'));																
																	
						// mod the index to the length of the array, so if the index is bigger, 
						// it's substituted with the first elements of the array
						obj
							.injectClipInfo(bbg_channel[(currentOffset+currentIdx) % bbg_channel.length])
							.bbg_updateLabel();
						});

				
				});
				
				
		
		
		$('a.shuffle',this)
			.click(function() {
				// exit if animating
				if ($.bbg_is_animating()) return false;
								
				// hide any selected card
				$.broadcast('clipHide.ui');
				// show the laoder
				$.broadcast('showLoader.ui');
				// get current section
				var section = mainSlider.attr('section');
				// track on GA
				if (window.pageTracker)
					pageTracker._trackPageview('/'+$.decodeChannelId(channelId)+'/'+$.decodeSection(section)+'/shuffle');
				if (window.console)
					console.log("GA: Virtual page view being sent: google._trackPageview('/"+$.decodeChannelId(channelId)+"/"+$.decodeSection(section)+"/shuffle');");						
				// move the offset of 10 clips, if it's bigger than the end of the array
				// then start again from the beginning						
				currentOffset += 10;
				if (currentOffset >= bbg_channel.length) {
					currentOffset = 0;
					//console.log('ok finished, starting from the beginning');
					}
					
				// if the last clip to be shuffled is within the array, then shuffle
				if ((currentOffset+10) < bbg_channel.length)
					$.broadcast('shuffle.ui'); 
				else {
					// if the last clip to be shuffled is not within the array
					// then try asking more clips											
					// ask new clips, using the current bbg_channel as offset					
					var qs = '/gateway/babelgumAPI/?action=channelclips&channelId='+channelId+'&section='+section+'&count=40&offset='+bbg_channel.length+'&drm='+(section != 'highlights' ? 'true' : 'false');
						$.getJSON(qs,function(clips) {
							// if I've found more clips						
							if (clips != null && clips.length > 0) {
								// append the new clips to the current ones

								$.merge(bbg_channel,$.arrayShuffle(clips));
								
								// leave untouched the offset, just go on, if the currentOffset+10 finish
								// over the end of the array, the idx id modded % length_of_array
								// so the first elements of the array are used insted of the missing one 																
								 
								} // end clips != null and not zero
							//else console.log('No more clips, sorry');
							
							// shuffle in any case
							$.broadcast('shuffle.ui');
							
							
								
																			
							}); // end json						
						
					
						
					}; // end else currentOffset > bbg_channel 	
					
								
				return false;
				}); // end a.shuffle
		
		

		
		
		// apply the play to all the cards
		$('.clip',this)
			.bbg_player_icon();
		

		// load different sections
		$('.sliderFooter .miniMenu a',this)
			.click(function() {
				// exit if animating
				if ($.bbg_is_animating()) return false;
				// check if selected
				if ($(this).hasClass('selected')) return false;				
				// hide any selected card
				$.broadcast('clipHide.ui');		
				// get requested section
				var section = $(this).attr('class');

				// remove the selected from any other and add to this
				$(this).parent().find('a').removeClass('selected');
				$(this).addClass('selected');
				// if valid
				if (section == 'highlights' || section == 'mostPopular' || section == 'mostRecent') {					
					var grid = $('.bbg_grid');
					var channelId = grid.attr('channelId');
					var rel = $('#menuChannels a.active').attr('rel');					
					// track on GA
					if (window.pageTracker)
						pageTracker._trackPageview('/'+$.decodeChannelId(channelId)+'/'+$.decodeSection(section));
					if (window.console)
						console.log("GA: Virtual page view being sent: google._trackPageview('/"+$.decodeChannelId(channelId)+"/"+$.decodeSection(section)+"');");
					// show just drm-ed content just for highlight
					if ((rel == null || rel == '') && section != 'highlights')
						channelId = -1;
					var qs = '/gateway/babelgumAPI/?action=channelclips&channelId='+channelId+'&section='+section+'&count=40&offset=0&drm='+(section != 'highlights' ? 'true' : 'false');
					$.getJSON(qs,function(clips) {
						// save the new clip
						bbg_channel = clips;
						currentOffset = 0;
						
						// set the main slider section
						mainSlider.attr('section',section);
						
						// hide loader
						//$('.sliderFooter .browse a').addClass('shuffle').removeClass('shuffle_loader');
						// if not clips
						if (clips != null) {
							// update the main slider with new content
														
							$('.hider .clip',mainSlider)
								.each(function(idx) {
									var obj = $(this);
									var currentIdx = parseInt(obj.attr('tabIdx'));																
									obj.fadeOut(1);
									if (clips[currentIdx] != null) {
									// update the card
									obj
										.injectClipInfo(clips[currentIdx],true)
										.bbg_updateLabel();
										
									$('<img src="'+clips[currentIdx].smallThumb+'" rel="'+clips[currentIdx].clip_id+'" style="display:none">')										
										.one('load',function() {
											//console.log('caricata',this)
											$('.clip[clipId='+$(this).attr('rel')+']').fadeIn(1000);
											})
										.appendTo('body')
									}
									
									
									});
							
							
							
							
							} // if data						
						}) // end json										
					} // if section
			
				return false;
				});
		
		
		$(this)	
			.find('.clip')		
			.bbg_updateLabel()	
			.bind('clipHover.ui',function(evt,myDiv,clip){
				
				// exit immediately if sliding menu it's open
				if ($('#videoinfo:visible').length || $('#videoshare:visible').length || $.bbg_is_animating()) return false;
				
				//console.log(this,'myID: '+$(this).attr('clipid') + ' clipID: ' + clip.clipId);				
				
				if (clip.clipId == $(this).attr('clipid')){
										
					var offset = myDiv.offset();
					var tabIdx = myDiv.attr('tabIdx');
									
					// add selected
					$('div.selected',mainSlider).removeClass('selected');
					myDiv.addClass('selected');
					
					// show balloon
					var balloon_text = '<div class="text">'
						+'<strong>'+clip.editorial_title+'</strong><br>'+$.truncate(clip.editorial_description,100,'...')
						+'</div>';
					$.broadcast('hide.balloon');
					myDiv.balloon('click',
						balloon_text,
						{
							backgroundColor: '#40495A',
							width: '180px',
							beak_align: (tabIdx == 4 || tabIdx == 9) ? 'br' : 'bl',
							balloon_align: (tabIdx == 4 || tabIdx == 9) ? 'right' : 'left',
							offset_x: (tabIdx == 4 || tabIdx == 9) ? -15 : 15,
							offset_y: 30,
							beak_url: '/themes/babelgum/images/balloon/beak_large.png',
							beak_width: 16,
							beak_height: 12,
							opacity: .95,
							zindex: (tabIdx >= 0 && tabIdx < 5) ? 11000 : 9000,
							balloon_instance: (tabIdx >= 0 && tabIdx < 5) ? 'balloon_upper' : 'balloon_lower'
						});
					
					// 	Attach to floating panel										
					$('#utilities')
						.bind('clipHide.ui',function(evt) {
							// hide the selector
							$(this).hide();
							// hide the balloon
							$.broadcast('hide.balloon');
							})						
						.css('top' , offset.top+myDiv.height()-11)
						.css('left', offset.left)
						.find('a.btnShare')
							.unbind('click')							
							.click(function() {

								var channelId = $('div.bbg_grid').attr('channelId');
								// track on GA
								if (channelId != null) {
									if (window.pageTracker)
										pageTracker._trackPageview('/'+$.decodeChannelId(channelId)+'/share');
									if (window.console)
										console.log("GA: Virtual page view being sent: google._trackPageview('/"+$.decodeChannelId(channelId)+"/share');");
									}
								//$('#mainMenu').css('background','url(/themes/babelgum/images/menu/backgroundLonger.png)')
								// ie tweak
								if ($.browser.msie && $.browser.version >= 7)
									$('#mainMenu').css('background','url(/themes/babelgum/images/menu/backgroundLonger.png)');

								$.broadcast('clipHide.ui');
								$.broadcast('clipShare.ui',clip);
								return false;
							})
							.end()
						.find('a.btnInfo')
						.unbind('click')
						.click(function() {

							var channelId = $('div.bbg_grid').attr('channelId');
							// track on GA
							if (channelId != null) {
								if (window.pageTracker)
									pageTracker._trackPageview('/'+$.decodeChannelId(channelId)+'/information');
								if (window.console)
									console.log("GA: Virtual page view being sent: google._trackPageview('/"+$.decodeChannelId(channelId)+"/information');");
								}	
							
							// ie8 tweak
							if ($.browser.msie && $.browser.version >= 7)
								$('#mainMenu').css('background','url(/themes/babelgum/images/menu/backgroundLonger.png)');
							
							$.broadcast('clipHide.ui');
							$.broadcast('clipInfo.ui',clip);
							return false;

							})
						.end().show();
							
						
				} // end bind clipHover
	
				
						
		});		
				
		
				
		return this;
		},


	// **
	// Install a play icon on a thumb
	//
	bbg_player_icon: function(large) {
		
		// init
		if (large == null) large = false;
		
		$(this)
			.each(function(idx) {
				
				var img = $('.thumb img',this);
				var imgWidth = img.attr('width');
				var imgHeight = img.attr('height');
				var clipId = $(this).attr('clipId');
				
				var drm = $(this).attr('blocked') == 'true';
				var currentClipIcon = $(this);

				// exit immediately if the player_icon was already applied
				if (img.attr('src').indexOf('shim.gif') != -1) 
					return false;	

				// Tie the event for updating the image								
				$(this)					
					.bind('clipHide.ui',function(evt) {
						if ($(this).hasClass('selected'))
							$(this).removeClass('selected');
						})
					.find('a.thumb,.meta,.info')
						.bind('mouseover',function(evt) {
							var clipDIV = $(this).parents('.clip');
							var clip = clipDIV.extractClipInfo();
							
							//console.log('Fire clipHover.ui',clipDIV,clip);
							$.broadcast('clipHover.ui',[clipDIV,clip]);	
							
												
							})							
						.end()
					.find('.thumb')
						.click(function() {
							var clip = $(this).parents('.clip');
							var clipId = clip.attr('clipId');
							var channelId = $(this).parents('.bbg_grid').attr('channelId');
							var drm = clip.attr('blocked') == 'true';
							var clipPosition = clip.attr('position');
							var order = $.trim($('.miniMenuSlider a.selected').attr('class').replace('selected',''));
							
							// translate the order in one of these
							// alphabetical','featured','most_popular','most_recent','top_rated']
							if (order == 'highlights') order = 'featured';
							else if (order == 'mostPopular') order = 'most_popular';
							else if (order == 'mostRecent') order = 'most_recent';
							else order = 'featured';								
																							
							if (window.pageTracker)
								pageTracker._trackPageview('/'+$.decodeChannelId(channelId)+'/clickonplay');
							if (window.console)
								console.log("GA: Virtual page view being sent: google._trackPageview('/"+$.decodeChannelId(channelId)+"/clickonplay');");

							if (!drm) {
								$.babelgum_clip(clipId,{
									context: 'channel',
									channelId: channelId,
									clipPosition: clipPosition,
									order: order
									});
								}							
							
							return false;
							})				

						
					.bind('updateImage.babelgum',function(evt,imgUrl) {
						//console.log(this);
						var a = $('.thumb',this);
						var img = $('.image .thumb img',this);
						var info = $('.info',this);
																							
						// attach image as background and events for over
						//a.css({
						//	backgroundImage: 'url('+imgUrl+')',
						//	backgroundRepeat: 'no-repeat'
						//	})							
		
						// add drm
						if (drm) a.addClass('blocked');
						// trasparent image				
						//img.attr('src','/themes/babelgum/images/shim.gif');	 										
							
						
						}) // end bind updateImage
				
					imgUrl = $.bbg_thumb('small',clipId);
					$('<img src="'+imgUrl+'" style="display:none;">')
						.one('load',function() {
							
							currentClipIcon
								.trigger('updateImage.babelgum',$(this).attr('src'))
								.trigger('showDescription.babelgum',large);
							})
						.appendTo('body');
		
				
			
				}) // end each
			return this;	
		},
		
	
	// **
	// Remove the player stuff from a card
	//	
	bbg_unplayer_icon: function() {
		
		var a = $('.thumb',this);
		var img = $('.thumb img',this);
		var info = $('.info',this);
		var imgUrl = a.css('backgroundImage').replace('url(','').replace(')','');
		
		// if bbg_player_icon was previously applied
		if (imgUrl != 'none') {
			$(this).unbind('.babelgum');
			a.css('backgroundImage','none')
				.unbind('.babelgum');	
			img.attr('src',imgUrl);
			}
		return this;
		},	
	





	// **
	// Promo block
	//	
	bbg_promo: function() {
				
		$('a.more',this)
			.click(function(evt) {
				var column = $('.left_column');
				column
					.find('.hidden')
					.hide()
					.end()
					.find('.more_container')
					.show();
				$(this)
					.parent()
					.hide()
					.parents('.bbg_promo')
					.find('.hidden')
					.show('normal');
				return false;		
				
				}); // end click
		
		
		
		} // end bbg_promo


	});
	
	
// *****




var babelgum = {
	/** Package a method and the object to apply it to inside a function */

	
	array: {
		/** Executes a provided function once per array element. */
		forEach: function(array, fn, self){
			var len = array.length;
			for (var i = 0; i < len; i++) {
				fn.call(self || array, array[i], i);
			}
		}
	}
	
	
	
};


//------------------------------------------------------------------------
// code for label, temporary


babelgum.forEach = babelgum.array.forEach;

function isCategoryItem(item) {
		var result = 
			item.children && item.children.length > 0
			&& item.children[0].action == null 
			&& item.children[0].children && item.children[0].children.length >0;
		return result;
	}

function loadNavData() {
		// get data from file (static or dynamic)
		var nav = NAVIGATION_DATA;
		
		// apply some rules
		babelgum.forEach(nav.children, function(item) {
			if (item.children && item.children.length > 0) {
				item.action = ["expand"];
				// find alternate action, i.e. the action associated to the sub-menu "All"
				if (this.isCategoryItem(item)) {
					item.altAction = item.children[0].children[0].action;
					
					// compute map: top level item by channel id 
					if (item.altAction && item.altAction[0] == "clips" 
						&& item.altAction[1][0] == "SEARCH"
						&& item.altAction[1][1].channelID) 
					{
						var channelID = item.altAction[1][1].channelID;
						topNavItemByChannel[channelID] = item;
					}
				}
			}
			if (item.styles && item.styles.className && /(?:^| )more(?: |$)/.test(item.styles.className)) {
				this.topNavMore = {
					item: item,
					channelID : item.action[1][1].channelID
				};
			}
		}, this);
		return nav;
	}


/*function loadNavData() {
		// get data from file (static or dynamic)
		var nav = NAVIGATION_DATA;
		// apply some rules
		babelgum.forEach(nav.children, function(item) {
			if (item.children && item.children.length > 0) {
				item.action = ["expand"];
				// find alternate action, i.e. the action associated to the sub-menu "All"
				if (this.isCategoryItem(item)) {
					item.altAction = item.children[0].children[0].action;
					
					// compute map: top level item by channel id 
					if (item.altAction && item.altAction[0] == "clips" 
						&& item.altAction[1][0] == "SEARCH"
						&& item.altAction[1][1].channelID) 
					{
						var channelID = item.altAction[1][1].channelID;
						topNavItemByChannel[channelID] = item;
					}
				}
			}
		}, this);
		return nav;
	}*/


function findTopNavItem(clip) {
		var channelsIDs = clip.navChannelsIDs;
		if (channelsIDs == null) {
			channelsIDs = [];
		}
	
	
		var foundItems = [];
		var foundMore = false;
		var len = channelsIDs.length;
		for(var i=0; i<len; i++) {
			var channelID = channelsIDs[i];
			var item = topNavItemByChannel[channelID];
			if (item != null) {
				foundItems.push(item);
			}
			else if (this.topNavMore && this.topNavMore.channelID == channelID) {
				foundMore = true;
			}
		}
		
		var result;
		if (foundItems.length > 0) {
			result = toTopNavItem(foundItems[0]);
		}
		else if (foundMore) {
			result = toTopNavItem(this.topNavMore.item);
		}
		else {
			// no category found
			result = {
				label : "More",
				color : "grey",
				action : null,
				url : ""
			};
		}
		
		return result;
	}

function toTopNavItem(item) {
		var action = item.altAction ? item.altAction : item.action;
		var result = {
			label : item.label,
			color : item.styles.id,
			action : action,
			url : ''
		};
		return result;
	}


/*
	
function findTopNavItem(clip) {
		var channelsIDs = clip.navChannelsIDs;
		if (channelsIDs == null) {
			channelsIDs = [];
		}
		
		var foundItems = [];
		var len = channelsIDs.length;
		for(var i=0; i<len; i++) {
			var channelID = channelsIDs[i];
			var item = topNavItemByChannel[channelID];
			if (item != null) {
				foundItems.push(item);
				break;
			}
		}
		
		var result;
		if (foundItems.length > 0) {
			var foundItem = foundItems[0];
			result = {
				label : foundItem.label,
				color : foundItem.styles.id,
				action : foundItem.altAction,
				url : ''
			};
		}
		else {
			// TODO get "More" item
			result = {
				label : "More",
				color : "grey",
				action : null,
				url : ""
			};
		}
		
		return result;
	}*/

topNavItemByChannel = [];

		
		
	
