/* global pm, wpcom_reblog */

var jetpackLikesWidgetQueue = [];
var jetpackLikesWidgetBatch = [];
var jetpackLikesMasterReady = false;

function JetpackLikespostMessage( message, target ) {
	if ( 'string' === typeof message ){
		try {
			message = JSON.parse( message );
		} catch(e) {
			return;
		}
	}

	pm( {
		target: target,
		type: 'likesMessage',
		data: message,
		origin: '*'
	} );
}

function JetpackLikesBatchHandler() {
	var requests = [];
	jQuery( 'div.jetpack-likes-widget-unloaded' ).each( function() {
		if ( jetpackLikesWidgetBatch.indexOf( this.id ) > -1 ) {
			return;
		}
		jetpackLikesWidgetBatch.push( this.id );
		var regex = /like-(post|comment)-wrapper-(\d+)-(\d+)-(\w+)/,
			match = regex.exec( this.id ),
			info;

		if ( ! match || match.length !== 5 ) {
			return;
		}

		info = {
			blog_id: match[2],
			width:   this.width
		};

		if ( 'post' === match[1] ) {
			info.post_id = match[3];
		} else if ( 'comment' === match[1] ) {
			info.comment_id = match[3];
		}

		info.obj_id = match[4];

		requests.push( info );
	});

	if ( requests.length > 0 ) {
		JetpackLikespostMessage( { event: 'initialBatch', requests: requests }, window.frames['likes-master'] );
	}
}

function JetpackLikesMessageListener( event ) {
	if ( 'undefined' === typeof event.event ) {
		return;
	}

	if ( 'masterReady' === event.event ) {
		jQuery( document ).ready( function() {
			jetpackLikesMasterReady = true;

			var stylesData = {
					event: 'injectStyles'
				},
				$sdTextColor = jQuery( '.sd-text-color' ),
				$sdLinkColor = jQuery( '.sd-link-color' );

			if ( jQuery( 'iframe.admin-bar-likes-widget' ).length > 0 ) {
				JetpackLikespostMessage( { event: 'adminBarEnabled' }, window.frames[ 'likes-master' ] );

				stylesData.adminBarStyles = {
					background: jQuery( '#wpadminbar .quicklinks li#wp-admin-bar-wpl-like > a' ).css( 'background' ),
					isRtl: ( 'rtl' === jQuery( '#wpadminbar' ).css( 'direction' ) )
				};
			}

			if ( ! window.addEventListener ) {
				jQuery( '#wp-admin-bar-admin-bar-likes-widget' ).hide();
			}

			stylesData.textStyles = {
				color:          $sdTextColor.css( 'color' ),
				fontFamily:     $sdTextColor.css( 'font-family' ),
				fontSize:       $sdTextColor.css( 'font-size' ),
				direction:      $sdTextColor.css( 'direction' ),
				fontWeight:     $sdTextColor.css( 'font-weight' ),
				fontStyle:      $sdTextColor.css( 'font-style' ),
				textDecoration: $sdTextColor.css('text-decoration')
			};

			stylesData.linkStyles = {
				color:          $sdLinkColor.css('color'),
				fontFamily:     $sdLinkColor.css('font-family'),
				fontSize:       $sdLinkColor.css('font-size'),
				textDecoration: $sdLinkColor.css('text-decoration'),
				fontWeight:     $sdLinkColor.css( 'font-weight' ),
				fontStyle:      $sdLinkColor.css( 'font-style' )
			};

			JetpackLikespostMessage( stylesData, window.frames[ 'likes-master' ] );

			JetpackLikesBatchHandler();

			jQuery( document ).on( 'inview', 'div.jetpack-likes-widget-unloaded', function() {
				jetpackLikesWidgetQueue.push( this.id );
			});
		});
	}

	if ( 'showLikeWidget' === event.event ) {
		jQuery( '#' + event.id + ' .post-likes-widget-placeholder'  ).fadeOut( 'fast', function() {
			jQuery( '#' + event.id + ' .post-likes-widget' ).fadeIn( 'fast', function() {
				JetpackLikespostMessage( { event: 'likeWidgetDisplayed', blog_id: event.blog_id, post_id: event.post_id, obj_id: event.obj_id }, window.frames['likes-master'] );
			});
		});
	}

	if ( 'clickReblogFlair' === event.event ) {
		wpcom_reblog.toggle_reblog_box_flair( event.obj_id );
	}

	if ( 'showOtherGravatars' === event.event ) {
		var $container = jQuery( '#likes-other-gravatars' ),
			$list = $container.find( 'ul' ),
			offset, rowLength, height, scrollbarWidth;

		$container.hide();
		$list.html( '' );

		$container.find( '.likes-text span' ).text( event.total );

		jQuery.each( event.likers, function( i, liker ) {
			$list.append( '<li class="' + liker.css_class + '"><a href="' + liker.profile_URL + '" class="wpl-liker" rel="nofollow" target="_parent"><img src="' + liker.avatar_URL + '" alt="' + liker.name + '" width="30" height="30" style="padding-right: 3px;" /></a></li>');
		} );

		offset = jQuery( '[name=\'' + event.parent + '\']' ).offset();

		$container.css( 'left', offset.left + event.position.left - 10 + 'px' );
		$container.css( 'top', offset.top + event.position.top - 33 + 'px' );

		rowLength = Math.floor( event.width / 37 );
		height = ( Math.ceil( event.likers.length / rowLength ) * 37 ) + 13;
		if ( height > 204 ) {
			height = 204;
		}

		$container.css( 'height', height + 'px' );
		$container.css( 'width', rowLength * 37 - 7 + 'px' );

		$list.css( 'width', rowLength * 37 + 'px' );

		$container.fadeIn( 'slow' );

		scrollbarWidth = $list[0].offsetWidth - $list[0].clientWidth;
		if ( scrollbarWidth > 0 ) {
			$container.width( $container.width() + scrollbarWidth );
			$list.width( $list.width() + scrollbarWidth );
		}
	}
}

pm.bind( 'likesMessage', function(e) { JetpackLikesMessageListener(e); } );

jQuery( document ).click( function( e ) {
	var $container = jQuery( '#likes-other-gravatars' );

	if ( $container.has( e.target ).length === 0 ) {
		$container.fadeOut( 'slow' );
	}
});

function JetpackLikesWidgetQueueHandler() {
	var $wrapper, wrapperID, found;
	if ( ! jetpackLikesMasterReady ) {
		setTimeout( JetpackLikesWidgetQueueHandler, 500 );
		return;
	}

	if ( jetpackLikesWidgetQueue.length > 0 ) {
		// We may have a widget that needs creating now
		found = false;
		while( jetpackLikesWidgetQueue.length > 0 ) {
			// Grab the first member of the queue that isn't already loading.
			wrapperID = jetpackLikesWidgetQueue.splice( 0, 1 )[0];
			if ( jQuery( '#' + wrapperID ).hasClass( 'jetpack-likes-widget-unloaded' ) ) {
				found = true;
				break;
			}
		}
		if ( ! found ) {
			setTimeout( JetpackLikesWidgetQueueHandler, 500 );
			return;
		}
	} else if ( jQuery( 'div.jetpack-likes-widget-unloaded' ).length > 0 ) {
		// Grab any unloaded widgets for a batch request
		JetpackLikesBatchHandler();

		// Get the next unloaded widget
		wrapperID = jQuery( 'div.jetpack-likes-widget-unloaded' ).first()[0].id;
		if ( ! wrapperID ) {
			// Everything is currently loaded
			setTimeout( JetpackLikesWidgetQueueHandler, 500 );
			return;
		}
	}

	if ( 'undefined' === typeof wrapperID ) {
		setTimeout( JetpackLikesWidgetQueueHandler, 500 );
		return;
	}

	$wrapper = jQuery( '#' + wrapperID );
	$wrapper.find( 'iframe' ).remove();

	if ( $wrapper.hasClass( 'slim-likes-widget' ) ) {
		$wrapper.find( '.post-likes-widget-placeholder' ).after( '<iframe class="post-likes-widget jetpack-likes-widget" name="' + $wrapper.data( 'name' ) + '" height="22px" width="68px" frameBorder="0" scrolling="no" src="' + $wrapper.data( 'src' ) + '"></iframe>' );
	} else {
		$wrapper.find( '.post-likes-widget-placeholder' ).after( '<iframe class="post-likes-widget jetpack-likes-widget" name="' + $wrapper.data( 'name' ) + '" height="55px" width="100%" frameBorder="0" src="' + $wrapper.data( 'src' ) + '"></iframe>' );
	}

	$wrapper.removeClass( 'jetpack-likes-widget-unloaded' ).addClass( 'jetpack-likes-widget-loading' );

	$wrapper.find( 'iframe' ).load( function( e ) {
		var $iframe = jQuery( e.target );
		$wrapper.removeClass( 'jetpack-likes-widget-loading' ).addClass( 'jetpack-likes-widget-loaded' );

		JetpackLikespostMessage( { event: 'loadLikeWidget', name: $iframe.attr( 'name' ), width: $iframe.width() }, window.frames[ 'likes-master' ] );

		if ( $wrapper.hasClass( 'slim-likes-widget' ) ) {
			$wrapper.find( 'iframe' ).Jetpack( 'resizeable' );
		}
	});
	setTimeout( JetpackLikesWidgetQueueHandler, 250 );
}
JetpackLikesWidgetQueueHandler();
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   /**
 * Like Button toolbar button, loading text & container styles
 *
 * @todo: doesn't look like "style.css" is used anymore.
 */


/* Master container */
#jp-post-flair {
	padding-top: .5em;
}

/* Overall Sharedaddy block title */
div.sharedaddy,
#content div.sharedaddy,
#main div.sharedaddy {
	clear: both;
}

div.sharedaddy h3.sd-title {
	margin: 0 0 1em 0;
	display: inline-block;
	line-height: 1.2;
	font-size: 9pt;
	font-weight: bold;
}

div.sharedaddy h3.sd-title:before {
	content: "";
	display: block;
	width: 100%;
	min-width: 30px;
	border-top: 1px solid #ddd;
	margin-bottom: 1em;
}


/* Toolbar */
#wpadminbar li#wp-admin-bar-admin-bar-likes-widget {
	width: 61px;
	overflow: hidden;
}

#wpadminbar iframe.admin-bar-likes-widget {
	width: 61px;
	height: 28px;
	min-height: 28px;
	border-width: 0px;
	position: absolute;
	top: 0;
}

div.jetpack-likes-widget-wrapper {
	width: 100%;
	min-height: 50px;	/* Previous height, 60px */
	position: relative; /* Need to abs position placeholder and iframe so there isn't a jarring jump */
}

div.jetpack-likes-widget-wrapper .sd-link-color {
	font-size: 12px;
}

div.jetpack-likes-widget-wrapper.slim-likes-widget {
	width: 1px; /* initial default */
	min-height: 0;
}

#likes-other-gravatars {
	display: none;
	position: absolute;
	padding: 10px;
	background-color: #000;
	border-width: 0;
	opacity: 0.88;
	filter: alpha(opacity=88);
	box-shadow: 0 0 10px black;
	min-width: 130px;
	z-index: 1000;
}

#likes-other-gravatars * {
	line-height: normal;
}

#likes-other-gravatars .likes-text {
	color: white;
	font-size: 14px;
	padding-bottom: 5px;
}

#likes-other-gravatars ul,
#likes-other-gravatars li {
	margin: 0;
	padding: 0;
	text-indent: 0;
	list-style-type: none;
}

#likes-other-gravatars li::before {
	content: "";
}

#likes-other-gravatars ul.wpl-avatars {
	overflow: auto;
	display: block;
	position: absolute;
	max-height: 190px;
}

#likes-other-gravatars ul.wpl-avatars li {
	width: 32px;
	height: 32px;
	float: left;
	margin: 0 5px 5px 0;
}

#likes-other-gravatars ul.wpl-avatars li a {
	margin: 0 2px 0 0;
	border-bottom: none !important;
	display: block;
}

#likes-other-gravatars ul.wpl-avatars li a img {
	background: none;
	border: none;
	margin: 0 !important;
	padding: 0 !important;
	position: static;
}

div.sd-box {
	border-top: 1px solid #ddd;
	border-top: 1px solid rgba(0,0,0,.13);
}

.entry-content .post-likes-widget, .post-likes-widget,
.comment-likes-widget {
	margin: 0;
	border-width: 0;
	display: block;
}


/* Loading text */
.post-likes-widget-placeholder {
	margin: 0;
	border-width: 0;
	position: relative;
}

.post-likes-widget-placeholder .button {
	display: none;	/* Let's not show a dummy like button, let's just make a great button experience once it's loaded */
}

.post-likes-widget-placeholder .button span {
}

.post-likes-widget-placeholder .loading {
	color: #999;
	font-size: 12px;
}

.slim-likes-widget .post-likes-widget {
	width: auto;
	float: none;
}


/* Like Special cases (display on it's own) */
div.sharedaddy.sd-like-enabled .sd-like h3 {
	display: none;
}

div.sharedaddy.sd-like-enabled .sd-like .post-likes-widget {
	width: 100%;
	float: none;
	position: absolute; /* Need to abs position placeholder and iframe so there isn't a jarring jump */
	top: 0;
}

.comment-likes-widget {
	width: 100%;
}


/* Make ratings block. @todo: make !important unnecessary by removing inline style */
.pd-rating {
	display: block !important;
}


/* Hide G+ title */
.sd-gplus .sd-title {
	display: none;
}
