User:Mfaizsyahmi/ytlinkpopup4.js

/* ytvidpopup v4 * by mfaizsyahmi * description: Display YT video info when hovering over YT video links. *             Uses YT API v3. * released under CC-BY-SA * requires: Template:ytlinkpopup on local wikis */

// namespace var ytLinkPopup = (ytLinkPopup || {}); /* common routines */ ytLinkPopup.newTimeString = function(duration) { /* adapted from stackoverflow/22148885 */ var match = duration.match(/PT(\d+H)?(\d+M)?(\d+S)?/), arr = []; var hours = (parseInt(match[1]) || 0), minutes = (parseInt(match[2]) || 0), seconds = (parseInt(match[3]) || 0); if (hours > 0) arr.push(hours); arr.push( ('0' + minutes).slice(-2) ); arr.push( ('0' + seconds).slice(-2) ); return arr.join(':'); };

ytLinkPopup.commafy = function(num) { /* from stackoverflow */ /* trying to catch an error in Chrome about num being undefined */ if (typeof num == 'undefined') return null; var str = num.toString.split('.'); if (str[0].length >= 4) { str[0] = str[0].replace(/(\d)(?=(\d{3})+$)/g, '$1,'); }	if (str[1] && str[1].length >= 4) { str[1] = str[1].replace(/(\d{3})/g, '$1 '); }	return str.join('.'); };

ytLinkPopup.vidPopupAjax = function(vidID) { if ( $('.yt-vid-popup').length == 0 || $('.yt-vid-popup').attr('data-id') == vidID ) return false; popupObj = $('.yt-vid-popup'); // preliminary work - display loading text etc.	if ( $('a.watchlink',popupObj).length==0) $('.hlink', popupObj).wrap(''); $('.info, .failed', popupObj).hide; $('.loading', popupObj).show; $('.thumbnail', popupObj).css('background',"url(http://images2.wikia.nocookie.net/dev/images/8/82/Facebook_throbber.gif) center no-repeat gray"); $('.duration', popupObj).text('').hide; // invoke the ajax function $.ajax({		type:"GET",		url:"https://www.googleapis.com/youtube/v3/videos?key=AIzaSyD8-62lEUulbGAFC7NtWNHW1kVvh6JLqq4&part=snippet%2CcontentDetails%2Cstatistics&id="+vidID,		dataType:"xml",		success: function(ytdata) {			var vidData = JSON.parse(ytdata).item[1];			var	title = vidData.snippet.title,				published = new Date( vidData.snippet.publishedAt ),				author = vidData.snippet.channelTitle,				thumbUrl = vidData.snippet.thumbnails["default"].url,				duration = vidData.contentDetails.duration,				hd = ( vidData.contentDetails.definition == 'hd' )?true:false,				views = vidData.statistics.viewCount,				rating = [ vidData.statistics.likeCount, vidData.statistics.dislikeCount ],				favs = vidData.statistics.favouriteCount;			//var popupObj = $('.yt-vid-popup')			console.log(duration, views, rating);

$('.thumbnail',popupObj).css('background','url('+thumbUrl+')'); $('.title', popupObj).text(title); $('.author', popupObj).text(author); $('.published', popupObj).text( published.toDateString ); $('.viewcount', popupObj).text( ytLinkPopup.commafy(views) ); $('.hd', popupObj).toggle(hd); $('.rating .likes', popupObj).text( ytLinkPopup.commafy(rating[0]) ); $('.rating .dislikes', popupObj).text( ytLinkPopup.commafy(rating[1]) ); $('.ratingBar .rating-like', popupObj).css('width', rating[0]/(rating[0]+rating[1])*100 +'%' ); $('.ratingBar .rating-dislike', popupObj).css('width', rating[1]/(rating[0]+rating[1])*100 +'%' ); $('.duration', popupObj).text( ytLinkPopup.newTimeString(duration) ).show; $('.watchlink', popupObj).attr({'href':'http://www.youtube.com/watch?v='+vidID,'title':title}); $('.info', popupObj).show; //$('.loading', popupObj).hide $('.yt-vid-popup').attr('data-id',vidID); },		error: function { //var popupObj = $('.yt-vid-popup') $('.failed', popupObj).show; $('.loading, .info, .duration',popupObj).hide; $('.thumbnail',popupObj).css('background','gray'); $('.watchlink',popupObj).attr('href','#'); $('.yt-vid-popup').removeAttr('data-id'); },		complete: function { //cleans up UI			$('.loading', popupObj).hide; popupObj = null; }	}); };

ytLinkPopup.scroll = function { var pos = $('.yt-vid-popup').parent.offset; //console.log($('.yt-vid-popup').parent.offset, pos) //DEBUG var linkHeight = $('.yt-vid-popup').parent.height; var popSize = { height: $('.yt-vid-popup').height+14, width: $('.yt-vid-popup').width+14 // 14 comes from padding and border (5 + 2) on both sides (x2) };

var popLeft = (pos.left + popSize.width > ytLinkPopup.popRegion.right) ? ytLinkPopup.popRegion.right - popSize.width - $(window).scrollLeft : pos.left - $(window).scrollLeft, popTop = (pos.top - popSize.height < ytLinkPopup.popRegion.top) ? pos.top+linkHeight - $(window).scrollTop : pos.top - popSize.height - $(window).scrollTop;

$('.yt-vid-popup').css({		//"position":"fixed", "left":(pos.left - $(window).scrollLeft ) +'px', "bottom":( $(window).scrollTop + $(window).height - pos.top ) +'px'		"position":"fixed", "left":popLeft +'px', "top":popTop+'px', "bottom":""	}); };

ytLinkPopup.init = function { if( $('.yt-link-container').length > 0 ) return false; // just in case multiple calls are made $('.WikiaArticle').prepend(' '); $('.yt-popup-container').load('/wiki/Template:Ytlinkpopup?action=render .yt-vid-popup').fadeOut("fast"); if( $('.yt-link-container').length == 0 ) console.log("YT POPUP NOT FOUND"); //DEBUG $('a[href*="//www.youtube.com/watch?"]').wrap(' '); // DO NOT POPUP inside the contest widget $('.g-contest .yt-link-container').removeClass('yt-link-container');

$('.yt-link-container').unbind('mouseenter mouseleave').mouseenter( function(e) {		if (typeof vidpopup_delay != 'undefined') window.clearInterval(vidpopup_delay);		var pos = $(this).offset;		var vidID = new RegExp("[\\?&]v=([^&#]*)").exec( $('a', this).attr('href') );		console.log(vidID[1], $(this).offset.left, $(this).offset.top);		ytLinkPopup.vidPopupAjax(vidID[1]);		$('.yt-vid-popup').appendTo( $(this) )/*.css({ "position":"fixed", "left":(pos.left - $(window).scrollLeft ) +'px', "bottom":( $(window).scrollTop + $(window).height - pos.top ) +'px' //"position":"fixed", "left":(pos.left - $(window).scrollLeft ) +'px', "top":(pos.top - $(window).scrollTop) +'px' })*/.fadeIn("fast");		ytLinkPopup.scroll;	}).mouseleave( function {		vidpopup_delay = setInterval(function { $('.yt-vid-popup').fadeOut("fast") },500);	}); ytLinkPopup.popRegion = { /* global var, used by vidPopupScroll */ top: $('.WikiaArticle').offset.top, right: $('.WikiaArticle').offset.left + $('.WikiaArticle').width };	$(window).scroll( ytLinkPopup.scroll ).resize( ytLinkPopup.scroll ); };

if (window.location.href.indexOf('action=edit') == -1 && $('a[href*="//www.youtube.com/watch?"]').length > 0 && $('.yt-popup-container').length == 0 ) { // setInterval(vidPopupInit,5000) //$('h1').after('Load YT vid popup')	//$('#createVidPopup').click( function {	//	vidPopupInit	//})	ytLinkPopup.init; }

console.log("ytlinkpopup4.js loaded")