// Default variables
var linkNum = 4;
var linkDivs = new Array();
var frameLinks = false;
var frameURL = "";
var returnLink = "";
var referral = "";
var addShareButtons = false;
var characterLimit = 0;
var minimumDescription = 100;
var profileURL = '';
var profileImages = false;

var recurringTimeout = 150;

// Initiates all of the functionality after the frame loads completely
function initiateWindow() {
	
	addLinkBehavior(1);
	showInitialLinks(linkNum, linkDivs, 1);
	
	// 
	if (addShareButtons == true) {
		showShareButtons(1);
	}
	
	// If there's a new profile URL, replace the default
	if (profileURL != '') {
		modifyProfileLink(1);
	}
	
	// Add profile images if we want them
	if (profileImages == true) {
		addProfileImages(1);
	}
	
	jQuery('div#linksnav-backbutton').bind('click', function(){
		countHidden('back');
	});
	
	jQuery('div#linksnav-nextbutton').bind('click', function(){
		countHidden('next');
	});
	
	jQuery('li.linksButton').bind("click", function(){
		jQuery('.linksWrap').hide();
		var id = jQuery(this).attr('id');
		if (id == 'allLinksButton') {
			jQuery('#allLinks').show();
			var totalLinks = jQuery('#allLinks .publish2_story').size();
			totalLinks--;
			if (totalLinks > linkNum) {
				jQuery('div#linksnav-nextbutton').show();
			} else {
				jQuery('div#linksnav-nextbutton').hide();
			}
			jQuery('div#linksnav-backbutton').hide();
			jQuery('.linksButton').removeClass('active');
			jQuery('#allLinksButton').addClass('active');
		} else if (id == 'topic1LinksButton') {
			jQuery('#topic1Links').show();
			var totalLinks = jQuery('#topic1Links .publish2_story').size();
			totalLinks--;
			if (totalLinks > linkNum) {
				jQuery('div#linksnav-nextbutton').show();
			} else {
				jQuery('div#linksnav-nextbutton').hide();
			}
			jQuery('div#linksnav-backbutton').hide();
			jQuery('.linksButton').removeClass('active');
			jQuery('#topic1LinksButton').addClass('active');
		} else if (id == 'topic2LinksButton') {
			jQuery('#topic2Links').show();
			var totalLinks = jQuery('#topic2Links .publish2_story').size();
			totalLinks--;
			if (totalLinks > linkNum) {
				jQuery('div#linksnav-nextbutton').show();
			} else {
				jQuery('div#linksnav-nextbutton').hide();
			}
			jQuery('div#linksnav-backbutton').hide();
			jQuery('.linksButton').removeClass('active');
			jQuery('#topic2LinksButton').addClass('active');
		} else if (id == 'topic3LinksButton') {
			jQuery('#topic3Links').show();
			var totalLinks = jQuery('#topic3Links .publish2_story').size();
			totalLinks--;
			if (totalLinks > linkNum) {
				jQuery('div#linksnav-nextbutton').show();
			} else {
				jQuery('div#linksnav-nextbutton').hide();
			}
			jQuery('div#linksnav-backbutton').hide();
			jQuery('.linksButton').removeClass('active');
			jQuery('#topic3LinksButton').addClass('active');
		} else if (id == 'topic4LinksButton') {
  		jQuery('#topic4Links').show();
  		var totalLinks = jQuery('#topic4Links .publish2_story').size();
  		totalLinks--;
  		if (totalLinks > linkNum) {
  			jQuery('div#linksnav-nextbutton').show();
  		} else {
  			jQuery('div#linksnav-nextbutton').hide();
  		}
  		jQuery('div#linksnav-backbutton').hide();
  		jQuery('.linksButton').removeClass('active');
  		jQuery('#topic4LinksButton').addClass('active');
  	}
	});	
}

function countHidden(direction) {
	var numDivs = linkDivs.length;
	for (var i = 0; i < numDivs; i++) {
		var j = 0;
		var end = false;
		var hidden = 0;
		if (jQuery('#'+linkDivs[i]).css('display') != 'none') {
			jQuery('#'+linkDivs[i]+' .publish2_story').each(function(){
				if (jQuery(this).css('display') == 'none' && end == false) {
					hidden++;
				} else {
					end = true;
				}
			});
			var anyVideos = 0;
			if (direction == 'back') {
				var hiddenPlusPlus = hidden;
				var hiddenPlus = hiddenPlusPlus - linkNum;
			} else if (direction == 'next') {
				var hiddenPlus = hidden + linkNum;
				var hiddenPlusPlus = hiddenPlus + linkNum;
			}
			// Look for video links and remove one end link if so
			jQuery('#'+linkDivs[i]+' .publish2_story').each(function(i, val) {
				if (i >= hiddenPlus && i <= hiddenPlusPlus) {
					if (jQuery(this).children('.publish2_video_wrapper').size() != 0) {
						anyVideos++;
					}
				}
			});
			
			j = 100;
			if (direction == 'back') {
				var startLinks = hidden - linkNum;
				if (startLinks < 0) {
					startLinks = 0;
				}
				var endLinks = startLinks + linkNum - 1;
				if (startLinks < 1) {
					jQuery('div#linksnav-backbutton').hide();
				}
				jQuery('div#linksnav-nextbutton').show();
				displayLinks(linkDivs[i], startLinks, endLinks);
			} else if (direction == 'next') {
				var startLinks = hidden + linkNum;
				startLinks - 1;
				if (startLinks < 0) {
					startLinks = 0;
				}
				var endLinks = startLinks + linkNum - 1;
				// Get the total number of links. If the end is longer than that, don't do it
				var totalLinks = jQuery('#'+linkDivs[i]+' .publish2_story').size();
				totalLinks--;
				if (endLinks >= totalLinks) {
					endLinks = totalLinks;
					startLinks = endLinks - linkNum + 1;
					jQuery('div#linksnav-nextbutton').hide();
				}
				jQuery('div#linksnav-backbutton').show();
				displayLinks(linkDivs[i], startLinks, endLinks);
			}
		}
	}
}

// Displays links based on the div, starting number and ending number
function displayLinks(linksDiv, startLinks, endLinks) {
	var newStartLinks = startLinks;
	var newEndLinks = endLinks;
	
	jQuery('#'+linksDiv+' .publish2_story').each(function(i, val) {
		if (i >= newStartLinks && i <= newEndLinks) {
			if (characterLimit != 0) {
				// Get length of all the elements
				var totalLength = 0;
				if (jQuery(this).children('.publish2_story_headline').css('display') != 'none' && jQuery(this).children('.publish2_story_headline').html() != null) {
					totalLength = totalLength + jQuery(this).children('.publish2_story_headline').html().length;					
				}
				if (jQuery(this).children('.publish2_story_publication_name').css('display') != 'none' && jQuery(this).children('.publish2_story_publication_name').html() != null) {
					totalLength = totalLength + jQuery(this).children('.publish2_story_publication_name').html().length;
				}
				if (jQuery(this).children('.publish2_story_publication_date').css('display') != 'none' && jQuery(this).children('.publish2_story_publication_date').html() != null) {
					totalLength = totalLength + jQuery(this).children('.publish2_story_publication_date').html().length;
				}
				if (jQuery(this).children('.publish2_story_description').css('display') != 'none' && jQuery(this).children('.publish2_story_description').html() != null) {
					totalLength = totalLength + jQuery(this).children('.publish2_story_description').html().length;
				}
				// If the total length exceeds character limit, truncate the description
				if (totalLength > characterLimit) {
					var linkDescription = jQuery(this).children('.publish2_story_description').html();
					var newCharacterLimit = characterLimit - (totalLength - linkDescription.length);
					var start = newCharacterLimit + 1;
					var stop = newCharacterLimit + 2;
					var found_char = '';
					while (found_char != ' ') {
						start--;
						stop--;
						found_char = linkDescription.substring(start,stop);
					}
					linkDescription = linkDescription.substring(0, stop) + '...';
					jQuery(this).children('.publish2_story_description').html(linkDescription);
				}	
			}
			jQuery(this).show();
			if (i == newEndLinks && jQuery(this).children('.publish2_video_wrapper').size() != 0) {
				jQuery(this).hide();
				newEndLinks++;
			} else if (jQuery(this).children('.publish2_video_wrapper').size() != 0) {
				newEndLinks--;
			}
		} else {
			jQuery(this).hide();
		}
	});
}

function addLinkBehavior(iteration) {
	//jQuery('a').attr('target', '_blank'); // Commented out so it opens in the same window
	if (frameLinks == true) {
		publish2_link = jQuery('a.publish2_story_headline');
		publish2_link.bind("click", function(){
			link = jQuery(this).attr('href');
			link = escape(link);			
			ref = escape(referral);
			returnLink = escape(returnLink);
			window.top.location = frameURL + "?url=" + link + "&return=" + returnLink + "&ref=" + ref;
			return false;
		});
	}
	/* jQuery('a#adlogo').bind("click", function(){
		window.top.location = "http://about.publish2.com/mockups/ford/ford-newswire.html";
		return false;
	}); */ // Temporarily disabled
	if (iteration < 60) {
		iteration++;
		setTimeout(function() { addLinkBehavior(iteration); }, recurringTimeout);
	}
}

function showInitialLinks(linkNum, linkDivs, iteration) {
	var numDivs = linkDivs.length;
	for (var i = 0; i < numDivs; i++) {
		var numVideos = 0;
		var k = 0;
		// Go through the set of links to see if we're going to show a video
		jQuery('#'+linkDivs[i]+' .publish2_story').each(function(){
			if (k < (linkNum - 1) && jQuery(this).css('display') == 'none') {			
				if (jQuery(this).children('.publish2_video_wrapper').size() != 0) {
					numVideos++;
				}
			  k++;
			}
		});
		var j = numVideos;
		jQuery('#'+linkDivs[i]+' .publish2_story').each(function(){
			if (j < linkNum && jQuery(this).css('display') == 'none') {
				if (characterLimit != 0) {
					// Get length of all the elements
					var totalLength = 0;
					if (jQuery(this).children('.publish2_story_headline').css('display') != 'none' && jQuery(this).children('.publish2_story_headline').html() != null) {
						totalLength = totalLength + jQuery(this).children('.publish2_story_headline').html().length;					
					}
					if (jQuery(this).children('.publish2_story_publication_name').css('display') != 'none' && jQuery(this).children('.publish2_story_publication_name').html() != null) {
						totalLength = totalLength + jQuery(this).children('.publish2_story_publication_name').html().length;
					}
					if (jQuery(this).children('.publish2_story_publication_date').css('display') != 'none' && jQuery(this).children('.publish2_story_publication_date').html() != null) {
						totalLength = totalLength + jQuery(this).children('.publish2_story_publication_date').html().length;
					}
					if (jQuery(this).children('.publish2_story_description').css('display') != 'none' && jQuery(this).children('.publish2_story_description').html() != null) {
						totalLength = totalLength + jQuery(this).children('.publish2_story_description').html().length;
					}
					// If the total length exceeds character limit, truncate the description
					if (totalLength > characterLimit) {
						var linkDescription = jQuery(this).children('.publish2_story_description').html();
						var newCharacterLimit = characterLimit - (totalLength - linkDescription.length);
						var start = newCharacterLimit + 1;
						var stop = newCharacterLimit + 2;
						var found_char = '';
						while (found_char != ' ') {
							start--;
							stop--;
							found_char = linkDescription.substring(start,stop);
						}
						linkDescription = linkDescription.substring(0, stop) + '...';
						jQuery(this).children('.publish2_story_description').html(linkDescription);
					}
				}
				jQuery(this).show();
				j++;
			}
			if (jQuery(this).css('display') != 'none') {
				iteration = 100;
				jQuery('div#linksnav-nextbutton').show();
			}
		});
	}
	if (iteration < 60) {
		iteration++;
		setTimeout(function() { showInitialLinks(linkNum, linkDivs, iteration); }, recurringTimeout);
	}
}

function modifyProfileLink(iteration) {
	link_wrap = jQuery('.publish2_story');
	jQuery.each(link_wrap, function(){
		if (jQuery(this).children('.publish2_journalist_profile').html() != null || jQuery(this).children('.publish2_video_wrapper').children('.publish2_journalist_profile').html() != null) {
			if (jQuery(this).children('.publish2_video_wrapper').size() != 0) {
				var journProfileURL = jQuery(this).children('.publish2_video_wrapper').children('.publish2_journalist_profile').attr('href');
			} else {
				var journProfileURL = jQuery(this).children('.publish2_journalist_profile').attr('href');
			}
			journProfileURL = journProfileURL.replace(/http:\/\/demo.p2dev.net\/users\//, profileURL);
			var lastFive = journProfileURL.substring(journProfileURL.length - 5);
			if (lastFive != '.html') {
				journProfileURL += '.html';
			}
			if (jQuery(this).children('.publish2_video_wrapper').size() != 0) {
				jQuery(this).children('.publish2_video_wrapper').children('.publish2_journalist_profile').attr('href', journProfileURL);
				jQuery(this).children('.publish2_video_wrapper').children('.publish2_journalist_profile').attr("target", "_blank");
			} else {
				jQuery(this).children('.publish2_journalist_profile').attr('href', journProfileURL);
				jQuery(this).children('.publish2_journalist_profile').attr("target", "_blank");
			}
		}
	});
	if (iteration < 60) {
		iteration++;
		setTimeout(function() { modifyProfileLink(iteration); }, recurringTimeout);
	}
}

function addProfileImages(iteration) {
	link_wrap = jQuery('.publish2_story');
	jQuery.each(link_wrap, function(){
		if (jQuery(this).children('.publish2_journalist_profile').html() != null || jQuery(this).children('.publish2_video_wrapper').children('.publish2_journalist_profile').html() != null) {
			if (jQuery(this).children('.publish2_video_wrapper').size() != 0) {
				var journProfileImage = jQuery(this).children('.publish2_video_wrapper').children('.publish2_journalist_profile').attr('href');
			} else {
				var journProfileImage = jQuery(this).children('.publish2_journalist_profile').attr('href');
			}
			journProfileImage = journProfileImage.replace(/http:\/\/demo.p2dev.net\/users\//, profileURL);
			var lastFive = journProfileImage.substring(journProfileImage.length - 5);
			if (lastFive != '.jpg') {
				journProfileImage = journProfileImage.replace('profiles', 'images');
				if (lastFive == '.html') {
					journProfileImage = journProfileImage.replace('.html', '.jpg');
				} else {
					journProfileImage += '.jpg';
				}
			}
			
			journProfileImage = '<img src="'
								+ journProfileImage
								+ '" class="publish2_profile_image" />';	
														
			if (jQuery(this).children('.publish2_video_wrapper').children('.publish2_profile_image').size() == 0 && jQuery(this).children('.publish2_video_wrapper').size() != 0) {	
					jQuery(this).children('.publish2_video_wrapper').children('a.publish2_story_headline.publish2_link').wrap('<span class="publish2_story_headline_wrap" />');
					var moveTitle = jQuery(this).children('.publish2_video_wrapper').children('span.publish2_story_headline_wrap').html();
					jQuery(this).children('.publish2_video_wrapper').children('span.publish2_story_headline_wrap').remove();
					jQuery(this).children('.publish2_video_wrapper').children('.publish2_video').after(moveTitle);
			jQuery(this).children('.publish2_video_wrapper').children('.publish2_story_headline.publish2_link').before(journProfileImage);
			} else if (jQuery(this).children('.publish2_profile_image').size() == 0 && jQuery(this).children('.publish2_video_wrapper').size() == 0) {
				jQuery(this).prepend(journProfileImage);
			}
			
			
			if (jQuery(this).children('.publish2_video_wrapper').children('.publish2_profile_wrap').size() == 0) {
				jQuery(this).children('.publish2_video_wrapper').children('a.publish2_link.publish2_journalist_profile').wrap('<span class="publish2_journalist_profile_wrap" />');
				var newHTML = jQuery(this).children('.publish2_video_wrapper').children('span.publish2_journalist_profile_wrap').html();
				jQuery(this).children('.publish2_video_wrapper').children('span.publish2_journalist_profile_wrap').remove();
				newHTML += ' ' + jQuery(this).children('.publish2_video_wrapper').children('span.publish2_journalist_profile').html();
				jQuery(this).children('.publish2_video_wrapper').children('span.publish2_journalist_profile').remove();
				newHTML += ' ' + jQuery(this).children('.publish2_video_wrapper').children('span.publish2_story_description').html();
				jQuery(this).children('.publish2_video_wrapper').children('span.publish2_story_description').remove();
				newHTML = '<p class="publish2_profile_wrap">' + newHTML + '</p>';
				jQuery(this).children('.publish2_video_wrapper').append(newHTML);
				//jQuery(this).children('.publish2_video_wrapper').children('.publish2_link.publish2_journalist_profile').after('</p>');
				jQuery('.publish2_profile_wrap').show();
			}
			jQuery('.publish2_profile_image').show();
		}
	});
	if (iteration < 60) {
		iteration++;
		setTimeout(function() { addProfileImages(iteration); }, recurringTimeout);
	}
}

function showShareButtons(iteration) {
	link_wrap = jQuery('.publish2_story');
	jQuery.each(link_wrap, function(){
		if (jQuery(this).children('.publish2_share').size() == 0 && jQuery(this).children('.publish2_tweet').size() == 0 && jQuery(this).children('.publish2_video_wrapper').size() == 0) {
			var readLink = jQuery(this).children('.publish2_story_headline').attr('href');
			var readTitle = jQuery(this).children('.publish2_story_headline').html();
			var readPublication = jQuery(this).children('.publish2_story_publication_name').html();
			var readDescription = jQuery(this).children('.publish2_story_description').html();
			var encodedLink = escape(readLink);			
			var encodedTitle = escape(readTitle);
			var encodedPublication = escape(readPublication);
			var encodedDescription = escape(readDescription);
			var readDiv = '<div class="publish2_read"><a class="publish2_link" href="' + readLink + '">Read the full article &raquo;</a></div>'
			var shareDiv = '<div class="publish2_share">Share on:'
										+ '<a class="external_link" target="_blank" href="http://twitter.com/?status=' 
										+ encodedTitle + '+' 
										+ encodedLink +'">'
										+	'<img src="images/twitter.png" width="16px" height="16px" class="publish2_share_twitter"/></a>'
										+ '<a class="external_link" target="_blank" href="http://www.facebook.com/sharer.php?u=' 
										+ encodedLink + '&t=' 
										+ encodedTitle + '">'
										+	'<img src="images/facebook.png" width="16px" height="16px" class="publish2_share_facebook"/></a>'
										+ '<a class="external_link" target="_blank" href="http://www.linkedin.com/shareArticle?mini=true&url=' 
										+ encodedLink + '&title=' 
										+ encodedTitle + '&summary=' 
										+ encodedDescription + '&source=' 
										+ encodedPublication + '">'
										+	'<img src="images/linkedin.png" width="16px" height="16px" class="publish2_share_linkedin"/></a>'
										+ '</div>';
			//jQuery(this).append('<br />'+shareDiv+readDiv);
			jQuery(this).append('<br />'+shareDiv);
		} else if (jQuery(this).children('.publish2_share').size() == 0 && jQuery(this).children('.publish2_tweet').size() != 0) {
			var tweet = jQuery(this).children('.publish2_tweet').text();			
			var encodedTweet = escape(tweet);
			var readDiv = '<div class="publish2_read"></div>'
			var shareDiv = '<div class="publish2_share">Retweet on:'
										+ '<a class="external_link" target="_blank" href="http://twitter.com/?status=RT+%40' 
										+ encodedTweet + '">'
										+	'<img src="images/twitter.png" width="16px" height="16px" class="publish2_share_twitter"/></a>'
										+ '</div>';
			//jQuery(this).append(shareDiv+readDiv);
			jQuery(this).append(shareDiv);
		} else if (jQuery(this).children('.publish2_share').size() == 0 && jQuery(this).children('.publish2_video_wrapper').size() != 0) {
			var readLink = jQuery(this).children('.publish2_video_wrapper').children('.publish2_story_headline').attr('href');
			var readTitle = jQuery(this).children('.publish2_video_wrapper').children('.publish2_story_headline').html();
			var readPublication = jQuery(this).children('.publish2_video_wrapper').children('.publish2_story_publication_name').html();
			var readDescription = jQuery(this).children('.publish2_video_wrapper').children('.publish2_story_description').html();	
			var encodedTitle = escape(readTitle);
			var encodedLink = escape(readLink);
			var encodedPublication = escape(readPublication);
			var encodedDescription = escape(readDescription);
			var readDiv = '<div class="publish2_read"></div>'
			var shareDiv = '<div class="publish2_share">Share on:'
										+ '<a class="external_link" target="_blank" href="http://twitter.com/?status=' 
										+ encodedTitle + '+' 
										+ encodedLink +'">'
										+	'<img src="images/twitter.png" width="16px" height="16px" class="publish2_share_twitter"/></a>'
										+ '<a class="external_link" target="_blank" href="http://www.facebook.com/sharer.php?u=' 
										+ encodedLink + '&t=' 
										+ encodedTitle + '">'
										+	'<img src="images/facebook.png" width="16px" height="16px" class="publish2_share_facebook"/></a>'
										+ '<a class="external_link" target="_blank" href="http://www.linkedin.com/shareArticle?mini=true&url=' 
										+ encodedLink + '&title=' 
										+ encodedTitle + '&summary='
										+ encodedDescription + '&source=' 
										+ encodedPublication + '">'
										+	'<img src="images/linkedin.png" width="16px" height="16px" class="publish2_share_linkedin"/></a>'
										+ '</div>';
			//jQuery(this).append(shareDiv+readDiv);
			jQuery(this).append(shareDiv);
		}
	});
	
	/* external_link = jQuery('a.external_link');
	external_link.bind("click", function(){
		link = jQuery(this).attr('href');
		window.top.location = link;
		return false;
	}); */ // temporarily disabled
	
	if (iteration < 60) {
		iteration++;
		setTimeout(function() { showShareButtons(iteration); }, recurringTimeout);
	}
}
