var GradeGuru = {};

GradeGuru.tools = {
	
	// Form URLs for Ajax requests
	//
	urls: {
		
		// data that is sent as a query string appended to this URL:
		//     name=thename&email=theemail&message=themessage
		//
		suggestURL: 'suggestionNotification',
		
		// data that is sent as a query string appended to this URL:
		//     address=address
		//
		updatesURL: 'citationManagerMarketingNotification'
	},
	
	// We have a couple of modificications for IE styling
	//
	isIE: false,
	
	init: function ()
	{
		var $this = GradeGuru.tools;
		this.isIE = $.browser.msie;
		
		// Initialize the forms
		//
		$this.suggestForm.init();
		$this.updatesForm.init();
		
		// Hide the "drag to install" text if this is IE
		// Also, give a little hint in the install instructions.
		//
		if ($this.isIE)
		{
			$('p.tool-deliverable strong').hide();
			$('dt.install-ie, .install-ie + dd').css({'background-color': '#FFFED6'});

			// Give IE6 a special class for styling
			// I didn't use a conditional comment and IE6 stylesheet because I 
			// only have one thing that's different
			if ($.browser.version.substr(0, 3) === '6.0')
			{
				$('body').addClass('ie-six');
			}
		}
		
		// Video button modal
		//
		$.fn.colorbox.settings.opacity = 0.28;
		$('a.btn-video').colorbox({ initialWidth: 100, initialHeight: 100, transition: 'elastic' });
		
		// Share links
		//
		$('a.share-facebook, a.share-twitter').click(
			function ()
			{
				$this.utils.showShareWindow($(this));
				return false;
			}
		);
		
		// External Links
		//
		$("a[rel='external']").click(
			function () 
			{ 
				window.open($(this).attr('href')); 
				return false; 
			}
		);
		
		// Tool installation hiding/showing
		//
		$('.tool-installation').hide();
		$('h4.tool-installation-trigger').click(function ()
		{
			$(this).toggleClass('open').find('~ .tool-installation').slideToggle(200);
			return false;
		});
		
		// Tool Icons - Don't let them click and launch the BM
		//
		$('a.tool-icon').click(function ()
		{
			var data = {},
				x = $(this).offset().left - 35,
				y = $(this).offset().top - 55;

			if (this.isIE)
			{
				data = {
					'msg': "To start using this bookmarklet, right-click and select 'Add To Favorites...' to save this link to your browser's 'Links' toolbar.",
					'coords': {
						'x': x,
						'y': y
					},
					'timeout': 7000
				};
			}
			else 
			{
				data = {
					'msg': "To start using this bookmarklet, drag this link to your browser's bookmarks toolbar.",
					'coords': {
						'x': x,
						'y': y
					},
					'timeout': 4000
				};
			}
			$this.utils.alertTip(data);
			return false;
		});
	},
	
	// "Stay in the Loop" form for users to input their email to be updated on Tools news
	//
	updatesForm: {	
		init: function ()
		{
			var $this = GradeGuru.tools;
			
			$('#emailAddress').smartinput();
			$('#footer-email-updates').submit(
				function ()
				{
					if ($this.utils.emailIsValid($('#emailAddress').val()))
					{
						jQuery.ajax(
							{
								type: "POST",
								url: $this.urls.updatesURL,
								data: 'address=' + $('#emailAddress').val(),
								success: function (data)
								{
									$('#emailAddress').val('').blur();
									$('#form-msg').text("Thanks, we'll keep you updated").attr('class', 'confirm');

									setTimeout(
										function () 
										{
											$('#form-msg').text('');
										}, 
										3000);
								},
								
								error: function ()
								{
									alert('Sorry, there was an error sending your address. Please try again');
								}
							}
						);
					}
					else
					{
						$('#form-msg').text('Invalid Email').attr('class', 'error');
					}
					return false;
				}
			);
		}
	},
	
	// Suggest a tool idea form
	//
	suggestForm: {
		// Default text for each field is stored here
		// we use this to test against while validating the form
		//
		defaults: {
			name: '',
			email: '',
			message: ''
		},
		
		init: function ()
		{
			var $this = GradeGuru.tools,
				defaults = $this.suggestForm.defaults;
			
			$('#tool-suggest-form p input, #tool-suggest-form textarea').smartinput({
				focusAction: function (e)
				{
					e.removeClass('error');
				}
			});
			
			// Store the default text of each input
			//
			defaults.name = $('#suggest-name').val();
			defaults.email = $('#suggest-email').val();
			defaults.message = $('#suggest-msg').val();
			
			
			$('#tool-suggest-form').submit(
				function ()
				{
					// Test that each field is not the default
					// TODO: Be a little smarter about this?
					//
					var errors = 0,
						query = [],
						data;
					
					// Testing name
					if ($('#suggest-name').val() === defaults.name)
					{
						$('#suggest-name').addClass('error');
						errors += 1;
					}
					else
					{
						query.push('name=' + $('#suggest-name').val());
					}
					
					// Testing Email address
					if ($('#suggest-email').val() === defaults.email)
					{
						$('#suggest-email').addClass('error');
						errors += 1;
					}
					else if (!$this.utils.emailIsValid($('#suggest-email').val()))
					{
						$('#suggest-email').addClass('error');
						errors += 1;
					}
					else
					{
						query.push('email=' + $('#suggest-email').val());
					}
					
					// Testing message
					if ($('#suggest-msg').val() === defaults.message)
					{
						$('#suggest-msg').addClass('error');
						errors += 1;
					}
					else
					{
						query.push('message=' + $('#suggest-msg').val());
					}
					
					
					// If we are error free, build and send the message
					//
					if (!errors)
					{
						data = query.join('&');
						
						$.ajax(
							{
								type: 'POST',
								url: $this.urls.suggestURL,
								data: data,
								success: function (data)
								{
									$("#tool-suggest-form input[type='text'], #tool-suggest-form textarea").val('').blur();
									$('#tool-suggest-form fieldset').prepend('<p id="confirmation">Thanks! We\'ll let you know if we use your idea.</p>');
									
									setTimeout(
										function ()
										{
											$('#confirmation').fadeOut('slow');
										}, 5000);
								},
								error: function ()
								{
									alert('Sorry, there was an error sending your idea. Please try again.');
								}
							}
						);
					}
					return false;
				}
			);
		}
	},
	
	utils: {
		
		/**
		 * Validate email addresses
		 * @return BOOL
		 */
		emailIsValid: function (address)
		{
			var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
			return reg.test(address);
		},
		
		/**
		 * Display our custom alert balloon
		 * @param data OBJ - {msg, coords:{x, y}}
		 *
		 */
		alertTip: function (data)
		{
			var $this = GradeGuru.tools,
				ieClass, 
				timeout;
			clearTimeout(timeout);

			$('div.tooltip').remove();

			ieClass = ($this.isIE) ? ' exploder' : '';
			$('body').append('<div class="tooltip' + ieClass + '" style="opacity:0;"><p>' + data.msg + '</p><span></span></div>');

			$('div.tooltip').css({'left': data.coords.x + 'px', 'top': (data.coords.y + 10) + 'px'})
				.animate({'opacity': 0.9, 'top': data.coords.y + 'px'}, 300);

			timeout = setTimeout(
							function () 
							{	
								$('div.tooltip').remove();
							}, 
							data.timeout);
		},
		
		/**
		 * Pop up window for social media share links
		 *
		 */
		showShareWindow: function (a)
		{	
			var u = a.attr('href');
			window.open(u, 'sharer', 'toolbar=0, status=0, width=795, height=550');
			return false;
		}
	}
}

$(document).ready(function ()
{	
	GradeGuru.tools.init();
});