/* mr_advocacy_donation_share_icons_js.css?type=.js
 * Example advo form: "Action: GS AX 1/12/2017 Franken Resolution thanks" https://secure.ucsusa.org/onlineactions/vLWAnTs4PkOi-BVBs61TOw2
 * Example pledge form: https://secure.ucsusa.org/onlineactions/Zvy4LqZe30-dwB6mUtMLcQ2
 * Evergreen donation form: "ucsusa.org new action landing page with social" https://secure.ucsusa.org/onlineactions/vphwHCv9-kO99nsLY0BdtQ2
 */

/*
 * Draws the share icons on the page
 */
function mrDrawShareIcons(share)
{
	if ($(".mrsharetableouter").length > 0)
	{
		return;  // Don't draw more than 1!
	}
	
	if ($("#fb-root").length == 0)
	{
		// Add Facebook div:
		$("body").append('<div id="fb-root"></div>');
		
		// Run Facebook setup script:
		(function(d, s, id)
		{
			var js, fjs = d.getElementsByTagName(s)[0];
			if (d.getElementById(id)) return;
			js = d.createElement(s); js.id = id;
			js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
			fjs.parentNode.insertBefore(js, fjs);
		}(document, 'script', 'facebook-jssdk'));
	}
	
	// Draw the share table:
	var shareTable = '\
	<table style="border: 0; width: 80px; margin: 0px 10px 25px 0px; float: left;" class="mrsharetableouter">\
		<tbody style="border: 0;">\
			<tr>\
				<td class="mrsharetable" style="border: 0; width: 60px;">\
					<strong style="display: block; padding-bottom: 18px;">Share this action:</strong>\
					<div class="mrfblikebutton">\
						<div class="fb-share-button" data-href="' + share.url + '" data-layout="box_count"></div>\
					</div>\
					<br>\
					<a class="twitter_share_link" href="' + share.tweet_encoded + '" target="_blank"><img src="https://nvlupin.blob.core.windows.net/images/van/UCS/UCS/1/58097/images/donation-advocacy-tweet-icon-2x.png" width="67" border="0" alt="Tweet" style="display: block; margin-top: -5px; outline: none; height: auto;"></a>\
					<br>\
					<a class="email_share_link" href="' + share.email_encoded + '"><img src="https://nvlupin.blob.core.windows.net/images/van/UCS/UCS/1/58097/images/donation-advocacy-email-icon-2x.png" width="67" border="0" alt="Email" style="display: block; margin-top: 1px; outline: none; height: auto;"></a>\
				</td>\
			</tr>\
		</tbody>\
	</table>';
	
	$(".facebook_share_link").attr('href', 'https://www.facebook.com/sharer/sharer.php?u=' + share.url);
	$(".twitter_share_link").attr('href', share.tweet_encoded);
	$(".email_share_link").attr('href', share.email_encoded);
	
	$("header.at-markup:first").prepend(shareTable);
	
	// And now that everything is in place, re-run FB library:
	try
	{
		FB.XFBML.parse();
	}
	catch(e)
	{
		window.setTimeout(function()
		{
			FB.XFBML.parse();
		}, 4000);
	}
	
	$(".mrfblikebutton, .mrfblikebutton .fb-share-button>span, .mrfblikebutton iframe").css("width", "60px").css("min-height", "40px");
}

/*
 * Function to remove any content after and including the ?
 */
function mrStripSearch(url)
{
	return url.replace(/(\?.*)/g, "");
}

/*
 * Setup when page finishes loading (or onContentReady for non-IE)
 */
function mrSetupShare()
{
	// For Twitter, use the Facebook share title (plus the alert URL) as the Tweet text. 
	// For Email, use the Facebook share title as the email subject, and the Facebook share description (plus the alert URL) as the email body. 
	var share = {
		url: mrStripSearch(document.location.href) + "?ms=facebook",
		tweet_encoded: "https://twitter.com/intent/tweet?text=Join%20me%20in%20taking%20action%20with%20%40ucsusa%20on%20global%20warming%2C%20our%20broken%20food%20system%2C%20and%20more%3A%20http%3A%2F%2Fwww.ucsusa.org%2Faction-center%3Fms%3Dtwitter",
		email_encoded: "mailto:?subject=Ready%20to%20stand%20up%20for%20science%3F&body=I%20just%20took%20action%20with%20the%20Union%20of%20Concerned%20Scientists%20to%20make%20sure%20science%E2%80%94not%20political%20calculations%20or%20corporate%20hype%E2%80%94guides%20public%20policy%20on%20the%20critical%20challenges%20we%20face%2C%20from%20global%20warming%20to%20our%20broken%20food%20system%2C%20and%20more.%20I%20thought%20you%27d%20be%20interested%20in%20checking%20out%20their%20current%20campaigns.%20Visit%20their%20Action%20Center%20to%20see%20where%20you%20can%20make%20a%20difference%20today%3A%20http%3A%2F%2Fwww.ucsusa.org%2Faction-center%3Fms%3DTAF"
	};
	
	// Test to see if we're on an advocacy page
	if ($('input[name="SelectAmount"]').length == 0 && $('input[name="OtherAmount"]').length == 0)
	{
		// Since we're on an advo page, compute our share text, from the header tags on the page:
		share.url = mrStripSearch($('meta[property="og:url"]').attr("content")) + "?ms=facebook";
		share.tweet_encoded = "http://twitter.com/intent/tweet?text=" + encodeURIComponent($('meta[property="og:title"]').attr("content")) + " " + encodeURIComponent(mrStripSearch(share.url) + "?ms=twitter");
		share.email_encoded = "mailto:?subject=" + encodeURIComponent($('meta[property="og:title"]').attr("content")) + "&body=" + encodeURIComponent($('meta[property="og:description"]').attr("content")) + "%0D%0A%0D%0A" + encodeURIComponent(mrStripSearch(share.url) + "?ms=TAF");
		
		// And now store our share text in a cookie:
		mr.Cookie.Set("ucssharecontent", escape(encodeURIComponent(share.url + "***" + share.tweet_encoded + "***" + share.email_encoded)), 31, 'd');
		
		// Hook into the form processing:
		$('form[action="Forms"] input[type="submit"]').click(function()
		{
			var valid = true;
			
			$("input:required, select:required, textarea:required").each(function()
			{
				if ($(this).val() == "")
				{
					valid = false;
				}
				else if ($(this).attr("name") == "EmailAddress" && !mr.Test.ValidEmail($(this).val()))
				{
					valid = false;
				}
			});
			
			if (valid)
			{
				// See if Facebook share popup on submit is enabled
				if (window.facebook_share_popup && (window.facebook_share_popup == "on" || window.facebook_share_popup == "true"))
				{
					// If so, show it on valid submit
					
					var y = Math.round(window.top.outerHeight / 2 + window.top.screenY - (580 / 2));
					var x = Math.round(window.top.outerWidth / 2 + window.top.screenX - (560 / 2));
					
					window.open("https://www.facebook.com/sharer/sharer.php?u=" + encodeURIComponent($('meta[property="og:url"]').attr("content")), '_blank', 'menubar=no,location=yes,resizable=yes,scrollbars=no,status=no,width=560,height=580,top=' + y + ',left=' + x);
				}
			}
		});
		
		console.log("Share code setup on advocacy page");
	}
	else
	{
		// Else, we're on the evergreen donation form, so try reading in from cookie:
		var cookieContent = decodeURIComponent(mr.Cookie.Get("ucssharecontent"));
		
		cookieContent = cookieContent.split("***");
		
		// If it's not found, then it will just use the default sharing content
		if (cookieContent.length == 3)
		{
			share.url = cookieContent[0];
			share.tweet_encoded = cookieContent[1];
			share.email_encoded = cookieContent[2];
		}
		
		console.log("Share code setup on evergreen donation page");
	}
	
	// Either way, now place the icons on the page:
	mrDrawShareIcons(share);
}

// Load mr_fx:
$.getScript("https://nvlupin.blob.core.windows.net/images/van/UCS/UCS/1/58097/images/scripts/mr_fx_js.css?type=.js", function(data, textStatus, jqxhr)
{
	// Setup shares:
	$(document).ready(mrSetupShare);
});
