
var publish2_embed_request = false;

function publish2_embedcode(html_object, url, max_width) {
  
  url = escape(url);
  max_width = escape(max_width);
  var api_url = 'http://api.embed.ly/v1/api/oembed?url=' + url + '&maxwidth=' + max_width + '&callback=?';
  //jQuery JSON call
  jQuery.getJSON(api_url, function(json) {
    if (json.html && html_object.parents('.publish2_item').find('span.p2data_link_format').html()) {
      html_object.parent().find('span.publish2_video_placeholder').replaceWith(json.html);
    } else if (json.html) {
      html_object.after('<div class="publish2_video_embed">' + json.html + '</div>');
    }
  });
  
}

function publish2_count_hidden(publish2_widget, direction) {

	var j = 0;
	var end = false;
	var hidden = 0;
	var linksPerView = parseInt(publish2_widget.find('span.p2data_link_count').html());
	publish2_widget.find('.publish2_item').each(function(){
		if ((jQuery(this).is(':hidden') || jQuery(this).css('display') == 'none') && end == false) {
			hidden++;
		} else {
			end = true;
		}
	});

	var anyVideos = 0;
	if (direction == 'back') {
		var hiddenPlusPlus = hidden;
		var hiddenPlus = hiddenPlusPlus - linksPerView;
	} else if (direction == 'next') {
		var hiddenPlus = hidden + linksPerView;
		var hiddenPlusPlus = hiddenPlus + linksPerView;
	}
	
	// If the oEmbed codes haven't been requested yet, initiate requests for all
	if (!publish2_embed_request && (publish2_widget.find('span.p2data_embed_video').html() && !publish2_widget.find('span.p2data_link_format').html()) || publish2_widget.find('span.p2data_link_format').html().search('%video%') != -1) {
	  jQuery('a.publish2_story_headline').each(function() {
	    if (!jQuery(this).parents('.publish2_item').find('object').length && !jQuery(this).parents('.publish2_item').find('embed').length) {
	      var href = jQuery(this).attr('href');
	      publish2_embedcode(jQuery(this), href, parseInt(publish2_widget.find('span.p2data_video_width').html()));
	    }
	  });
	  publish2_embed_request = true;
	}

	publish2_widget.find('.publish2_pagination #publish2_next').removeClass('inactive active');
	publish2_widget.find('.publish2_pagination #publish2_back').removeClass('inactive active');

	j = 100;
	if (direction == 'back') {
		var startLinks = hidden - linksPerView;
		if (startLinks < 0) {
			startLinks = 0;
		}
		var endLinks = startLinks + linksPerView - 1;
		if (startLinks < 1) {
			publish2_widget.find('.publish2_pagination #publish2_back').addClass('inactive');
		} else {
			publish2_widget.find('.publish2_pagination #publish2_back').addClass('active');
		}
		publish2_widget.find('.publish2_pagination #publish2_next').addClass('active');
		publish2_display_links(startLinks, endLinks, publish2_widget);

	} else if (direction == 'next') {
		var startLinks = hidden + linksPerView;
		startLinks - 1;
		if (startLinks < 0) {
			startLinks = 0;
		}
		var endLinks = startLinks + linksPerView - 1;
		// Get the total number of links. If the end is longer than that, don't do it
		var totalLinks = publish2_widget.find('.publish2_item').size();
		totalLinks--;
		if (endLinks >= totalLinks) {
			endLinks = totalLinks;
			startLinks = endLinks - linksPerView + 1;
			publish2_widget.find('.publish2_pagination #publish2_next').addClass('inactive');
		} else {
			publish2_widget.find('.publish2_pagination #publish2_next').addClass('active');
		}
		publish2_widget.find('.publish2_pagination #publish2_back').addClass('active');
		publish2_display_links(startLinks, endLinks, publish2_widget);
	}

}

/**
 * Displays links based on the div, starting number and ending number
 */
function publish2_display_links(startLinks, endLinks, publish2_widget) {
	var newStartLinks = startLinks;
	var newEndLinks = endLinks;
	publish2_widget.find('.publish2_item').each(function(i, val) {
		if (i >= newStartLinks && i <= newEndLinks) {
			jQuery(this).show();
		} else {
			jQuery(this).hide();
		}
	});
}

/**
 * Tests the link URL to see if it's a tweet, video, etc. or not
 */
function publish2_urltest(url) {
	
	if (url.match(/http(?:s*):\/\/twitter.com\/(\S+)\/(?:status|statuses)\/(\d+)/) != null) {
		return 'twitter';
	} else if (url.match(/http:\/\/www.youtube.com\/watch/) != null) {
		return 'youtube';
	} else if (url.match(/http:\/\/www.vimeo.com/) != null || url.match(/http:\/\/vimeo.com/) != null) {
		return 'vimeo';
	} else {
		return 'standard';
	}
	
}


jQuery(document).ready(function() {
  
  //publish2_embedcode('http://blip.tv/file/2710217', 100);
	
	jQuery('.publish2_pagination #publish2_back').click(function() {
		publish2_count_hidden(jQuery(this).parents('.publish2.widget'), 'back');
	});
	
	jQuery('.publish2_pagination #publish2_next').click(function() {
		publish2_count_hidden(jQuery(this).parents('.publish2.widget'), 'next');
	});
	
	jQuery('.publish2.widget').each(function() {
		if (jQuery(this).find('span.p2data_pagination').html() == 'on') {
			publish2_widget = jQuery(this);
			var p2data_feedlink = publish2_widget.find('span.p2data_feedlink').html();
			var p2data_shorturl = publish2_widget.find('span.p2data_shorturl').html();
			var p2data_character_limit = publish2_widget.find('span.p2data_character_limit').html();
			var p2data_share_buttons = publish2_widget.find('span.p2data_share_buttons').html();
			var p2data_link_count = parseInt(publish2_widget.find('span.p2data_link_count').html());
			var p2data_publication_name = publish2_widget.find('span.p2data_publication_name').html();
			var p2data_publication_date = publish2_widget.find('span.p2data_publication_date').html();
			var p2data_journalist_full_name = publish2_widget.find('span.p2data_journalist_full_name').html();
			var p2data_description = publish2_widget.find('span.p2data_description').html();
			var p2data_tags = publish2_widget.find('span.p2data_tags').html();
			var p2data_link_format = publish2_widget.find('span.p2data_link_format').html();
			var p2data_embed_video = publish2_widget.find('span.p2data_embed_video').html();
			var p2data_video_width = parseInt(publish2_widget.find('span.p2data_video_width').html());
			var p2data_quote = publish2_widget.find('span.p2data_quote').html();
			
			var minimum_limit = 20;

			// @todo Ensure that these requests are made chronologically
			for (i = 1; i <= 5; i++) {
				var new_link_count = p2data_link_count * i;
				var json_url = p2data_feedlink + '.js?page=2&number_of_items=' + new_link_count;
				jQuery.ajax({
					type: "GET",
					url: publish2_plugin_url + "/php/p2ajax.php", // @todo Ensure blog installed at root
					data: {
						url: json_url
					},
					cache: true,
					success: function(data, textStatus) {

						// Check to make sure it's a valid JSON feed from Publish2. Else, parse it
						if (data.charAt(0) != '{') {
							data = 'badfeed';
						} else {
							data = JSON.parse(data);
						
							jQuery.each(data.items,	function(i, item) {
							  
							  if (p2data_shorturl) {
									var link = item.short_url;
								} else {
									var link = item.link;
								}
							
								if (p2data_link_format) {
								  
								  var new_item = '<div class="publish2_item" style="display:none;">' + p2data_link_format;
								  var total_characters = 0;
								  
								  if (publish2_urltest(item.link) == 'twitter') {
            				new_item = new_item.replace('%headline%', '<a class="publish2_link" href="' + link + '">' + item.publication_name + '</a>: ' +  item.title);
            				new_item = new_item.replace('%source%', 'Twitter');
								  } 

            			new_item = new_item.replace('%headline%', '<a class="publish2_story_headline publish2_link" href="' + link + '">' + item.title + '</a>');
            			total_characters = total_characters + item.title.length;
            			
            			new_item = new_item.replace('%video%', '<span class="publish2_video_placeholder"></span>');
            			
                  new_item = new_item.replace('%source%', item.publication_name);
                  total_characters = total_characters + item.publication_name.length;
            				
                  new_item = new_item.replace('%date%', item.publication_date);
                  total_characters = total_characters + item.publication_date.length;

                  new_item = new_item.replace('%journalist%', '<a class="publish2_link" href="' + item.journalist_profile + '">' + item.journalist_full_name + '</a>');
            			total_characters = total_characters + item.journalist_full_name.length;
            			
                  if (p2data_character_limit && item.description) {
                    var description_characters = item.description.length;
                    total_characters = total_characters + description_characters;
                    if (total_characters > p2data_character_limit) {
                      var characters_over = total_characters - p2data_character_limit;
                      var truncate_description = description_characters - characters_over;
                      if (truncate_description < minimum_limit) {
                        new_character_limit = minimum_limit;
                      } else {
                        new_character_limit = p2data_character_limit - (total_characters - description_characters);
                      }
                      var start = new_character_limit + 1;
                      var stop = new_character_limit + 2;
                      var foundChar = '';
                      while (foundChar != ' ') {
                        start--;
                        stop--;
                        foundChar = item.description.substring(start,stop);
                      }
                      stop--;
                      item.description = item.description.substring(0, stop) + '...';
                    }
                  }
          				new_item = new_item.replace('%comment%', item.description);
          				
									new_item = new_item.replace('%quote%', item.quote);
									
									var alltags = '';
									if (item.tags != undefined && item.tags != undefined) {
										jQuery.each(item.tags[0], function(i, tag) {
											alltags += ' <a href="' + tag.link + '">' + tag.name + '</a>,';
										});
										alltags = alltags.replace(/,$/,"");
									}
									new_item = new_item.replace('%tags%', alltags);
									
									// Show "Share on: Twitter, Facebook, LinkedIn" buttons if the user wants
            			if (p2data_share_buttons) {
              			var encoded_title = escape(item.title);
              			if (item.short_url) {
              			  var encoded_link = escape(item.short_url);
              			} else {
              			  var encoded_link = escape(item.link);
              			}
              			if (item.description) {
              			  var encoded_description = escape(item.description);
              			} else {
              			  var encoded_description = '';
              			}
              			if (item.publication_name) {
              			  var encoded_publication = escape(item.publication_name);
              			} else {
              			  var encoded_publication = '';
              			}
              			if (publish2_urltest(item.link) == 'twitter') {
              			  new_item += '<div class="publish2_share">Retweet on: ';
                			new_item += '<a href="http://twitter.com/?status=RT+' + encoded_publication + '+' + encoded_title + '">';
                			new_item += '<img width="16px" height="16px" style="border:none;" class="publish2_share_twitter" src="' + publish2_plugin_url + '/img/twitter_s16.png" /></a> ';
                			new_item += '</div>';
              			} else {
                			new_item += '<div class="publish2_share">Share on: ';
                			new_item += '<a href="http://twitter.com/?status=' + encoded_title + '+' + encoded_link + '">';
                			new_item += '<img width="16px" height="16px" style="border:none;" class="publish2_share_twitter" src="' + publish2_plugin_url + '/img/twitter_s16.png" /></a> ';
                			new_item += '<a href="http://www.facebook.com/sharer.php?t=' + encoded_title + '&u=' + encoded_link + '">';
                			new_item += '<img width="16px" height="16px" style="border:none;" class="publish2_share_facebook" src="' + publish2_plugin_url + '/img/facebook_s16.png" /></a> ';
                			new_item += '<a href="http://www.linkedin.com/shareArticle?mini=true'
                			        + '&url=' + encoded_link 
                			        + '&title=' + encoded_title
                			        + '&summary=' + encoded_description
                			        + '&source=' + encoded_publication + '">';
                			new_item += '<img width="16px" height="16px" style="border:none;" class="publish2_share_linkedin" src="' + publish2_plugin_url + '/img/linkedin_s16.png" /></a>';
                			new_item += '</div>';
                		}
            		  }
            		  
            		  new_item += '</div>';
            			
            			publish2_widget.find('.publish2_pagination').before(new_item);
								  
								} else {
							
									var new_item = '<li class="publish2_item" style="display:none;">';
									
									// Character truncation on the description if enabled
                  if (p2data_character_limit && item.description) {
            			  var total_characters = 0;
                    total_characters = total_characters + item.title.length;
            			  if (p2data_publication_name) {
            			    total_characters = total_characters + item.publication_name.length;
            			  }
            			  if (p2data_publication_date) {
            			    total_characters = total_characters + item.publication_date.length;
            			  }
            			  if (p2data_journalist_full_name) {
            			    total_characters = total_characters + item.journalist_full_name.length;
            			  }
                    var description_characters = item.description.length;
                    total_characters = total_characters + description_characters;
                    if (total_characters > p2data_character_limit) {
                      var characters_over = total_characters - p2data_character_limit;
                      var truncate_description = description_characters - characters_over;
                      if (truncate_description < minimum_limit) {
                        new_character_limit = minimum_limit;
                      } else {
                        new_character_limit = p2data_character_limit - (total_characters - description_characters);
                      }
                      var start = new_character_limit + 1;
                      var stop = new_character_limit + 2;
                      var foundChar = '';
                      while (foundChar != ' ') {
                        start--;
                        stop--;
                        foundChar = item.description.substring(start,stop);
                      }
                      stop--;
                      var description = item.description.substring(0, stop) + '...';
                    }
                  } else {
                    var description = item.description;
                  }
						  
						      if (publish2_urltest(item.link) == 'twitter') {
						        new_item += '<span class="publish2_tweet">';
            				if (item.publication_name.length != 0) {
            					new_item += '<a class="publish2_link" href="' + item.link + '">' + item.publication_name + '</a>: ';
            				}
            				new_item += item.title + '</span>';
            				if (p2data_publication_name && (p2data_publication_date && item.publication_date.length != 0)) {
            					new_item += '<div><span class="publish2_story_publication_name">Twitter</span> | <span class="publish2_story_publication_date">' + item.publication_date + '</span></div>';
            				} else if (!p2data_publication_name && (p2data_publication_date && item.publication_date.length != 0)) {
            					new_item += '<div><span class="publish2_story_publication_date">' + item.publication_date + '</span></div>';
            				} else if (p2data_publication_name && !p2data_publication_date) {
            					new_item += '<div><span class="publish2_story_publication_name">Twitter</span></div>';
            				}
						      } else {
						        
									  new_item += '<a class="publish2_story_headline publish2_link" href="' + link + '">' + item.title + '</a>';
									  
									  //if (p2data_embed_video) {
									  //  new_item += publish2_embedcode(item.link, p2data_video_width);
									  //}
									  
									  if ((p2data_publication_name && item.publication_name.length != 0) && (p2data_publication_date && item.publication_date.length != 0)) {
  										new_item += '<div><span class="publish2_story_publication_name">' + item.publication_name + '</span>' + ' | ' + '<span class="publish2_story_publication_date">' + item.publication_date + '</span></div>';
  									} else if ((p2data_publication_name && item.publication_name.length != 0) && (p2data_publication_date && item.publication_date.length == 0)) {
  										new_item += '<div><span class="publish2_story_publication_name">' + item.publication_name + '</span></div>';
  									} else if ((p2data_publication_name && item.publication_name.length == 0) && (p2data_publication_date && item.publication_date.length != 0)) {
  										new_item += '<div><span class="publish2_story_publication_date">' + item.publication_date + '</span></div>';
  									} else if ((p2data_publication_name && item.publication_name.length != 0) && (!p2data_publication_date)) {
  										new_item += '<div><span class="publish2_story_publication_name">' + item.publication_name + '</span></div>';
  									} else if ((p2data_publication_date && item.publication_date.length != 0) && (!p2data_publication_name)) {
  										new_item += '<div><span class="publish2_story_publication_date">' + item.publication_date + '</span></div>';
  									}
  									
									}
								
									if ((p2data_description && item.description.length != 0) && p2data_journalist_full_name) {
										new_item += '<div><a href="' + item.journalist_profile + '" class="publish2_journalist_profile publish2_link">' + item.journalist_full_name + '</a>' + ' says: ';
										new_item += '<span class="publish2_story_description">' + description + '</span></div>';
									} else if (p2data_description) {
									  new_item += '<div><span class="publish2_story_description">' + description + '</span></div>';
									}

									if (p2data_quote && item.quote.length != 0) {
										new_item += '<div><span class="publish2_story_quote"><span class="publish2_story_quote_slug">Quote:</span> ' + item.quote + '</span></div>';
									}
									
									if (p2data_tags && item.tags != undefined && item.tags != undefined) {
										var alltags = 'Tags: ';
										jQuery.each(item.tags[0], function(i, tag) {
											alltags += ' <a href="' + tag.link + '">' + tag.name + '</a>,';
										});
										alltags = alltags.replace(/,$/,"");
										new_item += '<div>' + alltags + '</div>';
									}
									
									// Show "Share on: Twitter, Facebook, LinkedIn" buttons if the user wants
            			if (p2data_share_buttons) {
              			var encoded_title = escape(item.title);
              			if (item.short_url) {
              			  var encoded_link = escape(item.short_url);
              			} else {
              			  var encoded_link = escape(item.link);
              			}
              			if (item.description) {
              			  var encoded_description = escape(item.description);
              			} else {
              			  var encoded_description = '';
              			}
              			if (item.publication_name) {
              			  var encoded_publication = escape(item.publication_name);
              			} else {
              			  var encoded_publication = '';
              			}
              			if (publish2_urltest(item.link) == 'twitter') {
              			  new_item += '<div class="publish2_share">Retweet on: ';
                			new_item += '<a href="http://twitter.com/?status=RT+' + encoded_publication + '+' + encoded_title + '">';
                			new_item += '<img width="16px" height="16px" style="border:none;" class="publish2_share_twitter" src="' + publish2_plugin_url + '/img/twitter_s16.png" /></a> ';
                			new_item += '</div>';
              			} else {
                			new_item += '<div class="publish2_share">Share on: ';
                			new_item += '<a href="http://twitter.com/?status=' + encoded_title + '+' + encoded_link + '">';
                			new_item += '<img width="16px" height="16px" style="border:none;" class="publish2_share_twitter" src="' + publish2_plugin_url + '/img/twitter_s16.png" /></a> ';
                			new_item += '<a href="http://www.facebook.com/sharer.php?t=' + encoded_title + '&u=' + encoded_link + '">';
                			new_item += '<img width="16px" height="16px" style="border:none;" class="publish2_share_facebook" src="' + publish2_plugin_url + '/img/facebook_s16.png" /></a> ';
                			new_item += '<a href="http://www.linkedin.com/shareArticle?mini=true'
                			        + '&url=' + encoded_link 
                			        + '&title=' + encoded_title
                			        + '&summary=' + encoded_description
                			        + '&source=' + encoded_publication + '">';
                			new_item += '<img width="16px" height="16px" style="border:none;" class="publish2_share_linkedin" src="' + publish2_plugin_url + '/img/linkedin_s16.png" /></a>';
                			new_item += '</div>';
                		}
            		  }
								
									new_item += '</li>';
									publish2_widget.find('ul').append(new_item);
								
								}
							
							});
							
						}

					},
					error: function(XMLHttpRequest, textStatus, errowThrown) {
						// @todo Usable silent error
						link_element = "Official error: " + textStatus;
			
					},
					dataType: "text"
				});
			}
			
		}
	});
	
});