$(function(){
	/* This code is run on page load */

	/* Showing the wishes, hidden by the CSS. */
	$('#main').show();

	/* Listening for the submit event on the form */
	$('#wForm').submit(function(e){
		 addWish();
		 e.preventDefault();
	});
	
	function init(){
		/* Run on page load if the user is logged into facebook */
		$('#share .toggleContent').toggle();
		
		$('#addWish .name').html('Hi, <fb:name uid="loggedinuser" useyou="false" firstnameonly="true"></fb:name>, add your wish below:').show();
		$('#addWish .profile-pic').children().attr('uid',FB.Connect.get_loggedInUser());
		
		FB.XFBML.Host.parseDomTree();
	}
	
	/* Initializing facebook connect */
	FB.init("bcf260ae02d453654be01ec11e2d0aa0","xd_receiver.htm",{"ifUserConnected" : init});
	
	
	var commencing = false;
	
	function addWish()
	{
		/* If there is another AJAX process already active stop the function: */
		if(commencing) return false;
		
		/* Stripping HTML tags */
		var wish = $('#wish').val().replace(/<[^>]*>/g,'');
		
		if(wish.length<3) { alert('Your wish is too short or empty!'); return false; }
		
		if(!FB.Connect.get_loggedInUser()) { alert('You are not logged in!'); return false; }
		
		commencing=true;
		
		/* Sending the data to post.php */
		$.post('ajax/post.php',{uid:FB.Connect.get_loggedInUser(),wish:wish,key:$('#key').val()},function(msg){
		
			/* This function is run if the data was successfully sent */
			
			commencing=false;
		
			if(msg.status)
			{
				/* If there were no errors */
				if($('#cb').attr('checked'))
				{
					var attachment = {
						name:'Christmas Wishes',
						href:'http://christmas-wishes.tutorialzine.com/',
						description:'What do you wish for this christmas?'
					};
					
					var action_link='';
				
					setTimeout(function(){
						FB.Connect.streamPublish(wish, attachment, action_link);
					},1000);
				}
				
				try{
					/* Insert a new wish by duplicating and changing the first wish currently on the page */
					
					var el = $('#wishesContainer .wish').eq(0).clone()
					
					if(el.hasClass('green'))
					{
						el.addClass('red').removeClass('green');
					}
					else el.addClass('green').removeClass('red');
					
					el.find('.body').html(wish);
					el.hide().html(el.html().replace(/uid=\"\d+\"/g,'uid="'+FB.Connect.get_loggedInUser()+'"'));
					
					$('#wishesContainer').prepend(el);
					
					/* Parsing the fb tags: */
					FB.XFBML.Host.parseDomElement(el.get(0));
					el.fadeIn('slow');
					
					/* Scrolling the page to show the newly added wish into view: */
					$.scrollTo(el,800);
				}
				catch(e){location.reload();}
				
				$('#share').html('Thank you!');
			}
			else
			{
				alert('There was an error trying to add your comment!\nPlease try again in a few moments.');
				return false;
			}
		
		},'json')
	}

});
