var slPluginId = 'silverlightMap';
var appId = '199006310116343';
var petitionForm = false;
var thankyouPage = false;
var loggedIn = false;
var loginLogoutButtonElement = '#bFacebookConnect';
var streamPublishShown = false;


function getSilverlightFacebookService() {
	if (typeof (window.slPlugin) == "undefined" || window.slPlugin == null) {
		window.slPlugin = document.getElementById(slPluginId);
	}
	return window.slPlugin.Content.facebookService;
}


function fbLoginButton()
{
	if (loggedIn)
	{
		FB.logout( handleFbResponseNormal );
		//console.log('Logging Out');
	} else {
		FB.login( handleFbResponseNormal, {perms:'email,user_location'} );
		//console.log('Logging In');
	}
}


function showLogOut()
{
	$( loginLogoutButtonElement ).css('background-image', 'url(\'http://www.jamieoliver.com/foundation/jamies-food-revolution/imgs/btn_logout.gif\')');
}


function showLogIn()
{
	$( loginLogoutButtonElement ).css('background-image', 'url(\'http://www.jamieoliver.com/foundation/jamies-food-revolution/imgs/b_facebook_connect.gif\')');
}


function handleFbResponseNormal(response) {
	// These are for the map..
	if (response.session) {
		loggedIn = true;
		showLogOut();
	} else {
		loggedIn = false;
		showLogIn();		
	}
	fbLoaded();
}


function handleFbResponse(response) {
	// These are for the map..
	if (response.session) {
		loggedIn = true;
		showLogOut();
		
		getSilverlightFacebookService().RegisterFacebookSession(
			response.session.uid,
			response.session.access_token,
			response.session.expires,
			response.session.secret,
			response.session.sig,
			response.session.session_key
		);
	} else {
		loggedIn = false;
		showLogIn();
		
		getSilverlightFacebookService().UnregisterFacebookSession();
	}
	fbLoaded();
}


function facebookLogin() {
	// These are for the map..
	FB.login( handleFbResponse, {perms:'email,user_location'} );
}


function facebookLogout() {
	// These are for the map..
	FB.logout(function (response) {
		getSilverlightFacebookService().UnregisterFacebookSession();
	});
}


function checkAuthentication() {
	// These are for the map..
	FB.getLoginStatus(handleFbResponse, true);
}

function checkAuthenticationNormal() {
	// These are for the map..
	FB.getLoginStatus(handleFbResponseNormal, true);
}


function fbLoaded(check_auth)
{
	if (check_auth)
	{
		checkAuthenticationNormal();
	}
	
	if (petitionForm)
	{
		prefillPetitionForm();
	}

	if (thankyouPage && (streamPublishShown == false))
	{
		publishPlea();
		streamPublishShown = true;
	}
}


function prefillPetitionForm()
{
	FB.api('/me', function(response)
	{
		if (! response.error)
		{
			var fname = document.getElementById('petition_first_name');
			var lname = document.getElementById('petition_last_name');
			var email = document.getElementById('petition_email');
			var uid = document.getElementById('fb_uid');
			var location = document.getElementById('fb_location');

			//console.log(fname.value);


			if (fname.value == '' || fname.value == 'FIRST NAME')
			{
				fname.value = response.first_name
			}

			if (lname.value == '' || lname.value == 'LAST NAME')
			{
				lname.value = response.last_name
			}

			if (email.value == '' || email.value == 'EMAIL ADDRESS')
			{
				email.value = response.email
			}

			if (uid.value == '')
			{
				uid.value = response.id
			}

			if (location.value == '')
			{
				location.value = response.location.name
			}

		}
	});
}


function publishPlea()
{
	FB.ui(
		{
			method: 'stream.publish',
			message: 'I signed the Food Revolution Petition! Do your part...Visit http://www.jamiesfoodrevolution.com',
			attachment: {
				name: 'Jamie Oliver\'s Food Revolution',
				caption: 'www.jamiesfoodrevolution.com',
				description: 'The Food Revolution is about saving America\'s health by changing the way people eat. Join us and sign the petition!',
				href: 'http://www.jamieoliver.com/foundation/jamies-food-revolution/',
				media: [{
					"type": "flash",
					"swfsrc": "http://jamieoliver.com/facebook_stream_player/stream_player.swf?v=3", 
					"imgsrc": "http://jamieoliver.com/facebook_stream_player/thumbnail.jpg", 
					"width": "90", 
					"height": "90",
					"expanded_width": "397", 
					"expanded_height": "340"
				}
				]
			},
			user_message_prompt: 'Help spread the word...'
		},

		function(response) {
			if (response && response.post_id)
			{
				//alert('Post was published.');
				//console.log('Post sent...');
			} else {
				//alert('Post was not published.');
				//console.log('Post published...');
			}
		}
	);				

}

function share()
{
		
		FB.ui(
			{
		     method: 'feed',
			 name: 'Jamie Oliver\'s Food Revolution | Best and Worst School Lunches',
			 link: 'www.jamiesfoodrevolution.com/bestworstlunch',
		     picture: 'http://www.jamieoliver.com/foundation/jamies-food-revolution/imgs/photowall.jpg',
			 caption: 'www.jamiesfoodrevolution.com/bestworstlunch',
			 description: 'What\'s for lunch in school cafeterias across around the world? It might be tasty meals made with fresh ingredients, or processed, unappealing junk. Check out lunches from all over the globe and help the Food Revolution find the Best and Worst Lunches in the world.',		     
			 message: ''
		   },

		function(response) {
			if (response && response.post_id)
			{
				//alert('Post was published.');
				//console.log('Post sent...');
			} else {
				//alert('Post was not published.');
				//console.log('Post published...');
			}
		}
	);
}

function USDA()
{
	FB.ui(
		{
			method: 'stream.publish',
			message: "Now's the time to speak up for better school lunch! Join the Food Revolution in submitting a comment to the USDA to make sure we get more fresh food in schools.",
			attachment: {
				name: 'Jamie Oliver\'s Food Revolution',
				caption: 'www.jamiesfoodrevolution.com',
				description: 'The Food Revolution is about saving America\'s health by changing the way people eat. Join us and sign the petition!',
				href: 'http://www.jamieoliver.com/foundation/jamies-food-revolution/',
				media: [{
					"type": "flash",
					"swfsrc": "http://jamieoliver.com/facebook_stream_player/stream_player.swf?v=3", 
					"imgsrc": "http://jamieoliver.com/facebook_stream_player/thumbnail.jpg", 
					"width": "90", 
					"height": "90",
					"expanded_width": "397", 
					"expanded_height": "340"
				}
				]
			},
			user_message_prompt: 'Help spread the word...'
		},

		function(response) {
			if (response && response.post_id)
			{
				//alert('Post was published.');
				//console.log('Post sent...');
			} else {
				//alert('Post was not published.');
				//console.log('Post published...');
			}
		}
	);
}


function sugaryMilk()
{
	FB.ui(
		{
			method: 'stream.publish',
			message: "Too much sugar is threatening the health of our kids and we've got to do something about it. Sugar is a major contributor to health problems like diabetes and hypertension, and kids are getting loads of extra sugar from drinking sweetened chocolate and strawberry milk at school.  Sign on with Jamie Oliver and the Food Revolution to ask schools to switch back to plain, wholesome milk, and make sugary flavored milk an occasional treat. www.jamiesfoodrevolution.com/SugaryMilk",
			attachment: {
				name: 'Jamie Oliver\'s Food Revolution',
				caption: 'www.jamiesfoodrevolution.com',
				description: 'The Food Revolution is about saving America\'s health by changing the way people eat. Join us and sign the petition!',
				href: 'www.jamiesfodrevolution.com/sugarymilk/',
				media: [{
					"type": "flash",
					"swfsrc": "http://jamieoliver.com/facebook_stream_player/stream_player.swf?v=3", 
					"imgsrc": "http://jamieoliver.com/facebook_stream_player/thumbnail.jpg", 
					"width": "90", 
					"height": "90",
					"expanded_width": "397", 
					"expanded_height": "340"
				}
				]
			},
			user_message_prompt: 'Help spread the word...'
		},

		function(response) {
			if (response && response.post_id)
			{
				//alert('Post was published.');
				//console.log('Post sent...');
			} else {
				//alert('Post was not published.');
				//console.log('Post published...');
			}
		}
	);
}

function clearIfDefault(inputEl, defaultText)
{
	if (inputEl.value == defaultText)
	{
		inputEl.value = '';
	}
}
