/**
 * @author Tyler Gaw <tylerg@arc90.com>
 *		   Alex Gutierrez <alexg@arc90.com>
 *         
 * Javascript document for Notes - both the note view page, and notes on other pages
 *
 */

GradeGuru.note = {
	
	// Storage for the note id
	id: null,
	
	init: function ()
	{
		this.id = $('#note-id').val();
		this.rating.init();
		this.controlBar.init();
		this.feedback.init();
		
		if ($('#note-url').length !== 0)
		{
			this.socialSharing.noteURL = $('#note-url').val();
		}
		
		this.socialSharing.init();
	},
	
	// The current note rating and the behavior for allowing a user to rate
	rating: {
		init: function ()
		{
			// The average rating should be set in the HTML, when the page is served
			//
			var $this = this,
				noteAverageRating = $('#rating-select :selected').val();
			
			$('#rating-select').selectToRating({
				defaultRating: noteAverageRating,
				itemClick: $this.rateNote
			});
		},
		
		// When the user selects a rating we need to first check that
		// they are logged in and able to rate. If they are send the
		// rating info to the server.
		// As with other POST requests we'll send:
		// - User Id
		// - User Token
		// - and the note Id
		//
		rateNote: function (e)
		{
			var $this = GradeGuru.note,
				selectedRating = $(this).attr('href').split('#')[1],
				postData = {};
			
			// First we'll check to make sure the user is logged in
			if (!GradeGuru.core.user.isLoggedIn())
			{
				GradeGuru.registration.callLogin();
			}
			else
			{				
				// Build the data to send
				postData = GradeGuru.core.user.getData();
				postData.note = $this.id;
				
				// Make a call to the server with the selected rating
				$.ajax(
					{
						type: 'POST',
						dataType: 'json',
						url: '../api/notes/01.json',
						data: postData,
						success: function (data)
						{
							// We're going to need to check the response data for a
							// Failure message if the user id and token is not in sync
							//
							// TODO: FAIL IF ID AND TOKEN ARE OUT OF SYNC
							
							
							// I'm doing the averaging math here, but it will need
							// to be done on the server and just given back to us here
							// as a response
							//
							/*
							var rating = data.note.details.rating,
								newRating = (rating.totalScore + selectedRating) / (rating.numberOfRatings + 1),
								newAverage = Math.round(newRating * 10) / 10;
							*/

							// Call the update rating display of the rating list - it's broken in the plugin
							//e.data.elem.trigger('selectToRating.setRating', newAverage);

							// Display thank you
							GradeGuru.core.utils.alertBanner('<strong>Thanks!</strong> Your rating has been counted. <a href="#feedback">Don\'t forget to leave feedback below.</a>', 'confirmation');
						}
					}
				);
			}
			
			return false;
		}
	},
	
	// Note control bar
	controlBar: {
		
		init: function ()
		{
			this.popUps.init();
			this.save.init();
		},
		
		// Allow a user to save a note to their folder
		//
		// TODO: Set up a general 'action' method that you can pass an arg
		//       of 'save' or 'remove' instead of separate methods
		//
		save: {
			init: function ()
			{
				var $this = GradeGuru.note.controlBar.save;
				
				$('#control-save').click(
					function ()
					{
						if (!$(this).hasClass('user-saved'))
						{
							$this.add();
						}
						else
						{
							$this.remove();
						}
						return false;
					}
				);
			},
			
			// To save a note to a user's folder
			// Make an ajax request with:
			// - The note ID
			// - The user ID
			// - The user token
			add: function ()
			{
				var $this = GradeGuru.note.controlBar,
					postData;
				
				if (!GradeGuru.core.user.isLoggedIn())
				{
					GradeGuru.registration.callLogin();
				}
				else
				{
					// Build the data to send
					postData = GradeGuru.core.user.getData();
					postData.note = $this.id;

					// Make a call to the server with the selected rating
					$.ajax(
						{
							type: 'POST',
							url: '../api/users/01/saved.js',
							data: postData,
							success: function (data)
							{
								
								// We're going to need to check the response data for a
								// Failure message if the user id and token is not in sync
								//
								// TODO: FAIL IF ID AND TOKEN ARE OUT OF SYNC
								
								$this.save.confirm();
							}
						}
					);
				}				
			},
			
			remove: function ()
			{
				$('#control-save').removeClass('user-saved').find('a').text('Save in your folder');
				GradeGuru.core.utils.alertBanner('<strong>' + $('#note-title').val() + '</strong> has been removed from your folder', 'confirmation');
			},
			
			confirm: function ()
			{
				$('#control-save').addClass('user-saved').find('a').text('Saved in your folder');
				GradeGuru.core.utils.alertBanner('<strong>' + $('#note-title').val() + '</strong> has been saved in your folder. <a href="#feedback">Don\'t forget to leave feedback below.</a>', 'confirmation');
			}
		},
		
		// Share and cite have balloon type pop ups to allow the user to
		// do a number of things
		popUps: {
			init: function ()
			{
				// Click outside bubbles to close
				$('body').click(function () 
				{
					$('.bubble').hide();
					$('#note-control-bar li').removeClass('active');
				});
				
				// Click to show bubble
				$('.show-menu').click(function (event) {
					var activeWindow = $(this).attr('href');

					$('#note-control-bar li').removeClass('active');

					$('.bubble').not($(activeWindow)).hide();

					if ($(activeWindow).is(':visible')) 
					{
						$(activeWindow).fadeOut(250);

					} 
					else 
					{
						$(activeWindow).fadeIn(250);
						$(this).parent().addClass('active');
					}

					return false;
				});
			}
		}
	},
	
	// Note feedback thread
	feedback: {
		init: function ()
		{
			// Feedback form
		    $("#leave-feedback-form").submit(
				function () 
				{
					if ($("#leave-feedback-form textarea").val() === "") 
					{
						$('#leave-feedback').addClass('error').focus(
							function () 
							{
								$(this).removeClass('error');
							}
						);
					} 
					else 
					{
						/*
						Static added comment
						NOTE: The logged-in user has a class of "note-owner-feedback" for differentiation 
						*/
						
						var textareaText = $("textarea#leave-feedback").val();
						$(this).parent().parent().before('<div class="feedback-cell"><div class="user-avatar"><span></span> <img alt="" src="../images/temp/temp_avatar_mid.jpg" width="41" height="41" /> </div><div class="feedback-content note-owner-feedback"><div class="feedback-content-inner"> <h5><a href=" ">Jeff Daniels</a> <em>Today at 4:10pm</em></h5> <p>' + textareaText + '</p> </div></div></div>');
					}
					
					return false;
				}
			);
		}
	},
	
	// Note sharing on social networks and email
	socialSharing: {
		
		// If we are on an individual note page,
		// we can set the note url here, instead of searching
		// for it after we click a share link
		noteURL: null,
				
		// Bind click events to elements that will call the share functions
		init: function ()
		{
			var $this = this;
			
			// TODO: fix this so we don't have to repeat the same code over and over
			$('.note-share-facebook').live('click', 
				function ()
				{
					var url;
					
					if ($this.noteURL === null)
					{
						url = $(this).parent().find('input').val();
					}
					else
					{
						url = $this.noteURL;
					}
					
					$this.facebook(url);
				}
			);
			
			$('.note-share-twitter').live('click', 
				function ()
				{
					var url;
					
					if ($this.noteURL === null)
					{
						url = $(this).parent().find('input').val();
					}
					else
					{
						url = $this.noteURL;
					}
					
					$this.twitter(url);
				}
			);
			
			$('.note-share-email').live('click',
				function ()
				{
					var url;
					
					if ($this.noteURL === null)
					{
						url = $(this).parent().find('input').val();
					}
					else
					{
						url = $this.noteURL;
					}
					
					$this.email.call(url);
				}
			);
		},
		
		// Update the user's Twitter status with a link to their note
		twitter: function (noteURL)
		{
			var url  = 'http://twitter.com/home?status=' + encodeURIComponent('Check out my awesome blossom notes on GradeGuru! ' + noteURL);
			this.newShareWindow(url);
		},
		
		// Post an item to the user's facebook wall with a link to their note
		facebook: function (noteURL)
		{
			var url = 'http://www.facebook.com/sharer.php?u=' + encodeURIComponent(noteURL);
			this.newShareWindow(url);
		},
		
		// Open a modal window with a pre-filled form to send a link to their note
		email: {
			
			noteURL: null,
			
			// Store the note URL and open the colorbox modal
			call: function (url)
			{
				var $this = this;
				this.noteURL = url;
				
				$.fn.colorbox({
					// @configure - Might need to change this path
					href: '../partials/shareNoteForm.html',
					onComplete: $this.onComplete
				});
			},
			
			// Call after the colorbox modal has finished opening
			onComplete: function ()
			{
				var $this = GradeGuru.note.socialSharing.email;
				
				$('#share-message').val("Have a look at my note on GradeGuru: " + $this.noteURL);
				$('#share-to, #share-message').click(
					function ()
					{
						$(this).removeClass('error');
					}
				);
				
				$('#share-note-form').submit($this.submit);
				
				// Wait a sec for the input to exist, then focus
				setTimeout(
					function ()
					{
						$("#share-note-form input[type='text']:first").focus();
					}, 
				300);
			},
			
			// Handle the form submission
			submit: function ()
			{
				var $this = GradeGuru.note.socialSharing.email;
				
				if ($this.formIsValid())
				{
					$.ajax(
						{
							// @configure - Share note email URL
							url: '../api/index.html',
							
							// @configure - Might need to edit/add params to the query string
							data: 'to=' + $('#share-to').val() + '&message=' + $('#share-message').val(),
							
							type: 'POST',
							success: function ()
							{
								$('#share-note-form p.form-status').addClass('confirm')
									.text("Thanks! Your message has been sent.");

								$('#share-note-form p:has(input), #share-note-form p:has(textarea)').remove();
								$.fn.colorbox.resize();
							},
							error: function ()
							{
								alert('Sorry, we\'re having trouble sending your message, please try again');
							}
							
						}
					);
				}
				
				return false;
			},
			
			// Check that all required fields are entered and valid
			formIsValid: function ()
			{
				var isValid = true,
					to = $('#share-to'),
					emails = null;
				
				// If email is empty
				if (to.val() === '')
				{
					to.addClass('error');
					isValid = false;
				}
				
				// If multiple emails entered
				else if (to.val().indexOf(',') !== -1)
				{
					emails = to.val().replace(' ', '').split(',');
					$.each(emails, function (i, email)
					{
						
						if (!GradeGuru.core.utils.emailIsValid(email.trim()))
						{
							to.addClass('error');
							isValid = false;
							return false;
						}
						
					});
				}
				
				// If single email
				else
				{
					isValid = GradeGuru.core.utils.emailIsValid(to.val());
				}
				
				if ($('#share-message').val() === '')
				{
					$('#share-message').addClass('error');
					isValid = false;
				}
				
				return isValid;
			}
		},
		
		// Open a new window with of the sharing URL
		// @param STRING url
		// @param INT width - optional
		// @param INT height - optional
		newShareWindow: function (url, width, height)
		{
			var w = 795 || width,
				h = 435 || height;
			window.open(url, 'sharer', 'toolbar=0, status=0, width=' + w + ', height=' + h + '');
			return false;
		}
	}
};

$(document).ready(function () {
	GradeGuru.note.init();
});