$(document).ready(
	function()
	{
		$('#email-invite-form button').click(
			function()
			{
				var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

				if ($('#usersharemail').val() == "")
				{
					$('#error-message').html("Please enter at least one email address to continue");
					$('#error-message').show();
					$('#usersharemail').focus();
					return false;
				}
				else if ($('#share-email').val() == "" || !filter.test($.trim($('#share-email').val())))
				{
					$('#error-message').html("Please enter your email address to continue");
					$('#error-message').show();
					$('#share-email').focus();
					return false;
				}
				else
				{
					var emails = $('textarea[name=usersharemail]').val().trim().split(/[\s,;\n]+/);

					for (var i = 0; i < emails.length; i++)
					{
						if (!filter.test($.trim(emails[i])))
						{
							$('#error-message').html("The email address " + $.trim(emails[i]) + " is invalid");
							$('#error-message').show();
							$('textarea[name=usersharemail]').focus();
							return false;
						}
					}
				}
			}
		);
		
		$('#invite-select-all').change(
			function()
			{
				if ($(this).is(':checked'))
				{
					$('#contacts-table > tbody').find("input").attr('checked', 'checked');
				}
				else
				{
					$('#contacts-table > tbody').find("input").removeAttr('checked');
				}
			}
		);
		
		$('#import-response button').click(
			function()
			{
				$('#import-response form').submit();
			}
		);
		
		$('#share-buttons li').click(
			function()
			{
				if ($(this).attr('id') != 'twitter')
				{
					$('#share-buttons li').removeClass('share-selected');
					$(this).addClass('share-selected');
					$('.share-form').hide();
					$('#error-message').hide();
					$('#' + $(this).attr('id') + '-form').show();
				}

				var vars = new Object();
				vars.uri = '/share - ' + $('div:last', this).html();

				$.post('/link/impression', vars);
			}
		);
		
		$('#import-form').submit(
			function()
			{
				vars = new Object();
				vars.email = $('#import-email').val();
				vars.password = $('#import-password').val();
				
				if ($('.share-selected').hasClass('linkedin'))
				{
					vars.linkedin = 1;
				}
				else if ($('.share-selected').hasClass('plaxo'))
				{
					vars.plaxo = 1;
				}

				$.post(
					'/user/share/import',
					vars,
					function(data)
					{
						if (data.status == "success")
						{
							$('#contacts-table > tbody').find("tr").remove();

							for (var i = 0; i < data.contacts.length; i++)
							{
								if (!data.contacts[i].email.match(/^(admin|dns|help|info|noreply|no-reply|privacy|sales|spam|support|webmaster|unsubscribe)@/i)
									&& !data.contacts[i].email.match(/^(unsub).+@$/i)
									&& !data.contacts[i].email.match(/@(facebook.com|craigslist.org|@reply.facebook.com)$/i)
									&& data.contacts[i].email.match(/\.(com|co|net|org|me|info|us|biz|ly|fm|tv|cc|edu|gov|mil)$/i))
								{
									$('#contacts-table > tbody').append("<tr><td><input type=\"checkbox\" name=\"contacts[]\" value=\"" + data.contacts[i].email + ":::" + data.contacts[i].name + "\"/></td><td>" + truncate(data.contacts[i].name, 28) + "</td><td>" + truncate(data.contacts[i].email, 28) + "</td></tr>");
								}
							}

							$('#contacts-table > tbody').find("input").change(
								function()
								{
									if (!$(this).is(":checked"))
									{
										$('#invite-select-all').removeAttr('checked');
									}
								}
							);

							$('#error-message').slideUp('normal', function(){ $('#error-message').html(''); });
							$('#import-email').val('');
							$('#import-password').val('');
							$('.share-form').hide();
							$('#import-response').show();
						}
						else
						{
							$('#error-message').html(data.message);
							$('#error-message').show();
						}
					},
					'json'
				);

				return false;
			}
		);
	
		$('#add-emails').click(
			function()
			{
				$('#import-response :checkbox:checked').each(
					function(i)
					{
						var checked_value = $(this).val();

						if (checked_value != 'on')
						{
							var email = checked_value.split(':::');
							email = email[0];

							// If there's already emails, append a comma
							if ($('#usersharemail').val() != '')
							{
								$('#usersharemail').val($('#usersharemail').val() + ', ');
							}

							// Appends the email
							$('#usersharemail').val($('#usersharemail').val() + email);
						}
					}
				);

				$('#import-response').hide();
				$('#email-invite-form').show();
				
				$('.share-button').removeClass('share-selected');
				$('#email-invite').addClass('share-selected');
				
				$('#invite-select-all').attr('checked', '');

				window.scrollTo(0, 200);
			}
		);

		// Clears out the error messages
		jQuery.validator.messages.email     = "";
		jQuery.validator.messages.digits    = "";
		jQuery.validator.messages.minlength = "";
		jQuery.validator.messages.maxlength = "";
		jQuery.validator.messages.required  = "";
		
		// Cancel button
		$('#register-cancel').click(
			function()
			{
				history.back();
			}
		);

		// Email PDF button is clicked
		$('#email-pdf').click(
			function()
			{
				$.post(
					'/pdf/send',
					$('#pdf').serialize(),
					function(data, status)
					{
						if (typeof(data.message) != 'undefined')
						{
							alert('Error: ' + data.message);
						}
						else if (status == 'success')
						{
						}
					},
					'json'
				);
			}
		);

		// Submit button is clicked
		$('form.form button.submit,form.form a.submit').live('click',
			function()
			{
				var form = $(this).parents('form.form').get();

				if ($(form).valid() == true)
				{
					document.body.style.cursor = 'wait';

					$('button', form).hide();

					// Copies any CKEditor data to the same named form element
					if (typeof(CKEDITOR) != 'undefined')
					{
						if (typeof(CKEDITOR.instances) != 'undefined')
						{
							for (var instance in CKEDITOR.instances)
							{
								var data = CKEDITOR.instances[instance].getData();

								if (data != '')
								{
									$('#' + instance).val(data);
								}
							}
						}
					}

					$.post(
						$(form).attr('action'),
						$(form).serialize(),
						function(data, status)
						{
							document.body.style.cursor = 'default';

							if (data.status != 'success' && typeof(data.message) != 'undefined')
							{
								alert('Error: ' + data.message);
								$('button', form).show();
							}
							else if (data.status == 'success')
							{
								if (typeof(data.message) != 'undefined')
								{
									$('input',    form).val('');
									$('select',   form).val('');
									$('textarea', form).val('');

									alert(data.message);

									$('button', form).show();
								}

								if (typeof(data.url) != 'undefined')
								{
									parent.location.href = data.url;
								}

								if (typeof(data.callback) != 'undefined')
								{
									window[data.callback](data);
									$('button', form).show();
								}
							}
							else
							{
								alert('Error: ' + data);
								$('button', form).show();
							}
						},
						'json'
					);
				}
			}
		);
		
		// Cancel button is clicked
		$('form.form button.cancel').click(
			function()
			{
				document.location.href = '/';
			}
		);

		// Copy field is hovered
		$('.copy-field').mouseenter(function()
		{
			$(this).focus();
			$(this).select();
		});
		
		$('.copy-field').mouseleave(function()
		{
			$(this).blur();
		});

		$('.new-feature').click(function(){
			$(this).slideUp();
		});

		$('form.form').submit(function(){
			return false;
		});

		$('table.table tr:odd').addClass('odd');

		// Track link impressions
		$('a.tracked').each(function(index, element)
		{
			var vars = new Object();
			vars.uri = $(this).attr('href');

			$.post('/link/impression', vars);
		});

		// Track link clicks
		$('a.tracked').click(function()
		{
			var vars = new Object();
			vars.uri = $(this).attr('href');
			
			$.post('/link/click', vars);
		});

		if ($('#load-lists').length == 1)
		{
			$.post(
				'/user/lists',
				false,
				function(data, status)
				{

				},
				'json'
			);
		}
	}
);

function disableEnterKey(e)
{
	var key;     
	
	if(window.event)
		key = window.event.keyCode; //IE
	else
		key = e.which; //firefox     

	return (key != 13);
}

function toggle(that, id)
{
	if ($(that).attr('src') == '/images/icons/add.png')
	{
		$(that).attr('src', '/images/icons/delete.png');
	}
	else
	{
		$(that).attr('src', '/images/icons/add.png');
	}

	$('#' + id).toggle();
}

function truncate(string, length, hover)
{
	if (string.length > length)
	{
		if (hover == true)
		{
			string = '<span title="' + string + '" style="cursor:help">' + string.substring(0, length) + '...</span>';
		}
		else
		{
			string = string.substring(0, length) + '...';
		}
	}

	return string;
}

function autoTab(element)
{
	if ($(element).val().length >= $(element).attr('maxlength'))
	{
		$(element).next().focus();
	}
}

function skipSurveyQuestion()
{
	vars                 = new Object();
	vars.entry_id        = $('#entry_id').val();
	vars.question_id     = $('#question_id').val();
	vars.question_weight = $('#question_weight').val();

	$.post(
		'/survey/next',
		vars,
		function(data)
		{
			$('#response').val('');

			if (data.status == 'success')
			{
				$('#survey .question').html(data.question['question']);
				$('#question_id').val(data.question['id']);
				$('#question_weight').val(data.question['weight']);
			}
			else
			{
				$.fn.colorbox.close();
			}
		},
		'json'
	);
}

function surveyResponseCallback(data)
{
	$('#response').val('');

	if (data.status == 'success' && typeof(data.question) != 'undefined' )
	{
		$('#survey .question').html(data.question['question']);
		$('#question_id').val(data.question['id']);
		$('#question_weight').val(data.question['weight']);
	}
	else
	{
		$.fn.colorbox.close();
	}
}

function formatVoucherNumber(voucher_number)
{
	return voucher_number.substring(0, 2) + '-' + voucher_number.substring(2, 6) + '-' + voucher_number.substring(6);
}

